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