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