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