e3c83a1256bd789ded46fb8378ba22f0dc232b20
[sfa.git] / sfa / plc / api.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4 ### $Id$
5 ### $URL$
6 #
7
8 import sys
9 import os
10 import traceback
11 import string
12 import xmlrpclib
13 from sfa.trust.auth import Auth
14 from sfa.util.config import *
15 from sfa.util.faults import *
16 from sfa.util.debug import *
17 from sfa.trust.rights import *
18 from sfa.trust.credential import *
19 from sfa.trust.certificate import *
20 from sfa.util.namespace import *
21 from sfa.util.api import *
22 from sfa.util.nodemanager import NodeManager
23 from sfa.util.sfalogging import *
24 try:
25     from collections import defaultdict
26 except:
27     class defaultdict(dict):
28         def __init__(self, default_factory=None, *a, **kw):
29             if (default_factory is not None and
30                 not hasattr(default_factory, '__call__')):
31                 raise TypeError('first argument must be callable')
32             dict.__init__(self, *a, **kw)
33             self.default_factory = default_factory
34         def __getitem__(self, key):
35             try:
36                 return dict.__getitem__(self, key)
37             except KeyError:
38                 return self.__missing__(key)
39         def __missing__(self, key):
40             if self.default_factory is None:
41                 raise KeyError(key)
42             self[key] = value = self.default_factory()
43             return value
44         def __reduce__(self):
45             if self.default_factory is None:
46                 args = tuple()
47             else:
48                 args = self.default_factory,
49             return type(self), args, None, None, self.items()
50         def copy(self):
51             return self.__copy__()
52         def __copy__(self):
53             return type(self)(self.default_factory, self)
54         def __deepcopy__(self, memo):
55             import copy
56             return type(self)(self.default_factory,
57                               copy.deepcopy(self.items()))
58         def __repr__(self):
59             return 'defaultdict(%s, %s)' % (self.default_factory,
60                                             dict.__repr__(self))
61
62
63 ## end of http://code.activestate.com/recipes/523034/ }}}
64
65
66 def list_to_dict(recs, key):
67     """
68     convert a list of dictionaries into a dictionary keyed on the 
69     specified dictionary key 
70     """
71     keys = [rec[key] for rec in recs]
72     return dict(zip(keys, recs))
73
74 class SfaAPI(BaseAPI):
75
76     # flat list of method names
77     import sfa.methods
78     methods = sfa.methods.all
79     
80     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", 
81                  methods='sfa.methods', peer_cert = None, interface = None, 
82                 key_file = None, cert_file = None, cache = None):
83         BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, \
84                          peer_cert=peer_cert, interface=interface, key_file=key_file, \
85                          cert_file=cert_file, cache=cache)
86  
87         self.encoding = encoding
88
89         from sfa.util.table import SfaTable
90         self.SfaTable = SfaTable
91         # Better just be documenting the API
92         if config is None:
93             return
94
95         # Load configuration
96         self.config = Config(config)
97         self.auth = Auth(peer_cert)
98         self.interface = interface
99         self.key_file = key_file
100         self.key = Keypair(filename=self.key_file)
101         self.cert_file = cert_file
102         self.cert = Certificate(filename=self.cert_file)
103         self.credential = None
104         # Initialize the PLC shell only if SFA wraps a myPLC
105         rspec_type = self.config.get_aggregate_type()
106         if (rspec_type == 'pl' or rspec_type == 'vini'):
107             self.plshell = self.getPLCShell()
108             self.plshell_version = "4.3"
109
110         self.hrn = self.config.SFA_INTERFACE_HRN
111         self.time_format = "%Y-%m-%d %H:%M:%S"
112         self.logger=get_sfa_logger()
113
114     def getPLCShell(self):
115         self.plauth = {'Username': self.config.SFA_PLC_USER,
116                        'AuthMethod': 'password',
117                        'AuthString': self.config.SFA_PLC_PASSWORD}
118
119
120         self.plshell_type = 'xmlrpc' 
121         # connect via xmlrpc
122         url = self.config.SFA_PLC_URL
123         shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
124         return shell
125
126     def getCredential(self):
127         if self.interface in ['registry']:
128             return self.getCredentialFromLocalRegistry()
129         else:
130             return self.getCredentialFromRegistry()
131     
132     def getCredentialFromRegistry(self):
133         """ 
134         Get our credential from a remote registry 
135         """
136         type = 'authority'
137         path = self.config.SFA_DATA_DIR
138         filename = ".".join([self.interface, self.hrn, type, "cred"])
139         cred_filename = path + os.sep + filename
140         try:
141             credential = Credential(filename = cred_filename)
142             return credential.save_to_string(save_parents=True)
143         except IOError:
144             from sfa.server.registry import Registries
145             registries = Registries(self)
146             registry = registries[self.hrn]
147             cert_string=self.cert.save_to_string(save_parents=True)
148             # get self credential
149             self_cred = registry.get_self_credential(cert_string, type, self.hrn)
150             # get credential
151             cred = registry.get_credential(self_cred, type, self.hrn)
152             
153             # save cred to file
154             Credential(string=cred).save_to_file(cred_filename, save_parents=True)
155             return cred
156
157     def getCredentialFromLocalRegistry(self):
158         """
159         Get our current credential directly from the local registry.
160         """
161
162         hrn = self.hrn
163         auth_hrn = self.auth.get_authority(hrn)
164     
165         # is this a root or sub authority
166         if not auth_hrn or hrn == self.config.SFA_INTERFACE_HRN:
167             auth_hrn = hrn
168         auth_info = self.auth.get_auth_info(auth_hrn)
169         table = self.SfaTable()
170         records = table.findObjects(hrn)
171         if not records:
172             raise RecordNotFound
173         record = records[0]
174         type = record['type']
175         object_gid = record.get_gid_object()
176         new_cred = Credential(subject = object_gid.get_subject())
177         new_cred.set_gid_caller(object_gid)
178         new_cred.set_gid_object(object_gid)
179         new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn) 
180         new_cred.set_pubkey(object_gid.get_pubkey()) 
181         
182         r1 = determine_rights(type, hrn)
183         new_cred.set_privileges(r1)
184
185         auth_kind = "authority,ma,sa"
186
187         new_cred.set_parent(self.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
188
189         new_cred.encode()
190         new_cred.sign()
191
192         return new_cred.save_to_string(save_parents=True)
193    
194
195     def loadCredential (self):
196         """
197         Attempt to load credential from file if it exists. If it doesnt get
198         credential from registry.
199         """
200
201         # see if this file exists
202         # XX This is really the aggregate's credential. Using this is easier than getting
203         # the registry's credential from iteslf (ssl errors).   
204         ma_cred_filename = self.config.SFA_DATA_DIR + os.sep + self.interface + self.hrn + ".ma.cred"
205         try:
206             self.credential = Credential(filename = ma_cred_filename)
207         except IOError:
208             self.credential = self.getCredentialFromRegistry()
209
210     ##
211     # Convert SFA fields to PLC fields for use when registering up updating
212     # registry record in the PLC database
213     #
214     # @param type type of record (user, slice, ...)
215     # @param hrn human readable name
216     # @param sfa_fields dictionary of SFA fields
217     # @param pl_fields dictionary of PLC fields (output)
218
219     def sfa_fields_to_pl_fields(self, type, hrn, record):
220
221         def convert_ints(tmpdict, int_fields):
222             for field in int_fields:
223                 if field in tmpdict:
224                     tmpdict[field] = int(tmpdict[field])
225
226         pl_record = {}
227         #for field in record:
228         #    pl_record[field] = record[field]
229  
230         if type == "slice":
231             if not "instantiation" in pl_record:
232                 pl_record["instantiation"] = "plc-instantiated"
233             pl_record["name"] = hrn_to_pl_slicename(hrn)
234             if "url" in record:
235                pl_record["url"] = record["url"]
236             if "description" in record:
237                 pl_record["description"] = record["description"]
238             if "expires" in record:
239                 pl_record["expires"] = int(record["expires"])
240
241         elif type == "node":
242             if not "hostname" in pl_record:
243                 if not "hostname" in record:
244                     raise MissingSfaInfo("hostname")
245                 pl_record["hostname"] = record["hostname"]
246             if not "model" in pl_record:
247                 pl_record["model"] = "geni"
248
249         elif type == "authority":
250             pl_record["login_base"] = hrn_to_pl_login_base(hrn)
251
252             if not "name" in pl_record:
253                 pl_record["name"] = hrn
254
255             if not "abbreviated_name" in pl_record:
256                 pl_record["abbreviated_name"] = hrn
257
258             if not "enabled" in pl_record:
259                 pl_record["enabled"] = True
260
261             if not "is_public" in pl_record:
262                 pl_record["is_public"] = True
263
264         return pl_record
265
266     def fill_record_pl_info(self, records):
267         """
268         Fill in the planetlab specific fields of a SFA record. This
269         involves calling the appropriate PLC method to retrieve the 
270         database record for the object.
271         
272         PLC data is filled into the pl_info field of the record.
273     
274         @param record: record to fill in field (in/out param)     
275         """
276         # get ids by type
277         node_ids, site_ids, slice_ids = [], [], [] 
278         person_ids, key_ids = [], []
279         type_map = {'node': node_ids, 'authority': site_ids,
280                     'slice': slice_ids, 'user': person_ids}
281                   
282         for record in records:
283             for type in type_map:
284                 if type == record['type']:
285                     type_map[type].append(record['pointer'])
286
287         # get pl records
288         nodes, sites, slices, persons, keys = {}, {}, {}, {}, {}
289         if node_ids:
290             node_list = self.plshell.GetNodes(self.plauth, node_ids)
291             nodes = list_to_dict(node_list, 'node_id')
292         if site_ids:
293             site_list = self.plshell.GetSites(self.plauth, site_ids)
294             sites = list_to_dict(site_list, 'site_id')
295         if slice_ids:
296             slice_list = self.plshell.GetSlices(self.plauth, slice_ids)
297             slices = list_to_dict(slice_list, 'slice_id')
298         if person_ids:
299             person_list = self.plshell.GetPersons(self.plauth, person_ids)
300             persons = list_to_dict(person_list, 'person_id')
301             for person in persons:
302                 key_ids.extend(persons[person]['key_ids'])
303
304         pl_records = {'node': nodes, 'authority': sites,
305                       'slice': slices, 'user': persons}
306
307         if key_ids:
308             key_list = self.plshell.GetKeys(self.plauth, key_ids)
309             keys = list_to_dict(key_list, 'key_id')
310
311         # fill record info
312         for record in records:
313             # records with pointer==-1 do not have plc info.
314             # for example, the top level authority records which are
315             # authorities, but not PL "sites"
316             if record['pointer'] == -1:
317                 continue
318            
319             for type in pl_records:
320                 if record['type'] == type:
321                     if record['pointer'] in pl_records[type]:
322                         record.update(pl_records[type][record['pointer']])
323                         break
324             # fill in key info
325             if record['type'] == 'user':
326                 pubkeys = [keys[key_id]['key'] for key_id in record['key_ids'] if key_id in keys] 
327                 record['keys'] = pubkeys
328
329         # fill in record hrns
330         records = self.fill_record_hrns(records)   
331  
332         return records
333
334     def fill_record_hrns(self, records):
335         """
336         convert pl ids to hrns
337         """
338
339         # get ids
340         slice_ids, person_ids, site_ids, node_ids = [], [], [], []
341         for record in records:
342             if 'site_id' in record:
343                 site_ids.append(record['site_id'])
344             if 'site_ids' in records:
345                 site_ids.extend(record['site_ids'])
346             if 'person_ids' in record:
347                 person_ids.extend(record['person_ids'])
348             if 'slice_ids' in record:
349                 slice_ids.extend(record['slice_ids'])
350             if 'node_ids' in record:
351                 node_ids.extend(record['node_ids'])
352
353         # get pl records
354         slices, persons, sites, nodes = {}, {}, {}, {}
355         if site_ids:
356             site_list = self.plshell.GetSites(self.plauth, site_ids, ['site_id', 'login_base'])
357             sites = list_to_dict(site_list, 'site_id')
358         if person_ids:
359             person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'email'])
360             persons = list_to_dict(person_list, 'person_id')
361         if slice_ids:
362             slice_list = self.plshell.GetSlices(self.plauth, slice_ids, ['slice_id', 'name'])
363             slices = list_to_dict(slice_list, 'slice_id')       
364         if node_ids:
365             node_list = self.plshell.GetNodes(self.plauth, node_ids, ['node_id', 'hostname'])
366             nodes = list_to_dict(node_list, 'node_id')
367        
368         # convert ids to hrns
369         for record in records:
370              
371             # get all relevant data
372             type = record['type']
373             pointer = record['pointer']
374             auth_hrn = self.hrn
375             login_base = ''
376             if pointer == -1:
377                 continue
378
379             if 'site_id' in record:
380                 site = sites[record['site_id']]
381                 login_base = site['login_base']
382                 record['site'] = ".".join([auth_hrn, login_base])
383             if 'person_ids' in record:
384                 emails = [persons[person_id]['email'] for person_id in record['person_ids'] \
385                           if person_id in  persons]
386                 usernames = [email.split('@')[0] for email in emails]
387                 person_hrns = [".".join([auth_hrn, login_base, username]) for username in usernames]
388                 record['persons'] = person_hrns 
389             if 'slice_ids' in record:
390                 slicenames = [slices[slice_id]['name'] for slice_id in record['slice_ids'] \
391                               if slice_id in slices]
392                 slice_hrns = [slicename_to_hrn(auth_hrn, slicename) for slicename in slicenames]
393                 record['slices'] = slice_hrns
394             if 'node_ids' in record:
395                 hostnames = [nodes[node_id]['hostname'] for node_id in record['node_ids'] \
396                              if node_id in nodes]
397                 node_hrns = [hostname_to_hrn(auth_hrn, login_base, hostname) for hostname in hostnames]
398                 record['nodes'] = node_hrns
399             if 'site_ids' in record:
400                 login_bases = [sites[site_id]['login_base'] for site_id in record['site_ids'] \
401                                if site_id in sites]
402                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
403                 record['sites'] = site_hrns
404
405         return records   
406
407     def fill_record_sfa_info(self, records):
408
409         def startswith(prefix, values):
410             return [value for value in values if value.startswith(prefix)]
411
412         # get person ids
413         person_ids = []
414         site_ids = []
415         for record in records:
416             person_ids.extend(record.get("person_ids", []))
417             site_ids.extend(record.get("site_ids", [])) 
418             if 'site_id' in record:
419                 site_ids.append(record['site_id']) 
420         
421         # get all pis from the sites we've encountered
422         # and store them in a dictionary keyed on site_id 
423         site_pis = {}
424         if site_ids:
425             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
426             pi_list = self.plshell.GetPersons(self.plauth, pi_filter, ['person_id', 'site_ids'])
427             for pi in pi_list:
428                 # we will need the pi's hrns also
429                 person_ids.append(pi['person_id'])
430                 
431                 # we also need to keep track of the sites these pis
432                 # belong to
433                 for site_id in pi['site_ids']:
434                     if site_id in site_pis:
435                         site_pis[site_id].append(pi)
436                     else:
437                         site_pis[site_id] = [pi]
438                  
439         # get sfa records for all records associated with these records.   
440         # we'll replace pl ids (person_ids) with hrns from the sfa records
441         # we obtain
442         
443         # get the sfa records
444         table = self.SfaTable()
445         person_list, persons = [], {}
446         person_list = table.find({'type': 'user', 'pointer': person_ids})
447         # create a hrns keyed on the sfa record's pointer.
448         # Its possible for  multiple records to have the same pointer so
449         # the dict's value will be a list of hrns.
450         persons = defaultdict(list)
451         for person in person_list:
452             persons[person['pointer']].append(person)
453
454         # get the pl records
455         pl_person_list, pl_persons = [], {}
456         pl_person_list = self.plshell.GetPersons(self.plauth, person_ids, ['person_id', 'roles'])
457         pl_persons = list_to_dict(pl_person_list, 'person_id')
458
459         # fill sfa info
460         for record in records:
461             # skip records with no pl info (top level authorities)
462             if record['pointer'] == -1:
463                 continue 
464             sfa_info = {}
465             type = record['type']
466             if (type == "slice"):
467                 # all slice users are researchers
468                 record['PI'] = []
469                 record['researcher'] = []
470                 for person_id in record['person_ids']:
471                     hrns = [person['hrn'] for person in persons[person_id]]
472                     record['researcher'].extend(hrns)                
473
474                 # pis at the slice's site
475                 pl_pis = site_pis[record['site_id']]
476                 pi_ids = [pi['person_id'] for pi in pl_pis]
477                 for person_id in pi_ids:
478                     hrns = [person['hrn'] for person in persons[person_id]]
479                     record['PI'].extend(hrns)
480                 
481             elif (type == "authority"):
482                 record['PI'] = []
483                 record['operator'] = []
484                 record['owner'] = []
485                 for pointer in record['person_ids']:
486                     if pointer not in persons or pointer not in pl_persons:
487                         # this means there is not sfa or pl record for this user
488                         continue   
489                     hrns = [person['hrn'] for person in persons[pointer]] 
490                     roles = pl_persons[pointer]['roles']   
491                     if 'pi' in roles:
492                         record['PI'].extend(hrns)
493                     if 'tech' in roles:
494                         record['operator'].extend(hrns)
495                     if 'admin' in roles:
496                         record['owner'].extend(hrns)
497                     # xxx TODO: OrganizationName
498             elif (type == "node"):
499                 sfa_info['dns'] = record.get("hostname", "")
500                 # xxx TODO: URI, LatLong, IP, DNS
501     
502             elif (type == "user"):
503                 sfa_info['email'] = record.get("email", "")
504                 # xxx TODO: PostalAddress, Phone
505             record.update(sfa_info)
506
507     def fill_record_info(self, records):
508         """
509         Given a SFA record, fill in the PLC specific and SFA specific
510         fields in the record. 
511         """
512         if not isinstance(records, list):
513             records = [records]
514
515         self.fill_record_pl_info(records)
516         self.fill_record_sfa_info(records)
517
518     def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
519         # get a list of the HRNs tht are members of the old and new records
520         if oldRecord:
521             oldList = oldRecord.get(listName, [])
522         else:
523             oldList = []     
524         newList = record.get(listName, [])
525
526         # if the lists are the same, then we don't have to update anything
527         if (oldList == newList):
528             return
529
530         # build a list of the new person ids, by looking up each person to get
531         # their pointer
532         newIdList = []
533         table = self.SfaTable()
534         records = table.find({'type': 'user', 'hrn': newList})
535         for rec in records:
536             newIdList.append(rec['pointer'])
537
538         # build a list of the old person ids from the person_ids field 
539         if oldRecord:
540             oldIdList = oldRecord.get("person_ids", [])
541             containerId = oldRecord.get_pointer()
542         else:
543             # if oldRecord==None, then we are doing a Register, instead of an
544             # update.
545             oldIdList = []
546             containerId = record.get_pointer()
547
548     # add people who are in the new list, but not the oldList
549         for personId in newIdList:
550             if not (personId in oldIdList):
551                 addFunc(self.plauth, personId, containerId)
552
553         # remove people who are in the old list, but not the new list
554         for personId in oldIdList:
555             if not (personId in newIdList):
556                 delFunc(self.plauth, personId, containerId)
557
558     def update_membership(self, oldRecord, record):
559         if record.type == "slice":
560             self.update_membership_list(oldRecord, record, 'researcher',
561                                         self.plshell.AddPersonToSlice,
562                                         self.plshell.DeletePersonFromSlice)
563         elif record.type == "authority":
564             # xxx TODO
565             pass
566
567
568
569 class ComponentAPI(BaseAPI):
570
571     def __init__(self, config = "/etc/sfa/sfa_config.py", encoding = "utf-8", methods='sfa.methods',
572                  peer_cert = None, interface = None, key_file = None, cert_file = None):
573
574         BaseAPI.__init__(self, config=config, encoding=encoding, methods=methods, peer_cert=peer_cert,
575                          interface=interface, key_file=key_file, cert_file=cert_file)
576         self.encoding = encoding
577
578         # Better just be documenting the API
579         if config is None:
580             return
581
582         self.nodemanager = NodeManager(self.config)
583
584     def sliver_exists(self):
585         sliver_dict = self.nodemanager.GetXIDs()
586         if slicename in sliver_dict.keys():
587             return True
588         else:
589             return False