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