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