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