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