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