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