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