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