Tabs vs. spaces.
[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
16 import logger
17 import tools
18
19 def start(options, conf):
20     logger.log("sliverauth plugin starting up...")
21
22 def SetSliverTag(plc, slice, tagname, value):
23     node_id = tools.node_id()
24     slivertags=plc.GetSliceTags({"name":slice,"node_id":node_id})
25     if len(slivertags)==0:
26         slivertag_id=plc.AddSliceTag(slice,tagname,value,node_id)
27     else:
28         slivertag_id=slivertags[0]['slice_tag_id']
29         plc.UpdateSliceTag(slivertag_id,value)
30
31 def GetSlivers(plc, data, conf):
32     if 'slivers' not in data:
33         logger.log("sliverauth: getslivers data lack's sliver information. IGNORING!")
34         return
35
36     random.seed(42)
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             d = [random.choice(string.letters) for x in xrange(32)]
48             hmac = "".join(d)
49             SetSliverTag(plc,sliver['name'],'hmac',hmac)
50
51         path = '/vservers/%s/etc/planetlab' % sliver['name']
52         if os.path.exists(path):
53             keyfile = '%s/key' % path 
54             oldhmac = ''
55             if os.path.exists(keyfile):
56                 f = open(keyfile,'r')
57                 oldhmac = f.read()
58                 f.close()
59
60             if oldhmac <> hmac:
61                 # create a temporary file in the vserver
62                 fd, name = tempfile.mkstemp('','key',path)
63                 os.write(fd,hmac)
64                 os.close(fd)
65                 if os.path.exists(keyfile):
66                     os.unlink(keyfile)
67                 os.rename(name,keyfile)
68
69             os.chmod(keyfile,0400)
70