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