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