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