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