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