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