the generic architecture had a serious flaw
[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, subject_obj, ref_obj, dbsession):
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(subject_obj, ref_obj.researcher, 'user', 'researcher', dbsession)
274         elif type=='authority' and hasattr(ref_obj,'pi'):
275             self.update_driver_relation(subject_obj,ref_obj.pi, 'user', 'pi', dbsession)
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, record_obj, hrns, target_type, relation_name, dbsession):
281         # locate the linked objects in our db
282         subject_type=record_obj.type
283         subject_id=record_obj.pointer
284         # get the 'pointer' field of all matching records
285         link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
286         # sqlalchemy returns named tuples for columns
287         link_ids = [ tuple.pointer for tuple in link_id_tuples ]
288         self.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
289
290     def Register(self, api, record_dict):
291     
292         dbsession=api.dbsession()
293         hrn, type = record_dict['hrn'], record_dict['type']
294         urn = hrn_to_urn(hrn,type)
295         # validate the type
296         if type not in ['authority', 'slice', 'node', 'user']:
297             raise UnknownSfaType(type) 
298         
299         # check if record_dict already exists
300         existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
301         if existing_records:
302             raise ExistingRecord(hrn)
303            
304         assert ('type' in record_dict)
305         # returns the right type of RegRecord according to type in record
306         record = make_record(dict=record_dict)
307         record.just_created()
308         record.authority = get_authority(record.hrn)
309         auth_info = api.auth.get_auth_info(record.authority)
310         pub_key = None
311         # make sure record has a gid
312         if not record.gid:
313             uuid = create_uuid()
314             pkey = Keypair(create=True)
315             if getattr(record,'keys',None):
316                 pub_key=record.keys
317                 # use only first key in record
318                 if isinstance(record.keys, types.ListType):
319                     pub_key = record.keys[0]
320                 pkey = convert_public_key(pub_key)
321     
322             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
323             gid = gid_object.save_to_string(save_parents=True)
324             record.gid = gid
325     
326         if isinstance (record, RegAuthority):
327             # update the tree
328             if not api.auth.hierarchy.auth_exists(hrn):
329                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
330     
331             # get the GID from the newly created authority
332             auth_info = api.auth.get_auth_info(hrn)
333             gid = auth_info.get_gid_object()
334             record.gid=gid.save_to_string(save_parents=True)
335
336             # locate objects for relationships
337             pi_hrns = getattr(record,'pi',None)
338             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
339
340         elif isinstance (record, RegSlice):
341             researcher_hrns = getattr(record,'researcher',None)
342             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
343         
344         elif isinstance (record, RegUser):
345             # create RegKey objects for incoming keys
346             if hasattr(record,'keys'): 
347                 logger.debug ("creating %d keys for user %s"%(len(record.keys),record.hrn))
348                 record.reg_keys = [ RegKey (key) for key in record.keys ]
349             
350         # update testbed-specific data if needed
351         pointer = api.driver.register (record.__dict__, hrn, pub_key)
352
353         record.pointer=pointer
354         dbsession.add(record)
355         dbsession.commit()
356     
357         # update membership for researchers, pis, owners, operators
358         self.update_driver_relations (record, record, dbsession)
359         
360         return record.get_gid_object().save_to_string(save_parents=True)
361     
362     def Update(self, api, record_dict):
363         dbsession=api.dbsession()
364         assert ('type' in record_dict)
365         new_record=make_record(dict=record_dict)
366         (type,hrn) = (new_record.type, new_record.hrn)
367         
368         # make sure the record exists
369         record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
370         if not record:
371             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
372         record.just_updated()
373     
374         # Use the pointer from the existing record, not the one that the user
375         # gave us. This prevents the user from inserting a forged pointer
376         pointer = record.pointer
377     
378         # is there a change in keys ?
379         new_key=None
380         if type=='user':
381             if getattr(new_record,'keys',None):
382                 new_key=new_record.keys
383                 if isinstance (new_key,types.ListType):
384                     new_key=new_key[0]
385
386         # take new_key into account
387         if new_key:
388             # update the openssl key and gid
389             pkey = convert_public_key(new_key)
390             uuid = create_uuid()
391             urn = hrn_to_urn(hrn,type)
392             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
393             gid = gid_object.save_to_string(save_parents=True)
394         
395         # xxx should do side effects from new_record to record
396         # not too sure how to do that
397         # not too big a deal with planetlab as the driver is authoritative, but...
398
399         # update native relations
400         if isinstance (record, RegSlice):
401             researcher_hrns = getattr(new_record,'researcher',None)
402             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
403
404         elif isinstance (record, RegAuthority):
405             pi_hrns = getattr(new_record,'pi',None)
406             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
407         
408         # update the PLC information that was specified with the record
409         # xxx oddly enough, without this useless statement, 
410         # record.__dict__ as received by the driver seems to be off
411         # anyway the driver should receive an object 
412         # (and then extract __dict__ itself if needed)
413         print "DO NOT REMOVE ME before driver.update, record=%s"%record
414         new_key_pointer = -1
415         try:
416            (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
417         except:
418            pass
419         if new_key and new_key_pointer:
420             record.reg_keys=[ RegKey (new_key, new_key_pointer)]
421             record.gid = gid
422
423         dbsession.commit()
424         # update membership for researchers, pis, owners, operators
425         self.update_driver_relations (record, new_record, dbsession)
426         
427         return 1 
428     
429     # expecting an Xrn instance
430     def Remove(self, api, xrn, origin_hrn=None):
431         dbsession=api.dbsession()
432         hrn=xrn.get_hrn()
433         type=xrn.get_type()
434         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
435         if type and type not in ['all', '*']:
436             request=request.filter_by(type=type)
437     
438         record = request.first()
439         if not record:
440             msg="Could not find hrn %s"%hrn
441             if type: msg += " type=%s"%type
442             raise RecordNotFound(msg)
443
444         type = record.type
445         if type not in ['slice', 'user', 'node', 'authority'] :
446             raise UnknownSfaType(type)
447
448         credential = api.getCredential()
449         registries = api.registries
450     
451         # Try to remove the object from the PLCDB of federated agg.
452         # This is attempted before removing the object from the local agg's PLCDB and sfa table
453         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
454             for registry in registries:
455                 if registry not in [api.hrn]:
456                     try:
457                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
458                     except:
459                         pass
460
461         # call testbed callback first
462         # IIUC this is done on the local testbed TOO because of the refreshpeer link
463         if not api.driver.remove(record.__dict__):
464             logger.warning("driver.remove failed")
465
466         # delete from sfa db
467         dbsession.delete(record)
468         dbsession.commit()
469     
470         return 1
471
472     # This is a PLC-specific thing, won't work with other platforms
473     def get_key_from_incoming_ip (self, api):
474         dbsession=api.dbsession()
475         # verify that the callers's ip address exist in the db and is an interface
476         # for a node in the db
477         (ip, port) = api.remote_addr
478         interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
479         if not interfaces:
480             raise NonExistingRecord("no such ip %(ip)s" % locals())
481         nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
482         if not nodes:
483             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
484         node = nodes[0]
485        
486         # look up the sfa record
487         record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
488         if not record:
489             raise RecordNotFound("node with pointer %s"%node['node_id'])
490         
491         # generate a new keypair and gid
492         uuid = create_uuid()
493         pkey = Keypair(create=True)
494         urn = hrn_to_urn(record.hrn, record.type)
495         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
496         gid = gid_object.save_to_string(save_parents=True)
497         record.gid = gid
498
499         # update the record
500         dbsession.commit()
501   
502         # attempt the scp the key
503         # and gid onto the node
504         # this will only work for planetlab based components
505         (kfd, key_filename) = tempfile.mkstemp() 
506         (gfd, gid_filename) = tempfile.mkstemp() 
507         pkey.save_to_file(key_filename)
508         gid_object.save_to_file(gid_filename, save_parents=True)
509         host = node['hostname']
510         key_dest="/etc/sfa/node.key"
511         gid_dest="/etc/sfa/node.gid" 
512         scp = "/usr/bin/scp" 
513         #identity = "/etc/planetlab/root_ssh_key.rsa"
514         identity = "/etc/sfa/root_ssh_key"
515         scp_options=" -i %(identity)s " % locals()
516         scp_options+="-o StrictHostKeyChecking=no " % locals()
517         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
518                          locals()
519         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
520                          locals()    
521
522         all_commands = [scp_key_command, scp_gid_command]
523         
524         for command in all_commands:
525             (status, output) = commands.getstatusoutput(command)
526             if status:
527                 raise Exception, output
528
529         for filename in [key_filename, gid_filename]:
530             os.unlink(filename)
531
532         return 1