dont forget to import genitable
[sfa.git] / sfa / methods / get_key.py
1 ### $Id:  $
2 ### $URL:  $
3 import os
4 import tempfile
5 import commands
6 from sfa.util.faults import *
7 from sfa.util.misc import *
8 from sfa.util.method import Method
9 from sfa.util.parameter import Parameter, Mixed
10 from sfa.trust.auth import Auth
11 from sfa.util.genitable import *
12
13 class get_key(Method):
14     """
15     Generate a new keypair and gid for requesting caller (component).     
16     @return 1 If successful  
17     """
18
19     interfaces = ['registry']
20     
21     accepts = []
22
23     returns = Parameter(int, "1 if successful, faults otherwise")
24     
25     def call(self):
26         # verify that the callers's ip address exist in the db and is an inteface
27         # for a node in the db
28         (ip, port) = self.api.remote_addr
29         interfaces = self.api.plshell.GetInterfaces(self.api.plauth, {'ip': ip}, ['node_id'])
30         if not interfaces:
31             raise NonExistingRecord("no such ip %(ip)s" % locals())
32         nodes = self.api.plshell.GetNodes(self.api.plauth, [interfaces[0]['node_id']], ['node_id', 'hostname'])
33         if not nodes:
34             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
35         node = nodes[0]
36        
37         # look up the sfa record
38         table = GeniTable()
39         records = table.find({'type': 'node', 'pointer': node['node_id']})
40         if not records:
41             raise RecordNotFound("pointer:" + str(node['node_id']))  
42         record = records[0]
43         
44         # generate a new keypair and gid
45         uuid = create_uuid()
46         pkey = Keypair(create=True)
47         gid_object = self.api.auth.hierarchy.create_gid(record['hrn'], uuid, pkey)
48         gid = gid_object.save_to_string(save_parents=True)
49         record['gid'] = gid
50         record.set_gid(gid)
51
52         # update the record
53         table.update(record)
54   
55         # attempt the scp the key
56         # this will only work for planetlab based compoenents
57         (fd, filename) = tempfile.mkstemp() 
58         pkey.save_to_file(filename)
59         host = node['hostname']
60         dest="/etc/sfa/nodekey.key" 
61         identity = "/etc/planetlab/root_ssh_key.pub"
62         scp_command = "scp -i %(identity)s %(filename)s root@%(host)s:%(dest)s" % locals()
63         (status, output) = commands(scp_command)
64         if status:
65             raise Exception, output
66         os.unlink(filename)
67
68         return 1