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