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