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