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