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