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