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