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