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