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