minor improvements with the hope that slivers across machines get different hmacs
[nodemanager.git] / plugins / sliverauth.py
1 #!/usr/bin/python -tt
2 # vim:set ts=4 sw=4 expandtab:
3 # NodeManager plugin to empower slivers to make API calls
4
5 """
6 Sliver authentication support for NodeManager.
7
8 """
9
10 import errno
11 import os
12 import random
13 import string
14 import tempfile
15 import time
16
17 import logger
18 import tools
19
20 def start(options, conf):
21     logger.log("sliverauth plugin starting up...")
22
23 def SetSliverTag(plc, slice, tagname, value):
24     node_id = tools.node_id()
25     slivertags=plc.GetSliceTags({"name":slice,"node_id":node_id,"tagname":tagname})
26     if len(slivertags)==0:
27         slivertag_id=plc.AddSliceTag(slice,tagname,value,node_id)
28     else:
29         slivertag_id=slivertags[0]['slice_tag_id']
30         plc.UpdateSliceTag(slivertag_id,value)
31
32 def GetSlivers(data, config, plc):
33     if 'slivers' not in data:
34         logger.log("sliverauth: getslivers data lack's sliver information. IGNORING!")
35         return
36
37     for sliver in data['slivers']:
38         found_hmac = False
39         for attribute in sliver['attributes']:
40             name = attribute.get('tagname',attribute.get('name',''))
41             if name == 'hmac':
42                 found_hmac = True
43                 hmac = attribute['value']
44                 break
45
46         if not found_hmac:
47             # XXX need a better random seed?!
48             random.seed(time.time())
49             d = [random.choice(string.letters) for x in xrange(32)]
50             hmac = "".join(d)
51             SetSliverTag(plc,sliver['name'],'hmac',hmac)
52             logger.log("sliverauth setting %s hmac" % sliver['name'])
53
54         path = '/vservers/%s/etc/planetlab' % sliver['name']
55         if os.path.exists(path):
56             keyfile = '%s/key' % path 
57             oldhmac = ''
58             if os.path.exists(keyfile):
59                 f = open(keyfile,'r')
60                 oldhmac = f.read()
61                 f.close()
62
63             if oldhmac <> hmac:
64                 # create a temporary file in the vserver
65                 fd, name = tempfile.mkstemp('','key',path)
66                 os.write(fd,hmac)
67                 os.close(fd)
68                 if os.path.exists(keyfile):
69                     os.unlink(keyfile)
70                 os.rename(name,keyfile)
71                 logger.log("sliverauth writing hmac to %s " % keyfile)
72
73             os.chmod(keyfile,0400)
74