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