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