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