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