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