Removed hard coded login in GET requests (OARrestapi).
[sfa.git] / sfa / managers / registry_manager_openstack.py
1 import types
2 import time 
3 # for get_key_from_incoming_ip
4 import tempfile
5 import os
6 import commands
7
8 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
9     UnknownSfaType, ExistingRecord, NonExistingRecord
10 from sfa.util.sfatime import utcparse, datetime_to_epoch
11 from sfa.util.prefixTree import prefixTree
12 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
13 from sfa.util.plxrn import hrn_to_pl_login_base
14 from sfa.util.version import version_core
15 from sfa.util.sfalogging import logger
16 from sfa.trust.gid import GID 
17 from sfa.trust.credential import Credential
18 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
19 from sfa.trust.gid import create_uuid
20 from sfa.storage.record import SfaRecord
21 from sfa.storage.table import SfaTable
22 from sfa.managers import registry_manager
23
24 class RegistryManager(registry_manager.RegistryManager):
25
26     def __init__ (self, config): pass
27
28     # The GENI GetVersion call
29     def GetVersion(self, api, options):
30         peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems() 
31                        if hrn != api.hrn])
32         xrn=Xrn(api.hrn)
33         return version_core({'interface':'registry',
34                              'hrn':xrn.get_hrn(),
35                              'urn':xrn.get_urn(),
36                              'peers':peers})
37     
38     def GetCredential(self, api, xrn, type, is_self=False):
39         # convert xrn to hrn     
40         if type:
41             hrn = urn_to_hrn(xrn)[0]
42         else:
43             hrn, type = urn_to_hrn(xrn)
44             
45         # Is this a root or sub authority
46         auth_hrn = api.auth.get_authority(hrn)
47         if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
48             auth_hrn = hrn
49         # get record info
50         auth_info = api.auth.get_auth_info(auth_hrn)
51         table = SfaTable()
52         records = table.findObjects({'type': type, 'hrn': hrn})
53         if not records:
54             raise RecordNotFound(hrn)
55         record = records[0]
56     
57         # verify_cancreate_credential requires that the member lists
58         # (researchers, pis, etc) be filled in
59         self.driver.augment_records_with_testbed_info (record)
60         if not self.driver.is_enabled (record):
61               raise AccountNotEnabled(": PlanetLab account %s is not enabled. Please contact your site PI" %(record['email']))
62     
63         # get the callers gid
64         # if this is a self cred the record's gid is the caller's gid
65         if is_self:
66             caller_hrn = hrn
67             caller_gid = record.get_gid_object()
68         else:
69             caller_gid = api.auth.client_cred.get_gid_caller() 
70             caller_hrn = caller_gid.get_hrn()
71         
72         object_hrn = record.get_gid_object().get_hrn()
73         rights = api.auth.determine_user_rights(caller_hrn, record)
74         # make sure caller has rights to this object
75         if rights.is_empty():
76             raise PermissionError(caller_hrn + " has no rights to " + record['name'])
77     
78         object_gid = GID(string=record['gid'])
79         new_cred = Credential(subject = object_gid.get_subject())
80         new_cred.set_gid_caller(caller_gid)
81         new_cred.set_gid_object(object_gid)
82         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
83         #new_cred.set_pubkey(object_gid.get_pubkey())
84         new_cred.set_privileges(rights)
85         new_cred.get_privileges().delegate_all_privileges(True)
86         if 'expires' in record:
87             date = utcparse(record['expires'])
88             expires = datetime_to_epoch(date)
89             new_cred.set_expiration(int(expires))
90         auth_kind = "authority,ma,sa"
91         # Parent not necessary, verify with certs
92         #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
93         new_cred.encode()
94         new_cred.sign()
95     
96         return new_cred.save_to_string(save_parents=True)
97     
98     
99     def Resolve(self, api, xrns, type=None, full=True):
100     
101         if not isinstance(xrns, types.ListType):
102             xrns = [xrns]
103             # try to infer type if not set and we get a single input
104             if not type:
105                 type = Xrn(xrns).get_type()
106         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
107         # load all known registry names into a prefix tree and attempt to find
108         # the longest matching prefix
109         # create a dict where key is a registry hrn and its value is a
110         # hrns at that registry (determined by the known prefix tree).  
111         xrn_dict = {}
112         registries = api.registries
113         tree = prefixTree()
114         registry_hrns = registries.keys()
115         tree.load(registry_hrns)
116         for xrn in xrns:
117             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
118             if registry_hrn not in xrn_dict:
119                 xrn_dict[registry_hrn] = []
120             xrn_dict[registry_hrn].append(xrn)
121             
122         records = [] 
123         for registry_hrn in xrn_dict:
124             # skip the hrn without a registry hrn
125             # XX should we let the user know the authority is unknown?       
126             if not registry_hrn:
127                 continue
128     
129             # if the best match (longest matching hrn) is not the local registry,
130             # forward the request
131             xrns = xrn_dict[registry_hrn]
132             if registry_hrn != api.hrn:
133                 credential = api.getCredential()
134                 interface = api.registries[registry_hrn]
135                 server_proxy = api.server_proxy(interface, credential)
136                 peer_records = server_proxy.Resolve(xrns, credential)
137                 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
138     
139         # try resolving the remaining unfound records at the local registry
140         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
141         # 
142         table = SfaTable()
143         local_records = table.findObjects({'hrn': local_hrns})
144         
145         if full:
146             # in full mode we get as much info as we can, which involves contacting the 
147             # testbed for getting implementation details about the record
148             self.driver.augment_records_with_testbed_info(local_records)
149             # also we fill the 'url' field for known authorities
150             # used to be in the driver code, sounds like a poorman thing though
151             def solve_neighbour_url (record):
152                 if not record['type'].startswith('authority'): return 
153                 hrn=record['hrn']
154                 for neighbour_dict in [ api.aggregates, api.registries ]:
155                     if hrn in neighbour_dict:
156                         record['url']=neighbour_dict[hrn].get_url()
157                         return 
158             [ solve_neighbour_url (record) for record in local_records ]
159                     
160         
161         
162         # convert local record objects to dicts
163         records.extend([dict(record) for record in local_records])
164         if type:
165             records = filter(lambda rec: rec['type'] in [type], records)
166     
167         if not records:
168             raise RecordNotFound(str(hrns))
169     
170         return records
171     
172     def List(self, api, xrn, origin_hrn=None):
173         hrn, type = urn_to_hrn(xrn)
174         # load all know registry names into a prefix tree and attempt to find
175         # the longest matching prefix
176         records = []
177         registries = api.registries
178         registry_hrns = registries.keys()
179         tree = prefixTree()
180         tree.load(registry_hrns)
181         registry_hrn = tree.best_match(hrn)
182        
183         #if there was no match then this record belongs to an unknow registry
184         if not registry_hrn:
185             raise MissingAuthority(xrn)
186         # if the best match (longest matching hrn) is not the local registry,
187         # forward the request
188         records = []    
189         if registry_hrn != api.hrn:
190             credential = api.getCredential()
191             interface = api.registries[registry_hrn]
192             server_proxy = api.server_proxy(interface, credential)
193             record_list = server_proxy.List(xrn, credential)
194             records = [SfaRecord(dict=record).as_dict() for record in record_list]
195         
196         # if we still have not found the record yet, try the local registry
197         if not records:
198             if not api.auth.hierarchy.auth_exists(hrn):
199                 raise MissingAuthority(hrn)
200     
201             table = SfaTable()
202             records = table.find({'authority': hrn})
203     
204         return records
205     
206     
207     def CreateGid(self, api, xrn, cert):
208         # get the authority
209         authority = Xrn(xrn=xrn).get_authority_hrn()
210         auth_info = api.auth.get_auth_info(authority)
211         if not cert:
212             pkey = Keypair(create=True)
213         else:
214             certificate = Certificate(string=cert)
215             pkey = certificate.get_pubkey()    
216         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
217         return gid.save_to_string(save_parents=True)
218     
219     ####################
220     # utility for handling relationships among the SFA objects 
221     # given that the SFA db does not handle this sort of relationsships
222     # it will rely on side-effects in the testbed to keep this persistent
223     
224     # subject_record describes the subject of the relationships
225     # ref_record contains the target values for the various relationships we need to manage
226     # (to begin with, this is just the slice x person relationship)
227     def update_relations (self, subject_record, ref_record):
228         type=subject_record['type']
229         if type=='slice':
230             self.update_relation(subject_record, 'researcher', ref_record.get('researcher'), 'user')
231         
232     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
233     # hrns is the list of hrns that should be linked to the subject from now on
234     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
235     def update_relation (self, sfa_record, field_key, hrns, target_type):
236         # locate the linked objects in our db
237         subject_type=sfa_record['type']
238         subject_id=sfa_record['pointer']
239         table = SfaTable()
240         link_sfa_records = table.find ({'type':target_type, 'hrn': hrns})
241         link_ids = [ rec.get('pointer') for rec in link_sfa_records ]
242         self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
243         
244
245     def Register(self, api, record):
246     
247         hrn, type = record['hrn'], record['type']
248         urn = hrn_to_urn(hrn,type)
249         # validate the type
250         if type not in ['authority', 'slice', 'node', 'user']:
251             raise UnknownSfaType(type) 
252         
253         # check if record already exists
254         table = SfaTable()
255         existing_records = table.find({'type': type, 'hrn': hrn})
256         if existing_records:
257             raise ExistingRecord(hrn)
258            
259         record = SfaRecord(dict = record)
260         record['authority'] = get_authority(record['hrn'])
261         auth_info = api.auth.get_auth_info(record['authority'])
262         pub_key = None
263         # make sure record has a gid
264         if 'gid' not in record:
265             uuid = create_uuid()
266             pkey = Keypair(create=True)
267             if 'keys' in record and record['keys']:
268                 pub_key=record['keys']
269                 # use only first key in record
270                 if isinstance(record['keys'], types.ListType):
271                     pub_key = record['keys'][0]
272                 pkey = convert_public_key(pub_key)
273     
274             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
275             gid = gid_object.save_to_string(save_parents=True)
276             record['gid'] = gid
277             record.set_gid(gid)
278     
279         if type in ["authority"]:
280             # update the tree
281             if not api.auth.hierarchy.auth_exists(hrn):
282                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
283     
284             # get the GID from the newly created authority
285             gid = auth_info.get_gid_object()
286             record.set_gid(gid.save_to_string(save_parents=True))
287
288         # update testbed-specific data if needed
289         pointer = self.driver.register (record, hrn, pub_key)
290
291         record.set_pointer(pointer)
292         record_id = table.insert(record)
293         record['record_id'] = record_id
294     
295         # update membership for researchers, pis, owners, operators
296         self.update_relations (record, record)
297         
298         return record.get_gid_object().save_to_string(save_parents=True)
299     
300     def Update(self, api, record_dict):
301         new_record = SfaRecord(dict = record_dict)
302         type = new_record['type']
303         hrn = new_record['hrn']
304         urn = hrn_to_urn(hrn,type)
305         table = SfaTable()
306         # make sure the record exists
307         records = table.findObjects({'type': type, 'hrn': hrn})
308         if not records:
309             raise RecordNotFound(hrn)
310         record = records[0]
311         record['last_updated'] = time.gmtime()
312     
313         # validate the type
314         if type not in ['authority', 'slice', 'node', 'user']:
315             raise UnknownSfaType(type) 
316
317         # Use the pointer from the existing record, not the one that the user
318         # gave us. This prevents the user from inserting a forged pointer
319         pointer = record['pointer']
320     
321         # is the a change in keys ?
322         new_key=None
323         if type=='user':
324             if 'keys' in new_record and new_record['keys']:
325                 new_key=new_record['keys']
326                 if isinstance (new_key,types.ListType):
327                     new_key=new_key[0]
328
329         # update the PLC information that was specified with the record
330         if not self.driver.update (record, new_record, hrn, new_key):
331             logger.warning("driver.update failed")
332     
333         # take new_key into account
334         if new_key:
335             # update the openssl key and gid
336             pkey = convert_public_key(new_key)
337             uuid = create_uuid()
338             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
339             gid = gid_object.save_to_string(save_parents=True)
340             record['gid'] = gid
341             record = SfaRecord(dict=record)
342             table.update(record)
343         
344         # update membership for researchers, pis, owners, operators
345         self.update_relations (record, new_record)
346         
347         return 1 
348     
349     # expecting an Xrn instance
350     def Remove(self, api, xrn, origin_hrn=None):
351     
352         table = SfaTable()
353         filter = {'hrn': xrn.get_hrn()}
354         hrn=xrn.get_hrn()
355         type=xrn.get_type()
356         if type and type not in ['all', '*']:
357             filter['type'] = type
358     
359         records = table.find(filter)
360         if not records: raise RecordNotFound(hrn)
361         record = records[0]
362         type = record['type']
363         
364         if type not in ['slice', 'user', 'node', 'authority'] :
365             raise UnknownSfaType(type)
366
367         credential = api.getCredential()
368         registries = api.registries
369     
370         # Try to remove the object from the PLCDB of federated agg.
371         # This is attempted before removing the object from the local agg's PLCDB and sfa table
372         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
373             for registry in registries:
374                 if registry not in [api.hrn]:
375                     try:
376                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
377                     except:
378                         pass
379
380         # call testbed callback first
381         # IIUC this is done on the local testbed TOO because of the refreshpeer link
382         if not self.driver.remove(record):
383             logger.warning("driver.remove failed")
384
385         # delete from sfa db
386         table.remove(record)
387     
388         return 1
389
390     # This is a PLC-specific thing...
391     def get_key_from_incoming_ip (self, api):
392         # verify that the callers's ip address exist in the db and is an interface
393         # for a node in the db
394         (ip, port) = api.remote_addr
395         interfaces = self.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
396         if not interfaces:
397             raise NonExistingRecord("no such ip %(ip)s" % locals())
398         nodes = self.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
399         if not nodes:
400             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
401         node = nodes[0]
402        
403         # look up the sfa record
404         table = SfaTable()
405         records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
406         if not records:
407             raise RecordNotFound("pointer:" + str(node['node_id']))  
408         record = records[0]
409         
410         # generate a new keypair and gid
411         uuid = create_uuid()
412         pkey = Keypair(create=True)
413         urn = hrn_to_urn(record['hrn'], record['type'])
414         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
415         gid = gid_object.save_to_string(save_parents=True)
416         record['gid'] = gid
417         record.set_gid(gid)
418
419         # update the record
420         table.update(record)
421   
422         # attempt the scp the key
423         # and gid onto the node
424         # this will only work for planetlab based components
425         (kfd, key_filename) = tempfile.mkstemp() 
426         (gfd, gid_filename) = tempfile.mkstemp() 
427         pkey.save_to_file(key_filename)
428         gid_object.save_to_file(gid_filename, save_parents=True)
429         host = node['hostname']
430         key_dest="/etc/sfa/node.key"
431         gid_dest="/etc/sfa/node.gid" 
432         scp = "/usr/bin/scp" 
433         #identity = "/etc/planetlab/root_ssh_key.rsa"
434         identity = "/etc/sfa/root_ssh_key"
435         scp_options=" -i %(identity)s " % locals()
436         scp_options+="-o StrictHostKeyChecking=no " % locals()
437         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
438                          locals()
439         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
440                          locals()    
441
442         all_commands = [scp_key_command, scp_gid_command]
443         
444         for command in all_commands:
445             (status, output) = commands.getstatusoutput(command)
446             if status:
447                 raise Exception, output
448
449         for filename in [key_filename, gid_filename]:
450             os.unlink(filename)
451
452         return 1