added get_server
[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         if creds and not isinstance(creds, list): 
183             creds = [creds]
184         delegated_creds = filter_creds_by_caller(creds, [self.hrn, self.hrn + '.slicemanager'])
185         if not delegated_creds:
186             return None
187         return delegated_creds[0]
188  
189     def __getCredential(self):
190         """ 
191         Get our credential from a remote registry 
192         """
193         from sfa.server.registry import Registries
194         registries = Registries()
195         registry = registries.get_server(self.hrn, self.key_file, self.cert_file)
196         cert_string=self.cert.save_to_string(save_parents=True)
197         # get self credential
198         self_cred = registry.GetSelfCredential(cert_string, self.hrn, 'authority')
199         # get credential
200         cred = registry.GetCredential(self_cred, self.hrn, 'authority')
201         return Credential(string=cred)
202
203     def __getCredentialRaw(self):
204         """
205         Get our current credential directly from the local registry.
206         """
207
208         hrn = self.hrn
209         auth_hrn = self.auth.get_authority(hrn)
210     
211         # is this a root or sub authority
212         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
213             auth_hrn = hrn
214         auth_info = self.auth.get_auth_info(auth_hrn)
215         table = self.SfaTable()
216         records = table.findObjects({'hrn': hrn, 'type': 'authority+sa'})
217         if not records:
218             raise RecordNotFound
219         record = records[0]
220         type = record['type']
221         object_gid = record.get_gid_object()
222         new_cred = Credential(subject = object_gid.get_subject())
223         new_cred.set_gid_caller(object_gid)
224         new_cred.set_gid_object(object_gid)
225         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
226         
227         r1 = determine_rights(type, hrn)
228         new_cred.set_privileges(r1)
229         new_cred.encode()
230         new_cred.sign()
231
232         return new_cred
233    
234
235     def loadCredential (self):
236         """
237         Attempt to load credential from file if it exists. If it doesnt get
238         credential from registry.
239         """
240
241         # see if this file exists
242         # XX This is really the aggregate's credential. Using this is easier than getting
243         # the registry's credential from iteslf (ssl errors).   
244         ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
245         try:
246             self.credential = Credential(filename = ma_cred_filename)
247         except IOError:
248             self.credential = self.getCredentialFromRegistry()
249
250
251
252     ##
253     # Convert SFA fields to PLC fields for use when registering up updating
254     # registry record in the PLC database
255     #
256     # @param type type of record (user, slice, ...)
257     # @param hrn human readable name
258     # @param sfa_fields dictionary of SFA fields
259     # @param pl_fields dictionary of PLC fields (output)
260
261     def sfa_fields_to_pl_fields(self, type, hrn, record):
262
263         def convert_ints(tmpdict, int_fields):
264             for field in int_fields:
265                 if field in tmpdict:
266                     tmpdict[field] = int(tmpdict[field])
267
268         pl_record = {}
269         #for field in record:
270         #    pl_record[field] = record[field]
271  
272         if type == "slice":
273             if not "instantiation" in pl_record:
274                 pl_record["instantiation"] = "plc-instantiated"
275             pl_record["name"] = hrn_to_pl_slicename(hrn)
276             if "url" in record:
277                pl_record["url"] = record["url"]
278             if "description" in record:
279                 pl_record["description"] = record["description"]
280             if "expires" in record:
281                 pl_record["expires"] = int(record["expires"])
282
283         elif type == "node":
284             if not "hostname" in pl_record:
285                 if not "hostname" in record:
286                     raise MissingSfaInfo("hostname")
287                 pl_record["hostname"] = record["hostname"]
288             if not "model" in pl_record:
289                 pl_record["model"] = "geni"
290
291         elif type == "authority":
292             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
293
294             if not "name" in pl_record:
295                 pl_record["name"] = hrn
296
297             if not "abbreviated_name" in pl_record:
298                 pl_record["abbreviated_name"] = hrn
299
300             if not "enabled" in pl_record:
301                 pl_record["enabled"] = True
302
303             if not "is_public" in pl_record:
304                 pl_record["is_public"] = True
305
306         return pl_record
307
308     def fill_record_pl_info(self, records):
309         """
310         Fill in the planetlab specific fields of a SFA record. This
311         involves calling the appropriate PLC method to retrieve the 
312         database record for the object.
313         
314         PLC data is filled into the pl_info field of the record.
315     
316         @param record: record to fill in field (in/out param)     
317         """
318         # get ids by type
319         node_ids, site_ids, slice_ids = [], [], [] 
320         person_ids, key_ids = [], []
321         type_map = {'node': node_ids, 'authority': site_ids,
322                     'slice': slice_ids, 'user': person_ids}
323                   
324         for record in records:
325             for type in type_map:
326                 if type == record['type']:
327                     type_map[type].append(record['pointer'])
328
329         # get pl records
330         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
331         if node_ids:
332             node_list = self.plshell.GetNodes(self.plauth, node_ids)
333             nodes = list_to_dict(node_list, 'node_id')
334         if site_ids:
335             site_list = self.plshell.GetSites(self.plauth, site_ids)
336             sites = list_to_dict(site_list, 'site_id')
337         if slice_ids:
338             slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
339             slices = list_to_dict(slice_list, 'slice_id')
340         if person_ids:
341             person_list = self.plshell.GetPersons(self.plauth, person_ids)
342             persons = list_to_dict(person_list, 'person_id')
343             for person in persons:
344                 key_ids.extend(persons[person]['key_ids'])
345
346         pl_records = {'node': nodes, 'authority': sites,
347                       'slice': slices, 'user': persons}
348
349         if key_ids:
350             key_list = self.plshell.GetKeys(self.plauth, key_ids)
351             keys = list_to_dict(key_list, 'key_id')
352
353         # fill record info
354         for record in records:
355             # records with pointer==-1 do not have plc info.
356             # for example, the top level authority records which are
357             # authorities, but not PL "sites"
358             if record['pointer'] == -1:
359                 continue
360            
361             for type in pl_records:
362                 if record['type'] == type:
363                     if record['pointer'] in pl_records[type]:
364                         record.update(pl_records[type][record['pointer']])
365                         break
366             # fill in key info
367             if record['type'] == 'user':
368                 if 'key_ids' not in record:
369                     logger.info("user record has no 'key_ids' - need to import from myplc ?")
370                 else:
371                     pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
372                     record['keys'] = pubkeys
373
374         # fill in record hrns
375         records = self.fill_record_hrns(records)   
376  
377         return records
378
379     def fill_record_hrns(self, records):
380         """
381         convert pl ids to hrns
382         """
383
384         # get ids
385         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
386         for record in records:
387             if 'site_id' in record:
388                 site_ids.append(record['site_id'])
389             if 'site_ids' in records:
390                 site_ids.extend(record['site_ids'])
391             if 'person_ids' in record:
392                 person_ids.extend(record['person_ids'])
393             if 'slice_ids' in record:
394                 slice_ids.extend(record['slice_ids'])
395             if 'node_ids' in record:
396                 node_ids.extend(record['node_ids'])
397
398         # get pl records
399         slices, persons, sites, nodes = {}, {}, {}, {}
400         if site_ids:
401             site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
402             sites = list_to_dict(site_list, 'site_id')
403         if person_ids:
404             person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
405             persons = list_to_dict(person_list, 'person_id')
406         if slice_ids:
407             slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
408             slices = list_to_dict(slice_list, 'slice_id')       
409         if node_ids:
410             node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
411             nodes = list_to_dict(node_list, 'node_id')
412        
413         # convert ids to hrns
414         for record in records:
415             # get all relevant data
416             type = record['type']
417             pointer = record['pointer']
418             auth_hrn = self.hrn
419             login_base = ''
420             if pointer == -1:
421                 continue
422
423             if 'site_id' in record:
424                 site = sites[record['site_id']]
425                 login_base = site['login_base']
426                 record['site'] = ".".join([auth_hrn, login_base])
427             if 'person_ids' in record:
428                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
429                           if person_id in  persons]
430                 usernames = [email.split('@')[0] for email in emails]
431                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
432                 record['persons'] = person_hrns 
433             if 'slice_ids' in record:
434                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
435                               if slice_id in slices]
436                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
437                 record['slices'] = slice_hrns
438             if 'node_ids' in record:
439                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
440                              if node_id in nodes]
441                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
442                 record['nodes'] = node_hrns
443             if 'site_ids' in record:
444                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
445                                if site_id in sites]
446                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
447                 record['sites'] = site_hrns
448             
449         return records   
450
451     def fill_record_sfa_info(self, records):
452
453         def startswith(prefix, values):
454             return [value for value in values if value.startswith(prefix)]
455
456         # get person ids
457         person_ids = []
458         site_ids = []
459         for record in records:
460             person_ids.extend(record.get("person_ids", []))
461             site_ids.extend(record.get("site_ids", [])) 
462             if 'site_id' in record:
463                 site_ids.append(record['site_id']) 
464         
465         # get all pis from the sites we've encountered
466         # and store them in a dictionary keyed on site_id 
467         site_pis = {}
468         if site_ids:
469             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
470             pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
471             for pi in pi_list:
472                 # we will need the pi's hrns also
473                 person_ids.append(pi['person_id'])
474                 
475                 # we also need to keep track of the sites these pis
476                 # belong to
477                 for site_id in pi['site_ids']:
478                     if site_id in site_pis:
479                         site_pis[site_id].append(pi)
480                     else:
481                         site_pis[site_id] = [pi]
482                  
483         # get sfa records for all records associated with these records.   
484         # we'll replace pl ids (person_ids) with hrns from the sfa records
485         # we obtain
486         
487         # get the sfa records
488         table = self.SfaTable()
489         person_list, persons = [], {}
490         person_list = table.find({'type': 'user', 'pointer': person_ids})
491         # create a hrns keyed on the sfa record's pointer.
492         # Its possible for  multiple records to have the same pointer so
493         # the dict's value will be a list of hrns.
494         persons = defaultdict(list)
495         for person in person_list:
496             persons[person['pointer']].append(person)
497
498         # get the pl records
499         pl_person_list, pl_persons = [], {}
500         pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
501         pl_persons = list_to_dict(pl_person_list, 'person_id')
502
503         # fill sfa info
504         for record in records:
505             # skip records with no pl info (top level authorities)
506             #if record['pointer'] == -1:
507             #    continue 
508             sfa_info = {}
509             type = record['type']
510             if (type == "slice"):
511                 # all slice users are researchers
512                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
513                 record['PI'] = []
514                 record['researcher'] = []
515                 for person_id in record.get('person_ids', []):
516                     hrns = [person['hrn'] for person in persons[person_id]]
517                     record['researcher'].extend(hrns)                
518
519                 # pis at the slice's site
520                 if 'site_id' in record and record['site_id'] in site_pis:
521                     pl_pis = site_pis[record['site_id']]
522                     pi_ids = [pi['person_id'] for pi in pl_pis]
523                     for person_id in pi_ids:
524                         hrns = [person['hrn'] for person in persons[person_id]]
525                         record['PI'].extend(hrns)
526                         record['geni_creator'] = record['PI'] 
527                 
528             elif (type.startswith("authority")):
529                 record['url'] = None
530                 if record['hrn'] in self.aggregates:
531                     
532                     record['url'] = self.aggregates[record['hrn']].get_url()
533
534                 if record['pointer'] != -1:
535                     record['PI'] = []
536                     record['operator'] = []
537                     record['owner'] = []
538                     for pointer in record.get('person_ids', []):
539                         if pointer not in persons or pointer not in pl_persons:
540                             # this means there is not sfa or pl record for this user
541                             continue   
542                         hrns = [person['hrn'] for person in persons[pointer]] 
543                         roles = pl_persons[pointer]['roles']   
544                         if 'pi' in roles:
545                             record['PI'].extend(hrns)
546                         if 'tech' in roles:
547                             record['operator'].extend(hrns)
548                         if 'admin' in roles:
549                             record['owner'].extend(hrns)
550                         # xxx TODO: OrganizationName
551             elif (type == "node"):
552                 sfa_info['dns'] = record.get("hostname", "")
553                 # xxx TODO: URI, LatLong, IP, DNS
554     
555             elif (type == "user"):
556                 sfa_info['email'] = record.get("email", "")
557                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
558                 sfa_info['geni_certificate'] = record['gid'] 
559                 # xxx TODO: PostalAddress, Phone
560             record.update(sfa_info)
561
562     def fill_record_info(self, records):
563         """
564         Given a SFA record, fill in the PLC specific and SFA specific
565         fields in the record. 
566         """
567         if not isinstance(records, list):
568             records = [records]
569
570         self.fill_record_pl_info(records)
571         self.fill_record_sfa_info(records)
572
573     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
574         # get a list of the HRNs tht are members of the old and new records
575         if oldRecord:
576             oldList = oldRecord.get(listName, [])
577         else:
578             oldList = []     
579         newList = record.get(listName, [])
580
581         # if the lists are the same, then we don't have to update anything
582         if (oldList == newList):
583             return
584
585         # build a list of the new person ids, by looking up each person to get
586         # their pointer
587         newIdList = []
588         table = self.SfaTable()
589         records = table.find({'type': 'user', 'hrn': newList})
590         for rec in records:
591             newIdList.append(rec['pointer'])
592
593         # build a list of the old person ids from the person_ids field 
594         if oldRecord:
595             oldIdList = oldRecord.get("person_ids", [])
596             containerId = oldRecord.get_pointer()
597         else:
598             # if oldRecord==None, then we are doing a Register, instead of an
599             # update.
600             oldIdList = []
601             containerId = record.get_pointer()
602
603     # add people who are in the new list, but not the oldList
604         for personId in newIdList:
605             if not (personId in oldIdList):
606                 addFunc(self.plauth, personId, containerId)
607
608         # remove people who are in the old list, but not the new list
609         for personId in oldIdList:
610             if not (personId in newIdList):
611                 delFunc(self.plauth, personId, containerId)
612
613     def update_membership(self, oldRecord, record):
614         if record.type == "slice":
615             self.update_membership_list(oldRecord, record, 'researcher',
616                                         self.plshell.AddPersonToSlice,
617                                         self.plshell.DeletePersonFromSlice)
618         elif record.type == "authority":
619             # xxx TODO
620             pass
621
622
623
624 class ComponentAPI(BaseAPI):
625
626     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
627                  peer_cert = None, interface = None, key_file = None, cert_file = None):
628
629         BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
630                          interface=interface, key_file=key_file, cert_file=cert_file)
631         self.encoding = encoding
632
633         # Better just be documenting the API
634         if config is None:
635             return
636
637         self.nodemanager = NodeManager(self.config)
638
639     def sliver_exists(self):
640         sliver_dict = self.nodemanager.GetXIDs()
641         if slicename in sliver_dict.keys():
642             return True
643         else:
644             return False
645
646     def get_registry(self):
647         addr, port = self.config.SFA_REGISTRY_HOST, self.config.SFA_REGISTRY_PORT
648         url = "http://%(addr)s:%(port)s" % locals()
649         server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
650         return server
651
652     def get_node_key(self):
653         # this call requires no authentication,
654         # so we can generate a random keypair here
655         subject="component"
656         (kfd, keyfile) = tempfile.mkstemp()
657         (cfd, certfile) = tempfile.mkstemp()
658         key = Keypair(create=True)
659         key.save_to_file(keyfile)
660         cert = Certificate(subject=subject)
661         cert.set_issuer(key=key, subject=subject)
662         cert.set_pubkey(key)
663         cert.sign()
664         cert.save_to_file(certfile)
665         registry = self.get_registry()
666         # the registry will scp the key onto the node
667         registry.get_key()        
668
669     def getCredential(self):
670         """
671         Get our credential from a remote registry
672         """
673         path = self.config.SFA_DATA_DIR
674         config_dir = self.config.config_path
675         cred_filename = path + os.sep + 'node.cred'
676         try:
677             credential = Credential(filename = cred_filename)
678             return credential.save_to_string(save_parents=True)
679         except IOError:
680             node_pkey_file = config_dir + os.sep + "node.key"
681             node_gid_file = config_dir + os.sep + "node.gid"
682             cert_filename = path + os.sep + 'server.cert'
683             if not os.path.exists(node_pkey_file) or \
684                not os.path.exists(node_gid_file):
685                 self.get_node_key()
686
687             # get node's hrn
688             gid = GID(filename=node_gid_file)
689             hrn = gid.get_hrn()
690             # get credential from registry
691             cert_str = Certificate(filename=cert_filename).save_to_string(save_parents=True)
692             registry = self.get_registry()
693             cred = registry.GetSelfCredential(cert_str, hrn, 'node')
694             Credential(string=cred).save_to_file(credfile, save_parents=True)            
695
696             return cred
697
698     def clean_key_cred(self):
699         """
700         remove the existing keypair and cred  and generate new ones
701         """
702         files = ["server.key", "server.cert", "node.cred"]
703         for f in files:
704             filepath = KEYDIR + os.sep + f
705             if os.path.isfile(filepath):
706                 os.unlink(f)
707
708         # install the new key pair
709         # GetCredential will take care of generating the new keypair
710         # and credential
711         self.get_node_key()
712         self.getCredential()
713
714