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