6049ebbd95ec02819e9e822e273ba417634a6079
[sfa.git] / sfa / managers / registry_manager.py
1 import types
2 # for get_key_from_incoming_ip
3 import tempfile
4 import os
5 import commands
6
7 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
8     UnknownSfaType, ExistingRecord, NonExistingRecord
9 from sfa.util.sfatime import utcparse, datetime_to_epoch
10 from sfa.util.prefixTree import prefixTree
11 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.version import version_core
13 from sfa.util.sfalogging import logger
14
15 from sfa.util.printable import printable
16
17 from sfa.trust.gid import GID 
18 from sfa.trust.credential import Credential
19 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
20 from sfa.trust.gid import create_uuid
21
22 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
23     augment_with_sfa_builtins
24 ### the types that we need to exclude from sqlobjects before being able to dump
25 # them on the xmlrpc wire
26 from sqlalchemy.orm.collections import InstrumentedList
27
28 ### historical note -- april 2014
29 # the myslice chaps rightfully complained about the following discrepancy
30 # they found that
31 # * read operations (resolve) expose stuff like e.g. 
32 #   'reg-researchers', or 'reg-pis', but that
33 # * write operations (register, update) need e.g. 
34 #   'researcher' or 'pi' to be set - reg-* are just ignored
35 #
36 # the '_normalize_input' helper functions below aim at ironing this out
37 # however in order to break as few code as possible we essentially make sure that *both* fields are set
38 # upon entering the write methods (so again register and update) for legacy, as some driver code
39 # might depend on the presence of, say, 'researcher'
40
41 # normalize an input record to a write method - register or update
42 # e.g. registry calls this 'reg-researchers'
43 # while some drivers call this 'researcher'
44 # we need to make sure that both keys appear and are the same
45 def _normalize_input (record, reg_key, driver_key):
46     # this looks right, use this for both keys
47     if reg_key in record:
48         # and issue a warning if they were both set and different
49         # as we're overwriting some user data here
50         if driver_key in record:
51             logger.warning ("normalize_input: incoming record has both values, using %s"%reg_key)
52         record[driver_key] = record[reg_key]
53     # we only have one key set, duplicate for the other one
54     elif driver_key in record:
55         logger.warning ("normalize_input: you should use '%s' instead of '%s'"%(reg_key,driver_key))
56         record[reg_key] = record[driver_key]
57
58 def normalize_input_record (record):
59     _normalize_input (record, 'reg-researchers','researcher')
60     _normalize_input (record, 'reg-pis','pi')
61     _normalize_input (record, 'reg-keys','keys')
62     # xxx the keys thing could use a little bit more attention:
63     # some parts of the code are using 'keys' while they should use 'reg-keys' 
64     # but I run out of time for now
65     if 'reg-keys' in record:
66         record['keys'] = record['reg-keys']
67     return record
68
69 class RegistryManager:
70
71     def __init__ (self, config): 
72         logger.info("Creating RegistryManager[%s]"%id(self))
73
74     # The GENI GetVersion call
75     def GetVersion(self, api, options):
76         peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems() 
77                        if hrn != api.hrn])
78         xrn=Xrn(api.hrn,type='authority')
79         return version_core({'interface':'registry',
80                              'sfa': 3,
81                              'hrn':xrn.get_hrn(),
82                              'urn':xrn.get_urn(),
83                              'peers':peers})
84     
85     def GetCredential(self, api, xrn, input_type, caller_xrn=None):
86         # convert xrn to hrn     
87         if input_type:
88             hrn, _ = urn_to_hrn(xrn)
89             type = input_type
90         else:
91             hrn, type = urn_to_hrn(xrn)
92
93         # Slivers don't have credentials but users should be able to 
94         # specify a sliver xrn and receive the slice's credential
95         # However if input_type is specified
96         if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
97             slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
98             hrn = slice_xrn.hrn 
99   
100         # Is this a root or sub authority
101         auth_hrn = api.auth.get_authority(hrn)
102         if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
103             auth_hrn = hrn
104         auth_info = api.auth.get_auth_info(auth_hrn)
105
106         # get record info
107         dbsession = api.dbsession()
108         record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
109         if not record:
110             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
111
112         # get the callers gid
113         # if caller_xrn is not specified assume the caller is the record
114         # object itself.
115         if not caller_xrn:
116             caller_hrn = hrn
117             caller_gid = record.get_gid_object()
118         else:
119             caller_hrn, caller_type = urn_to_hrn(caller_xrn)
120             if caller_type:
121                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
122             else:
123                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
124             if not caller_record:
125                 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
126             caller_gid = GID(string=caller_record.gid)
127  
128         object_hrn = record.get_gid_object().get_hrn()
129         # call the builtin authorization/credential generation engine
130         rights = api.auth.determine_user_rights(caller_hrn, record)
131         # make sure caller has rights to this object
132         if rights.is_empty():
133             raise PermissionError("%s has no rights to %s (%s)" % \
134                                   (caller_hrn, object_hrn, xrn))    
135         object_gid = GID(string=record.gid)
136         new_cred = Credential(subject = object_gid.get_subject())
137         new_cred.set_gid_caller(caller_gid)
138         new_cred.set_gid_object(object_gid)
139         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
140         #new_cred.set_pubkey(object_gid.get_pubkey())
141         new_cred.set_privileges(rights)
142         new_cred.get_privileges().delegate_all_privileges(True)
143         if hasattr(record,'expires'):
144             date = utcparse(record.expires)
145             expires = datetime_to_epoch(date)
146             new_cred.set_expiration(int(expires))
147         auth_kind = "authority,ma,sa"
148         # Parent not necessary, verify with certs
149         #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
150         new_cred.encode()
151         new_cred.sign()
152     
153         return new_cred.save_to_string(save_parents=True)
154     
155     
156     # the default for full, which means 'dig into the testbed as well', should be false
157     def Resolve(self, api, xrns, type=None, details=False):
158     
159         dbsession = api.dbsession()
160         if not isinstance(xrns, types.ListType):
161             # try to infer type if not set and we get a single input
162             if not type:
163                 type = Xrn(xrns).get_type()
164             xrns = [xrns]
165         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
166
167         # load all known registry names into a prefix tree and attempt to find
168         # the longest matching prefix
169         # create a dict where key is a registry hrn and its value is a list
170         # of hrns at that registry (determined by the known prefix tree).  
171         xrn_dict = {}
172         registries = api.registries
173         tree = prefixTree()
174         registry_hrns = registries.keys()
175         tree.load(registry_hrns)
176         for xrn in xrns:
177             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
178             if registry_hrn not in xrn_dict:
179                 xrn_dict[registry_hrn] = []
180             xrn_dict[registry_hrn].append(xrn)
181             
182         records = [] 
183         for registry_hrn in xrn_dict:
184             # skip the hrn without a registry hrn
185             # XX should we let the user know the authority is unknown?       
186             if not registry_hrn:
187                 continue
188     
189             # if the best match (longest matching hrn) is not the local registry,
190             # forward the request
191             xrns = xrn_dict[registry_hrn]
192             if registry_hrn != api.hrn:
193                 credential = api.getCredential()
194                 interface = api.registries[registry_hrn]
195                 server_proxy = api.server_proxy(interface, credential)
196                 # should propagate the details flag but that's not supported in the xmlrpc interface yet
197                 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
198                 peer_records = server_proxy.Resolve(xrns, credential)
199                 # pass foreign records as-is
200                 # previous code used to read
201                 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
202                 # not sure why the records coming through xmlrpc had to be processed at all
203                 records.extend(peer_records)
204     
205         # try resolving the remaining unfound records at the local registry
206         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
207         # 
208         local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
209         if type:
210             local_records = local_records.filter_by(type=type)
211         local_records=local_records.all()
212         
213         for local_record in local_records:
214             augment_with_sfa_builtins(local_record)
215
216         logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
217         local_dicts = [ record.__dict__ for record in local_records ]
218         
219         if details:
220             # in details mode we get as much info as we can, which involves contacting the 
221             # testbed for getting implementation details about the record
222             api.driver.augment_records_with_testbed_info(local_dicts)
223             # also we fill the 'url' field for known authorities
224             # used to be in the driver code, sounds like a poorman thing though
225             def solve_neighbour_url (record):
226                 if not record.type.startswith('authority'): return 
227                 hrn=record.hrn
228                 for neighbour_dict in [ api.aggregates, api.registries ]:
229                     if hrn in neighbour_dict:
230                         record.url=neighbour_dict[hrn].get_url()
231                         return 
232             for record in local_records: solve_neighbour_url (record)
233         
234         # convert local record objects to dicts for xmlrpc
235         # xxx somehow here calling dict(record) issues a weird error
236         # however record.todict() seems to work fine
237         # records.extend( [ dict(record) for record in local_records ] )
238         records.extend( [ record.todict(exclude_types=(InstrumentedList,)) for record in local_records ] )
239
240         if not records:
241             raise RecordNotFound(str(hrns))
242     
243         return records
244     
245     def List (self, api, xrn, origin_hrn=None, options=None):
246         if options is None: options={}
247         dbsession = api.dbsession()
248         # load all know registry names into a prefix tree and attempt to find
249         # the longest matching prefix
250         hrn, type = urn_to_hrn(xrn)
251         registries = api.registries
252         registry_hrns = registries.keys()
253         tree = prefixTree()
254         tree.load(registry_hrns)
255         registry_hrn = tree.best_match(hrn)
256        
257         #if there was no match then this record belongs to an unknow registry
258         if not registry_hrn:
259             raise MissingAuthority(xrn)
260         # if the best match (longest matching hrn) is not the local registry,
261         # forward the request
262         record_dicts = []    
263         if registry_hrn != api.hrn:
264             credential = api.getCredential()
265             interface = api.registries[registry_hrn]
266             server_proxy = api.server_proxy(interface, credential)
267             record_list = server_proxy.List(xrn, credential, options)
268             # same as above, no need to process what comes from through xmlrpc
269             # pass foreign records as-is
270             record_dicts = record_list
271         
272         # if we still have not found the record yet, try the local registry
273 #        logger.debug("before trying local records, %d foreign records"% len(record_dicts))
274         if not record_dicts:
275             recursive = False
276             if ('recursive' in options and options['recursive']):
277                 recursive = True
278             elif hrn.endswith('*'):
279                 hrn = hrn[:-1]
280                 recursive = True
281
282             if not api.auth.hierarchy.auth_exists(hrn):
283                 raise MissingAuthority(hrn)
284             if recursive:
285                 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
286 #                logger.debug("recursive mode, found %d local records"%(len(records)))
287             else:
288                 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
289 #                logger.debug("non recursive mode, found %d local records"%(len(records)))
290             # so that sfi list can show more than plain names...
291             for record in records:
292                 # xxx mystery - again this useless statement is key here so that
293                 # resulting records have their __dict__ field actually in line with the
294                 # object's contents; was first observed with authorities' 'name' column
295                 # that would be missing from result as received by client
296                 # record.todict() is the place where __dict__ is used
297                 print "DO NOT REMOVE ME before augment_with_sfa_builtins, record=%s"%record
298                 augment_with_sfa_builtins(record)
299             record_dicts = [ record.todict(exclude_types=(InstrumentedList,)) for record in records ]
300     
301         return record_dicts
302     
303     def CreateGid(self, api, xrn, cert):
304         # get the authority
305         authority = Xrn(xrn=xrn).get_authority_hrn()
306         auth_info = api.auth.get_auth_info(authority)
307         if not cert:
308             pkey = Keypair(create=True)
309         else:
310             certificate = Certificate(string=cert)
311             pkey = certificate.get_pubkey()    
312
313         # Add the email of the user to SubjectAltName in the GID
314         email = None
315         hrn = Xrn(xrn).get_hrn()
316         dbsession = api.dbsession()
317         record=dbsession.query(RegUser).filter_by(hrn=hrn).first()
318         if record:
319             email = getattr(record,'email',None)
320         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey, email=email)
321         return gid.save_to_string(save_parents=True)
322     
323     ####################
324     # utility for handling relationships among the SFA objects 
325     
326     # subject_record describes the subject of the relationships
327     # ref_record contains the target values for the various relationships we need to manage
328     # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
329     def update_driver_relations (self, api, subject_obj, ref_obj):
330         type=subject_obj.type
331         #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
332         if type=='slice' and hasattr(ref_obj,'researcher'):
333             self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
334         elif type=='authority' and hasattr(ref_obj,'pi'):
335             self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
336         
337     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
338     # hrns is the list of hrns that should be linked to the subject from now on
339     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
340     def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
341         dbsession = api.dbsession()
342         # locate the linked objects in our db
343         subject_type=record_obj.type
344         subject_id=record_obj.pointer
345         # get the 'pointer' field of all matching records
346         link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
347         # sqlalchemy returns named tuples for columns
348         link_ids = [ tuple.pointer for tuple in link_id_tuples ]
349         api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
350
351     def Register(self, api, record_dict):
352     
353         logger.debug("Register: entering with record_dict=%s"%printable(record_dict))
354         normalize_input_record (record_dict)
355         logger.debug("Register: normalized record_dict=%s"%printable(record_dict))
356
357         dbsession = api.dbsession()
358         hrn, type = record_dict['hrn'], record_dict['type']
359         urn = hrn_to_urn(hrn,type)
360         # validate the type
361         if type not in ['authority', 'slice', 'node', 'user']:
362             raise UnknownSfaType(type) 
363         
364         # check if record_dict already exists
365         existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
366         if existing_records:
367             raise ExistingRecord(hrn)
368            
369         assert ('type' in record_dict)
370         # returns the right type of RegRecord according to type in record
371         record = make_record(dict=record_dict)
372         record.just_created()
373         record.authority = get_authority(record.hrn)
374         auth_info = api.auth.get_auth_info(record.authority)
375         pub_key = None
376         # make sure record has a gid
377         if not record.gid:
378             uuid = create_uuid()
379             pkey = Keypair(create=True)
380             pub_key=getattr(record,'reg-keys',None)
381             if pub_key is not None:
382                 # use only first key in record
383                 if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0]
384                 pkey = convert_public_key(pub_key)
385     
386             email = getattr(record,'email',None)
387             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
388             gid = gid_object.save_to_string(save_parents=True)
389             record.gid = gid
390     
391         if isinstance (record, RegAuthority):
392             # update the tree
393             if not api.auth.hierarchy.auth_exists(hrn):
394                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
395     
396             # get the GID from the newly created authority
397             auth_info = api.auth.get_auth_info(hrn)
398             gid = auth_info.get_gid_object()
399             record.gid=gid.save_to_string(save_parents=True)
400
401             # locate objects for relationships
402             pi_hrns = getattr(record,'reg-pis',None)
403             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
404
405         elif isinstance (record, RegSlice):
406             researcher_hrns = getattr(record,'reg-researchers',None)
407             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
408         
409         elif isinstance (record, RegUser):
410             # create RegKey objects for incoming keys
411             if hasattr(record,'reg-keys'):
412                 keys=getattr(record,'reg-keys')
413                 # some people send the key as a string instead of a list of strings
414                 if isinstance(keys,types.StringTypes): keys=[keys]
415                 logger.debug ("creating %d keys for user %s"%(len(keys),record.hrn))
416                 record.reg_keys = [ RegKey (key) for key in keys ]
417             
418         # update testbed-specific data if needed
419         pointer = api.driver.register (record.__dict__, hrn, pub_key)
420
421         record.pointer=pointer
422         dbsession.add(record)
423         dbsession.commit()
424     
425         # update membership for researchers, pis, owners, operators
426         self.update_driver_relations (api, record, record)
427         
428         return record.get_gid_object().save_to_string(save_parents=True)
429     
430     def Update(self, api, record_dict):
431
432         logger.debug("Update: entering with record_dict=%s"%printable(record_dict))
433         normalize_input_record (record_dict)
434         logger.debug("Update: normalized record_dict=%s"%printable(record_dict))
435
436         dbsession = api.dbsession()
437         assert ('type' in record_dict)
438         new_record = make_record(dict=record_dict)
439         (type, hrn) = (new_record.type, new_record.hrn)
440         
441         # make sure the record exists
442         record = dbsession.query(RegRecord).filter_by(type=type, hrn=hrn).first()
443         if not record:
444             raise RecordNotFound("hrn={}, type={}".format(hrn, type))
445         record.just_updated()
446     
447         # Use the pointer from the existing record, not the one that the user
448         # gave us. This prevents the user from inserting a forged pointer
449         pointer = record.pointer
450
451         # is there a change in keys ?
452         new_key = None
453         if type == 'user':
454             if getattr(new_record, 'keys', None):
455                 new_key = new_record.keys
456                 if isinstance (new_key, types.ListType):
457                     new_key = new_key[0]
458
459         # take new_key into account
460         if new_key:
461             # update the openssl key and gid
462             pkey = convert_public_key(new_key)
463             uuid = create_uuid()
464             urn = hrn_to_urn(hrn,type)
465
466             email = getattr(new_record, 'email', None)
467             if email is None:
468                 email = getattr(record, 'email', None)
469             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email = email)
470             gid = gid_object.save_to_string(save_parents=True)
471         
472         # xxx should do side effects from new_record to record
473         # not too sure how to do that
474         # not too big a deal with planetlab as the driver is authoritative, but...
475
476         # update native relations
477         if isinstance(record, RegSlice):
478             researcher_hrns = getattr(new_record, 'reg-researchers', None)
479             if researcher_hrns is not None:
480                 record.update_researchers (researcher_hrns, dbsession)
481
482         elif isinstance(record, RegAuthority):
483             pi_hrns = getattr(new_record, 'reg-pis', None)
484             if pi_hrns is not None:
485                 record.update_pis(pi_hrns, dbsession)
486             name = getattr(new_record, 'name', None)
487             if name is not None:
488                 record.name = name
489
490         elif isinstance(record, RegUser):
491             email = getattr(new_record, 'email', None)
492             if email is not None:
493                 record.email = email
494         
495         # update the PLC information that was specified with the record
496         # xxx mystery: oddly enough, without this useless statement, 
497         # record.__dict__ as received by the driver seems to be off
498         # anyway the driver should receive an object 
499         # (and then extract __dict__ itself if needed)
500         print "DO NOT REMOVE ME before driver.update, record=%s"%record
501         new_key_pointer = -1
502         try:
503            (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
504         except:
505            pass
506         if new_key and new_key_pointer:
507             record.reg_keys = [ RegKey (new_key, new_key_pointer)]
508             record.gid = gid
509
510         dbsession.commit()
511         # update membership for researchers, pis, owners, operators
512         self.update_driver_relations(api, record, new_record)
513         
514         return 1 
515     
516     # expecting an Xrn instance
517     def Remove(self, api, xrn, origin_hrn=None):
518         dbsession = api.dbsession()
519         hrn=xrn.get_hrn()
520         type=xrn.get_type()
521         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
522         if type and type not in ['all', '*']:
523             request=request.filter_by(type=type)
524     
525         record = request.first()
526         if not record:
527             msg="Could not find hrn %s"%hrn
528             if type: msg += " type=%s"%type
529             raise RecordNotFound(msg)
530
531         type = record.type
532         if type not in ['slice', 'user', 'node', 'authority'] :
533             raise UnknownSfaType(type)
534
535         credential = api.getCredential()
536         registries = api.registries
537     
538         # Try to remove the object from the PLCDB of federated agg.
539         # This is attempted before removing the object from the local agg's PLCDB and sfa table
540         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
541             for registry in registries:
542                 if registry not in [api.hrn]:
543                     try:
544                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
545                     except:
546                         pass
547
548         # call testbed callback first
549         # IIUC this is done on the local testbed TOO because of the refreshpeer link
550         if not api.driver.remove(record.__dict__):
551             logger.warning("driver.remove failed")
552
553         # delete from sfa db
554         dbsession.delete(record)
555         dbsession.commit()
556     
557         return 1
558
559     # This is a PLC-specific thing, won't work with other platforms
560     def get_key_from_incoming_ip (self, api):
561         dbsession = api.dbsession()
562         # verify that the callers's ip address exist in the db and is an interface
563         # for a node in the db
564         (ip, port) = api.remote_addr
565         interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
566         if not interfaces:
567             raise NonExistingRecord("no such ip %(ip)s" % locals())
568         nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
569         if not nodes:
570             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
571         node = nodes[0]
572        
573         # look up the sfa record
574         record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
575         if not record:
576             raise RecordNotFound("node with pointer %s"%node['node_id'])
577         
578         # generate a new keypair and gid
579         uuid = create_uuid()
580         pkey = Keypair(create=True)
581         urn = hrn_to_urn(record.hrn, record.type)
582
583         email = getattr(record, 'email', None)
584         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey, email)
585         gid = gid_object.save_to_string(save_parents=True)
586         record.gid = gid
587
588         # update the record
589         dbsession.commit()
590   
591         # attempt the scp the key
592         # and gid onto the node
593         # this will only work for planetlab based components
594         (kfd, key_filename) = tempfile.mkstemp() 
595         (gfd, gid_filename) = tempfile.mkstemp() 
596         pkey.save_to_file(key_filename)
597         gid_object.save_to_file(gid_filename, save_parents=True)
598         host = node['hostname']
599         key_dest="/etc/sfa/node.key"
600         gid_dest="/etc/sfa/node.gid" 
601         scp = "/usr/bin/scp" 
602         #identity = "/etc/planetlab/root_ssh_key.rsa"
603         identity = "/etc/sfa/root_ssh_key"
604         scp_options=" -i %(identity)s " % locals()
605         scp_options+="-o StrictHostKeyChecking=no " % locals()
606         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
607                          locals()
608         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
609                          locals()    
610
611         all_commands = [scp_key_command, scp_gid_command]
612         
613         for command in all_commands:
614             (status, output) = commands.getstatusoutput(command)
615             if status:
616                 raise Exception, output
617
618         for filename in [key_filename, gid_filename]:
619             os.unlink(filename)
620
621         return 1