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