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