renamed sfaticket from util/ to trust/
[sfa.git] / sfa / plc / api.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4
5 import sys
6 import os
7 import traceback
8 import string
9 import datetime
10 import xmlrpclib
11
12 from sfa.util.faults import *
13 from sfa.util.api import *
14 from sfa.util.config import *
15 from sfa.util.sfalogging import logger
16 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
17 from sfa.trust.auth import Auth
18 from sfa.trust.rights import Right, Rights, determine_rights
19 from sfa.trust.credential import Credential,Keypair
20 from sfa.trust.certificate import Certificate
21 from sfa.util.xrn import get_authority, hrn_to_urn
22 from sfa.util.plxrn import hostname_to_hrn, hrn_to_pl_slicename, hrn_to_pl_slicename, slicename_to_hrn
23 from sfa.util.nodemanager import NodeManager
24 try:
25     from collections import defaultdict
26 except:
27     class defaultdict(dict):
28         def __init__(self, default_factory=None, *a, **kw):
29             if (default_factory is not None and
30                 not hasattr(default_factory, '__call__')):
31                 raise TypeError('first argument must be callable')
32             dict.__init__(self, *a, **kw)
33             self.default_factory = default_factory
34         def __getitem__(self, key):
35             try:
36                 return dict.__getitem__(self, key)
37             except KeyError:
38                 return self.__missing__(key)
39         def __missing__(self, key):
40             if self.default_factory is None:
41                 raise KeyError(key)
42             self[key] = value = self.default_factory()
43             return value
44         def __reduce__(self):
45             if self.default_factory is None:
46                 args = tuple()
47             else:
48                 args = self.default_factory,
49             return type(self), args, None, None, self.items()
50         def copy(self):
51             return self.__copy__()
52         def __copy__(self):
53             return type(self)(self.default_factory, self)
54         def __deepcopy__(self, memo):
55             import copy
56             return type(self)(self.default_factory,
57                               copy.deepcopy(self.items()))
58         def __repr__(self):
59             return 'defaultdict(%s, %s)' % (self.default_factory,
60                                             dict.__repr__(self))
61 ## end of http://code.activestate.com/recipes/523034/ }}}
62
63 def list_to_dict(recs, key):
64     """
65     convert a list of dictionaries into a dictionary keyed on the 
66     specified dictionary key 
67     """
68     keys = [rec[key] for rec in recs]
69     return dict(zip(keys, recs))
70
71 class SfaAPI(BaseAPI):
72
73     # flat list of method names
74     import sfa.methods
75     methods = sfa.methods.all
76     
77     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", 
78                  methods='sfa.methods', peer_cert = None, interface = None, 
79                 key_file = None, cert_file = None, cache = None):
80         BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
81                          peer_cert=peer_cert, interface=interface, key_file=key_file, \
82                          cert_file=cert_file, cache=cache)
83  
84         self.encoding = encoding
85         from sfa.util.table import SfaTable
86         self.SfaTable = SfaTable
87         # Better just be documenting the API
88         if config is None:
89             return
90
91         # Load configuration
92         self.config = Config(config)
93         self.auth = Auth(peer_cert)
94         self.interface = interface
95         self.key_file = key_file
96         self.key = Keypair(filename=self.key_file)
97         self.cert_file = cert_file
98         self.cert = Certificate(filename=self.cert_file)
99         self.credential = None
100         # Initialize the PLC shell only if SFA wraps a myPLC
101         rspec_type = self.config.get_aggregate_type()
102         if (rspec_type == 'pl' or rspec_type == 'vini' or \
103             rspec_type == 'eucalyptus' or rspec_type == 'max'):
104             self.plshell = self.getPLCShell()
105             self.plshell_version = "4.3"
106
107         self.hrn = self.config.SFA_INTERFACE_HRN
108         self.time_format = "%Y-%m-%d %H:%M:%S"
109
110     
111     def getPLCShell(self):
112         self.plauth = {'Username': self.config.SFA_PLC_USER,
113                        'AuthMethod': 'password',
114                        'AuthString': self.config.SFA_PLC_PASSWORD}
115
116         # The native shell (PLC.Shell.Shell) is more efficient than xmlrpc,
117         # but it leaves idle db connections open. use xmlrpc until we can figure
118         # out why PLC.Shell.Shell doesn't close db connection properly     
119         #try:
120         #    sys.path.append(os.path.dirname(os.path.realpath("/usr/bin/plcsh")))
121         #    self.plshell_type = 'direct'
122         #    import PLC.Shell
123         #    shell = PLC.Shell.Shell(globals = globals())
124         #except:
125         
126         self.plshell_type = 'xmlrpc' 
127         url = self.config.SFA_PLC_URL
128         shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
129         return shell
130
131     def get_server(self, interface, cred, timeout=30):
132         """
133         Returns a connection to the specified interface. Use the specified
134         credential to determine the caller and look for the caller's key/cert 
135         in the registry hierarchy cache. 
136         """       
137         from sfa.trust.hierarchy import Hierarchy
138         if not isinstance(cred, Credential):
139             cred_obj = Credential(string=cred)
140         else:
141             cred_obj = cred
142         caller_gid = cred_obj.get_gid_caller()
143         hierarchy = Hierarchy()
144         auth_info = hierarchy.get_auth_info(caller_gid.get_hrn())
145         key_file = auth_info.get_privkey_filename()
146         cert_file = auth_info.get_gid_filename()
147         server = interface.get_server(key_file, cert_file, timeout)
148         return server
149                
150         
151     def getCredential(self):
152         """
153         Return a valid credential for this interface. 
154         """
155         type = 'authority'
156         path = self.config.SFA_DATA_DIR
157         filename = ".".join([self.interface, self.hrn, type, "cred"])
158         cred_filename = path + os.sep + filename
159         cred = None
160         if os.path.isfile(cred_filename):
161             cred = Credential(filename = cred_filename)
162             # make sure cred isnt expired
163             if not cred.get_expiration or \
164                datetime.datetime.utcnow() < cred.get_expiration():    
165                 return cred.save_to_string(save_parents=True)
166
167         # get a new credential
168         if self.interface in ['registry']:
169             cred =  self.__getCredentialRaw()
170         else:
171             cred =  self.__getCredential()
172         cred.save_to_file(cred_filename, save_parents=True)
173
174         return cred.save_to_string(save_parents=True)
175
176
177     def getDelegatedCredential(self, creds):
178         """
179         Attempt to find a credential delegated to us in
180         the specified list of creds.
181         """
182         from sfa.trust.hierarchy import Hierarchy
183         if creds and not isinstance(creds, list): 
184             creds = [creds]
185         hierarchy = Hierarchy()
186                 
187         delegated_cred = None
188         for cred in creds:
189             if hierarchy.auth_exists(Credential(string=cred).get_gid_caller().get_hrn()):
190                 delegated_cred = cred
191                 break
192         return delegated_cred
193  
194     def __getCredential(self):
195         """ 
196         Get our credential from a remote registry 
197         """
198         from sfa.server.registry import Registries
199         registries = Registries()
200         registry = registries.get_server(self.hrn, self.key_file, self.cert_file)
201         cert_string=self.cert.save_to_string(save_parents=True)
202         # get self credential
203         self_cred = registry.GetSelfCredential(cert_string, self.hrn, 'authority')
204         # get credential
205         cred = registry.GetCredential(self_cred, self.hrn, 'authority')
206         return Credential(string=cred)
207
208     def __getCredentialRaw(self):
209         """
210         Get our current credential directly from the local registry.
211         """
212
213         hrn = self.hrn
214         auth_hrn = self.auth.get_authority(hrn)
215     
216         # is this a root or sub authority
217         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
218             auth_hrn = hrn
219         auth_info = self.auth.get_auth_info(auth_hrn)
220         table = self.SfaTable()
221         records = table.findObjects({'hrn': hrn, 'type': 'authority+sa'})
222         if not records:
223             raise RecordNotFound
224         record = records[0]
225         type = record['type']
226         object_gid = record.get_gid_object()
227         new_cred = Credential(subject = object_gid.get_subject())
228         new_cred.set_gid_caller(object_gid)
229         new_cred.set_gid_object(object_gid)
230         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
231         
232         r1 = determine_rights(type, hrn)
233         new_cred.set_privileges(r1)
234         new_cred.encode()
235         new_cred.sign()
236
237         return new_cred
238    
239
240     def loadCredential (self):
241         """
242         Attempt to load credential from file if it exists. If it doesnt get
243         credential from registry.
244         """
245
246         # see if this file exists
247         # XX This is really the aggregate's credential. Using this is easier than getting
248         # the registry's credential from iteslf (ssl errors).   
249         ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
250         try:
251             self.credential = Credential(filename = ma_cred_filename)
252         except IOError:
253             self.credential = self.getCredentialFromRegistry()
254
255
256
257     ##
258     # Convert SFA fields to PLC fields for use when registering up updating
259     # registry record in the PLC database
260     #
261     # @param type type of record (user, slice, ...)
262     # @param hrn human readable name
263     # @param sfa_fields dictionary of SFA fields
264     # @param pl_fields dictionary of PLC fields (output)
265
266     def sfa_fields_to_pl_fields(self, type, hrn, record):
267
268         def convert_ints(tmpdict, int_fields):
269             for field in int_fields:
270                 if field in tmpdict:
271                     tmpdict[field] = int(tmpdict[field])
272
273         pl_record = {}
274         #for field in record:
275         #    pl_record[field] = record[field]
276  
277         if type == "slice":
278             if not "instantiation" in pl_record:
279                 pl_record["instantiation"] = "plc-instantiated"
280             pl_record["name"] = hrn_to_pl_slicename(hrn)
281             if "url" in record:
282                pl_record["url"] = record["url"]
283             if "description" in record:
284                 pl_record["description"] = record["description"]
285             if "expires" in record:
286                 pl_record["expires"] = int(record["expires"])
287
288         elif type == "node":
289             if not "hostname" in pl_record:
290                 if not "hostname" in record:
291                     raise MissingSfaInfo("hostname")
292                 pl_record["hostname"] = record["hostname"]
293             if not "model" in pl_record:
294                 pl_record["model"] = "geni"
295
296         elif type == "authority":
297             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
298
299             if not "name" in pl_record:
300                 pl_record["name"] = hrn
301
302             if not "abbreviated_name" in pl_record:
303                 pl_record["abbreviated_name"] = hrn
304
305             if not "enabled" in pl_record:
306                 pl_record["enabled"] = True
307
308             if not "is_public" in pl_record:
309                 pl_record["is_public"] = True
310
311         return pl_record
312
313     def fill_record_pl_info(self, records):
314         """
315         Fill in the planetlab specific fields of a SFA record. This
316         involves calling the appropriate PLC method to retrieve the 
317         database record for the object.
318         
319         PLC data is filled into the pl_info field of the record.
320     
321         @param record: record to fill in field (in/out param)     
322         """
323         # get ids by type
324         node_ids, site_ids, slice_ids = [], [], [] 
325         person_ids, key_ids = [], []
326         type_map = {'node': node_ids, 'authority': site_ids,
327                     'slice': slice_ids, 'user': person_ids}
328                   
329         for record in records:
330             for type in type_map:
331                 if type == record['type']:
332                     type_map[type].append(record['pointer'])
333
334         # get pl records
335         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
336         if node_ids:
337             node_list = self.plshell.GetNodes(self.plauth, node_ids)
338             nodes = list_to_dict(node_list, 'node_id')
339         if site_ids:
340             site_list = self.plshell.GetSites(self.plauth, site_ids)
341             sites = list_to_dict(site_list, 'site_id')
342         if slice_ids:
343             slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
344             slices = list_to_dict(slice_list, 'slice_id')
345         if person_ids:
346             person_list = self.plshell.GetPersons(self.plauth, person_ids)
347             persons = list_to_dict(person_list, 'person_id')
348             for person in persons:
349                 key_ids.extend(persons[person]['key_ids'])
350
351         pl_records = {'node': nodes, 'authority': sites,
352                       'slice': slices, 'user': persons}
353
354         if key_ids:
355             key_list = self.plshell.GetKeys(self.plauth, key_ids)
356             keys = list_to_dict(key_list, 'key_id')
357
358         # fill record info
359         for record in records:
360             # records with pointer==-1 do not have plc info.
361             # for example, the top level authority records which are
362             # authorities, but not PL "sites"
363             if record['pointer'] == -1:
364                 continue
365            
366             for type in pl_records:
367                 if record['type'] == type:
368                     if record['pointer'] in pl_records[type]:
369                         record.update(pl_records[type][record['pointer']])
370                         break
371             # fill in key info
372             if record['type'] == 'user':
373                 if 'key_ids' not in record:
374                     logger.info("user record has no 'key_ids' - need to import from myplc ?")
375                 else:
376                     pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
377                     record['keys'] = pubkeys
378
379         # fill in record hrns
380         records = self.fill_record_hrns(records)   
381  
382         return records
383
384     def fill_record_hrns(self, records):
385         """
386         convert pl ids to hrns
387         """
388
389         # get ids
390         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
391         for record in records:
392             if 'site_id' in record:
393                 site_ids.append(record['site_id'])
394             if 'site_ids' in records:
395                 site_ids.extend(record['site_ids'])
396             if 'person_ids' in record:
397                 person_ids.extend(record['person_ids'])
398             if 'slice_ids' in record:
399                 slice_ids.extend(record['slice_ids'])
400             if 'node_ids' in record:
401                 node_ids.extend(record['node_ids'])
402
403         # get pl records
404         slices, persons, sites, nodes = {}, {}, {}, {}
405         if site_ids:
406             site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
407             sites = list_to_dict(site_list, 'site_id')
408         if person_ids:
409             person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
410             persons = list_to_dict(person_list, 'person_id')
411         if slice_ids:
412             slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
413             slices = list_to_dict(slice_list, 'slice_id')       
414         if node_ids:
415             node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
416             nodes = list_to_dict(node_list, 'node_id')
417        
418         # convert ids to hrns
419         for record in records:
420             # get all relevant data
421             type = record['type']
422             pointer = record['pointer']
423             auth_hrn = self.hrn
424             login_base = ''
425             if pointer == -1:
426                 continue
427
428             if 'site_id' in record:
429                 site = sites[record['site_id']]
430                 login_base = site['login_base']
431                 record['site'] = ".".join([auth_hrn, login_base])
432             if 'person_ids' in record:
433                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
434                           if person_id in  persons]
435                 usernames = [email.split('@')[0] for email in emails]
436                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
437                 record['persons'] = person_hrns 
438             if 'slice_ids' in record:
439                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
440                               if slice_id in slices]
441                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
442                 record['slices'] = slice_hrns
443             if 'node_ids' in record:
444                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
445                              if node_id in nodes]
446                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
447                 record['nodes'] = node_hrns
448             if 'site_ids' in record:
449                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
450                                if site_id in sites]
451                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
452                 record['sites'] = site_hrns
453             
454         return records   
455
456     def fill_record_sfa_info(self, records):
457
458         def startswith(prefix, values):
459             return [value for value in values if value.startswith(prefix)]
460
461         # get person ids
462         person_ids = []
463         site_ids = []
464         for record in records:
465             person_ids.extend(record.get("person_ids", []))
466             site_ids.extend(record.get("site_ids", [])) 
467             if 'site_id' in record:
468                 site_ids.append(record['site_id']) 
469         
470         # get all pis from the sites we've encountered
471         # and store them in a dictionary keyed on site_id 
472         site_pis = {}
473         if site_ids:
474             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
475             pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
476             for pi in pi_list:
477                 # we will need the pi's hrns also
478                 person_ids.append(pi['person_id'])
479                 
480                 # we also need to keep track of the sites these pis
481                 # belong to
482                 for site_id in pi['site_ids']:
483                     if site_id in site_pis:
484                         site_pis[site_id].append(pi)
485                     else:
486                         site_pis[site_id] = [pi]
487                  
488         # get sfa records for all records associated with these records.   
489         # we'll replace pl ids (person_ids) with hrns from the sfa records
490         # we obtain
491         
492         # get the sfa records
493         table = self.SfaTable()
494         person_list, persons = [], {}
495         person_list = table.find({'type': 'user', 'pointer': person_ids})
496         # create a hrns keyed on the sfa record's pointer.
497         # Its possible for  multiple records to have the same pointer so
498         # the dict's value will be a list of hrns.
499         persons = defaultdict(list)
500         for person in person_list:
501             persons[person['pointer']].append(person)
502
503         # get the pl records
504         pl_person_list, pl_persons = [], {}
505         pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
506         pl_persons = list_to_dict(pl_person_list, 'person_id')
507
508         # fill sfa info
509         for record in records:
510             # skip records with no pl info (top level authorities)
511             #if record['pointer'] == -1:
512             #    continue 
513             sfa_info = {}
514             type = record['type']
515             if (type == "slice"):
516                 # all slice users are researchers
517                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
518                 record['PI'] = []
519                 record['researcher'] = []
520                 for person_id in record.get('person_ids', []):
521                     hrns = [person['hrn'] for person in persons[person_id]]
522                     record['researcher'].extend(hrns)                
523
524                 # pis at the slice's site
525                 if 'site_id' in record and record['site_id'] in site_pis:
526                     pl_pis = site_pis[record['site_id']]
527                     pi_ids = [pi['person_id'] for pi in pl_pis]
528                     for person_id in pi_ids:
529                         hrns = [person['hrn'] for person in persons[person_id]]
530                         record['PI'].extend(hrns)
531                         record['geni_creator'] = record['PI'] 
532                 
533             elif (type.startswith("authority")):
534                 record['url'] = None
535                 if record['hrn'] in self.aggregates:
536                     
537                     record['url'] = self.aggregates[record['hrn']].get_url()
538
539                 if record['pointer'] != -1:
540                     record['PI'] = []
541                     record['operator'] = []
542                     record['owner'] = []
543                     for pointer in record.get('person_ids', []):
544                         if pointer not in persons or pointer not in pl_persons:
545                             # this means there is not sfa or pl record for this user
546                             continue   
547                         hrns = [person['hrn'] for person in persons[pointer]] 
548                         roles = pl_persons[pointer]['roles']   
549                         if 'pi' in roles:
550                             record['PI'].extend(hrns)
551                         if 'tech' in roles:
552                             record['operator'].extend(hrns)
553                         if 'admin' in roles:
554                             record['owner'].extend(hrns)
555                         # xxx TODO: OrganizationName
556             elif (type == "node"):
557                 sfa_info['dns'] = record.get("hostname", "")
558                 # xxx TODO: URI, LatLong, IP, DNS
559     
560             elif (type == "user"):
561                 sfa_info['email'] = record.get("email", "")
562                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
563                 sfa_info['geni_certificate'] = record['gid'] 
564                 # xxx TODO: PostalAddress, Phone
565             record.update(sfa_info)
566
567     def fill_record_info(self, records):
568         """
569         Given a SFA record, fill in the PLC specific and SFA specific
570         fields in the record. 
571         """
572         if not isinstance(records, list):
573             records = [records]
574
575         self.fill_record_pl_info(records)
576         self.fill_record_sfa_info(records)
577
578     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
579         # get a list of the HRNs that are members of the old and new records
580         if oldRecord:
581             oldList = oldRecord.get(listName, [])
582         else:
583             oldList = []     
584         newList = record.get(listName, [])
585         # ugly hack to see what's next
586         def normalize (value):
587             from types import StringTypes
588             from sfa.util.sfalogging import logger
589             if isinstance(value,StringTypes): return value
590             elif isinstance(value,dict): 
591                 newvalue=value['text']
592                 logger.info("Normalizing %s=>%s"%(value,newvalue))
593                 return newvalue
594         newList=[normalize(v) for v in newList]
595
596         # if the lists are the same, then we don't have to update anything
597         if (oldList == newList):
598             return
599
600         # build a list of the new person ids, by looking up each person to get
601         # their pointer
602         newIdList = []
603         table = self.SfaTable()
604         records = table.find({'type': 'user', 'hrn': newList})
605         for rec in records:
606             newIdList.append(rec['pointer'])
607
608         # build a list of the old person ids from the person_ids field 
609         if oldRecord:
610             oldIdList = oldRecord.get("person_ids", [])
611             containerId = oldRecord.get_pointer()
612         else:
613             # if oldRecord==None, then we are doing a Register, instead of an
614             # update.
615             oldIdList = []
616             containerId = record.get_pointer()
617
618     # add people who are in the new list, but not the oldList
619         for personId in newIdList:
620             if not (personId in oldIdList):
621                 addFunc(self.plauth, personId, containerId)
622
623         # remove people who are in the old list, but not the new list
624         for personId in oldIdList:
625             if not (personId in newIdList):
626                 delFunc(self.plauth, personId, containerId)
627
628     def update_membership(self, oldRecord, record):
629         if record.type == "slice":
630             self.update_membership_list(oldRecord, record, 'researcher',
631                                         self.plshell.AddPersonToSlice,
632                                         self.plshell.DeletePersonFromSlice)
633         elif record.type == "authority":
634             # xxx TODO
635             pass
636
637
638
639 class ComponentAPI(BaseAPI):
640
641     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
642                  peer_cert = None, interface = None, key_file = None, cert_file = None):
643
644         BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
645                          interface=interface, key_file=key_file, cert_file=cert_file)
646         self.encoding = encoding
647
648         # Better just be documenting the API
649         if config is None:
650             return
651
652         self.nodemanager = NodeManager(self.config)
653
654     def sliver_exists(self):
655         sliver_dict = self.nodemanager.GetXIDs()
656         if slicename in sliver_dict.keys():
657             return True
658         else:
659             return False
660
661     def get_registry(self):
662         addr, port = self.config.SFA_REGISTRY_HOST, self.config.SFA_REGISTRY_PORT
663         url = "http://%(addr)s:%(port)s" % locals()
664         server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
665         return server
666
667     def get_node_key(self):
668         # this call requires no authentication,
669         # so we can generate a random keypair here
670         subject="component"
671         (kfd, keyfile) = tempfile.mkstemp()
672         (cfd, certfile) = tempfile.mkstemp()
673         key = Keypair(create=True)
674         key.save_to_file(keyfile)
675         cert = Certificate(subject=subject)
676         cert.set_issuer(key=key, subject=subject)
677         cert.set_pubkey(key)
678         cert.sign()
679         cert.save_to_file(certfile)
680         registry = self.get_registry()
681         # the registry will scp the key onto the node
682         registry.get_key()        
683
684     def getCredential(self):
685         """
686         Get our credential from a remote registry
687         """
688         path = self.config.SFA_DATA_DIR
689         config_dir = self.config.config_path
690         cred_filename = path + os.sep + 'node.cred'
691         try:
692             credential = Credential(filename = cred_filename)
693             return credential.save_to_string(save_parents=True)
694         except IOError:
695             node_pkey_file = config_dir + os.sep + "node.key"
696             node_gid_file = config_dir + os.sep + "node.gid"
697             cert_filename = path + os.sep + 'server.cert'
698             if not os.path.exists(node_pkey_file) or \
699                not os.path.exists(node_gid_file):
700                 self.get_node_key()
701
702             # get node's hrn
703             gid = GID(filename=node_gid_file)
704             hrn = gid.get_hrn()
705             # get credential from registry
706             cert_str = Certificate(filename=cert_filename).save_to_string(save_parents=True)
707             registry = self.get_registry()
708             cred = registry.GetSelfCredential(cert_str, hrn, 'node')
709             Credential(string=cred).save_to_file(credfile, save_parents=True)            
710
711             return cred
712
713     def clean_key_cred(self):
714         """
715         remove the existing keypair and cred  and generate new ones
716         """
717         files = ["server.key", "server.cert", "node.cred"]
718         for f in files:
719             filepath = KEYDIR + os.sep + f
720             if os.path.isfile(filepath):
721                 os.unlink(f)
722
723         # install the new key pair
724         # GetCredential will take care of generating the new keypair
725         # and credential
726         self.get_node_key()
727         self.getCredential()
728
729