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