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