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