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