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