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