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