fix bug in get_aggregate_nodes()
[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.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.record import SfaRecord
23 from sfa.storage.table import SfaTable
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         # get record info
53         auth_info = api.auth.get_auth_info(auth_hrn)
54         table = SfaTable()
55         records = table.findObjects({'type': type, 'hrn': hrn})
56         if not records:
57             raise RecordNotFound(hrn)
58         record = records[0]
59     
60         # verify_cancreate_credential requires that the member lists
61         # (researchers, pis, etc) be filled in
62         self.driver.augment_records_with_testbed_info (record)
63         if not self.driver.is_enabled (record):
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)
77         # make sure caller has rights to this object
78         if rights.is_empty():
79             raise PermissionError("%s has no rights to %s (%s)" % \
80                                   (caller_hrn, object_hrn, xrn))    
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 'expires' in record:
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, type=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 type:
108                 type = Xrn(xrns).get_type()
109         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
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
113         # 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)
140                 records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
141     
142         # try resolving the remaining unfound records at the local registry
143         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
144         # 
145         table = SfaTable()
146         local_records = table.findObjects({'hrn': local_hrns})
147         
148         if full:
149             # in full mode we get as much info as we can, which involves contacting the 
150             # testbed for getting implementation details about the record
151             self.driver.augment_records_with_testbed_info(local_records)
152             # also we fill the 'url' field for known authorities
153             # used to be in the driver code, sounds like a poorman thing though
154             def solve_neighbour_url (record):
155                 if not record['type'].startswith('authority'): return 
156                 hrn=record['hrn']
157                 for neighbour_dict in [ api.aggregates, api.registries ]:
158                     if hrn in neighbour_dict:
159                         record['url']=neighbour_dict[hrn].get_url()
160                         return 
161             [ solve_neighbour_url (record) for record in local_records ]
162                     
163         
164         
165         # convert local record objects to dicts
166         records.extend([dict(record) for record in local_records])
167         if type:
168             records = filter(lambda rec: rec['type'] in [type], records)
169     
170         if not records:
171             raise RecordNotFound(str(hrns))
172     
173         return records
174     
175     def List(self, api, xrn, origin_hrn=None):
176         hrn, type = urn_to_hrn(xrn)
177         # load all know registry names into a prefix tree and attempt to find
178         # the longest matching prefix
179         records = []
180         registries = api.registries
181         registry_hrns = registries.keys()
182         tree = prefixTree()
183         tree.load(registry_hrns)
184         registry_hrn = tree.best_match(hrn)
185        
186         #if there was no match then this record belongs to an unknow registry
187         if not registry_hrn:
188             raise MissingAuthority(xrn)
189         # if the best match (longest matching hrn) is not the local registry,
190         # forward the request
191         records = []    
192         if registry_hrn != api.hrn:
193             credential = api.getCredential()
194             interface = api.registries[registry_hrn]
195             server_proxy = api.server_proxy(interface, credential)
196             record_list = server_proxy.List(xrn, credential)
197             records = [SfaRecord(dict=record).as_dict() for record in record_list]
198         
199         # if we still have not found the record yet, try the local registry
200         if not records:
201             if not api.auth.hierarchy.auth_exists(hrn):
202                 raise MissingAuthority(hrn)
203     
204             table = SfaTable()
205             records = table.find({'authority': hrn})
206     
207         return records
208     
209     
210     def CreateGid(self, api, xrn, cert):
211         # get the authority
212         authority = Xrn(xrn=xrn).get_authority_hrn()
213         auth_info = api.auth.get_auth_info(authority)
214         if not cert:
215             pkey = Keypair(create=True)
216         else:
217             certificate = Certificate(string=cert)
218             pkey = certificate.get_pubkey()    
219         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
220         return gid.save_to_string(save_parents=True)
221     
222     ####################
223     # utility for handling relationships among the SFA objects 
224     # given that the SFA db does not handle this sort of relationsships
225     # it will rely on side-effects in the testbed to keep this persistent
226     
227     # subject_record describes the subject of the relationships
228     # ref_record contains the target values for the various relationships we need to manage
229     # (to begin with, this is just the slice x person relationship)
230     def update_relations (self, subject_record, ref_record):
231         type=subject_record['type']
232         if type=='slice':
233             self.update_relation(subject_record, 'researcher', ref_record.get('researcher'), 'user')
234         
235     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
236     # hrns is the list of hrns that should be linked to the subject from now on
237     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
238     def update_relation (self, sfa_record, field_key, hrns, target_type):
239         # locate the linked objects in our db
240         subject_type=sfa_record['type']
241         subject_id=sfa_record['pointer']
242         table = SfaTable()
243         link_sfa_records = table.find ({'type':target_type, 'hrn': hrns})
244         link_ids = [ rec.get('pointer') for rec in link_sfa_records ]
245         self.driver.update_relation (subject_type, target_type, subject_id, link_ids)
246         
247
248     def Register(self, api, record):
249     
250         hrn, type = record['hrn'], record['type']
251         urn = hrn_to_urn(hrn,type)
252         # validate the type
253         if type not in ['authority', 'slice', 'node', 'user']:
254             raise UnknownSfaType(type) 
255         
256         # check if record already exists
257         table = SfaTable()
258         existing_records = table.find({'type': type, 'hrn': hrn})
259         if existing_records:
260             raise ExistingRecord(hrn)
261            
262         record = SfaRecord(dict = record)
263         record['authority'] = get_authority(record['hrn'])
264         auth_info = api.auth.get_auth_info(record['authority'])
265         pub_key = None
266         # make sure record has a gid
267         if 'gid' not in record:
268             uuid = create_uuid()
269             pkey = Keypair(create=True)
270             if 'keys' in record and record['keys']:
271                 pub_key=record['keys']
272                 # use only first key in record
273                 if isinstance(record['keys'], types.ListType):
274                     pub_key = record['keys'][0]
275                 pkey = convert_public_key(pub_key)
276     
277             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
278             gid = gid_object.save_to_string(save_parents=True)
279             record['gid'] = gid
280             record.set_gid(gid)
281     
282         if type in ["authority"]:
283             # update the tree
284             if not api.auth.hierarchy.auth_exists(hrn):
285                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
286     
287             # get the GID from the newly created authority
288             gid = auth_info.get_gid_object()
289             record.set_gid(gid.save_to_string(save_parents=True))
290
291         # update testbed-specific data if needed
292         pointer = self.driver.register (record, hrn, pub_key)
293
294         record.set_pointer(pointer)
295         record_id = table.insert(record)
296         record['record_id'] = record_id
297     
298         # update membership for researchers, pis, owners, operators
299         self.update_relations (record, record)
300         
301         return record.get_gid_object().save_to_string(save_parents=True)
302     
303     def Update(self, api, record_dict):
304         new_record = SfaRecord(dict = record_dict)
305         type = new_record['type']
306         hrn = new_record['hrn']
307         urn = hrn_to_urn(hrn,type)
308         table = SfaTable()
309         # make sure the record exists
310         records = table.findObjects({'type': type, 'hrn': hrn})
311         if not records:
312             raise RecordNotFound(hrn)
313         record = records[0]
314         record['last_updated'] = time.gmtime()
315     
316         # validate the type
317         if type not in ['authority', 'slice', 'node', 'user']:
318             raise UnknownSfaType(type) 
319
320         # Use the pointer from the existing record, not the one that the user
321         # gave us. This prevents the user from inserting a forged pointer
322         pointer = record['pointer']
323     
324         # is the a change in keys ?
325         new_key=None
326         if type=='user':
327             if 'keys' in new_record and new_record['keys']:
328                 new_key=new_record['keys']
329                 if isinstance (new_key,types.ListType):
330                     new_key=new_key[0]
331
332         # update the PLC information that was specified with the record
333         if not self.driver.update (record, new_record, hrn, new_key):
334             logger.warning("driver.update failed")
335     
336         # take new_key into account
337         if new_key:
338             # update the openssl key and gid
339             pkey = convert_public_key(new_key)
340             uuid = create_uuid()
341             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
342             gid = gid_object.save_to_string(save_parents=True)
343             record['gid'] = gid
344             record = SfaRecord(dict=record)
345             table.update(record)
346         
347         # update membership for researchers, pis, owners, operators
348         self.update_relations (record, new_record)
349         
350         return 1 
351     
352     # expecting an Xrn instance
353     def Remove(self, api, xrn, origin_hrn=None):
354     
355         table = SfaTable()
356         filter = {'hrn': xrn.get_hrn()}
357         hrn=xrn.get_hrn()
358         type=xrn.get_type()
359         if type and type not in ['all', '*']:
360             filter['type'] = type
361     
362         records = table.find(filter)
363         if not records: raise RecordNotFound(hrn)
364         record = records[0]
365         type = record['type']
366         
367         if type not in ['slice', 'user', 'node', 'authority'] :
368             raise UnknownSfaType(type)
369
370         credential = api.getCredential()
371         registries = api.registries
372     
373         # Try to remove the object from the PLCDB of federated agg.
374         # This is attempted before removing the object from the local agg's PLCDB and sfa table
375         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
376             for registry in registries:
377                 if registry not in [api.hrn]:
378                     try:
379                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
380                     except:
381                         pass
382
383         # call testbed callback first
384         # IIUC this is done on the local testbed TOO because of the refreshpeer link
385         if not self.driver.remove(record):
386             logger.warning("driver.remove failed")
387
388         # delete from sfa db
389         table.remove(record)
390     
391         return 1
392
393     # This is a PLC-specific thing...
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         table = SfaTable()
408         records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
409         if not records:
410             raise RecordNotFound("pointer:" + str(node['node_id']))  
411         record = records[0]
412         
413         # generate a new keypair and gid
414         uuid = create_uuid()
415         pkey = Keypair(create=True)
416         urn = hrn_to_urn(record['hrn'], record['type'])
417         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
418         gid = gid_object.save_to_string(save_parents=True)
419         record['gid'] = gid
420         record.set_gid(gid)
421
422         # update the record
423         table.update(record)
424   
425         # attempt the scp the key
426         # and gid onto the node
427         # this will only work for planetlab based components
428         (kfd, key_filename) = tempfile.mkstemp() 
429         (gfd, gid_filename) = tempfile.mkstemp() 
430         pkey.save_to_file(key_filename)
431         gid_object.save_to_file(gid_filename, save_parents=True)
432         host = node['hostname']
433         key_dest="/etc/sfa/node.key"
434         gid_dest="/etc/sfa/node.gid" 
435         scp = "/usr/bin/scp" 
436         #identity = "/etc/planetlab/root_ssh_key.rsa"
437         identity = "/etc/sfa/root_ssh_key"
438         scp_options=" -i %(identity)s " % locals()
439         scp_options+="-o StrictHostKeyChecking=no " % locals()
440         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
441                          locals()
442         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
443                          locals()    
444
445         all_commands = [scp_key_command, scp_gid_command]
446         
447         for command in all_commands:
448             (status, output) = commands.getstatusoutput(command)
449             if status:
450                 raise Exception, output
451
452         for filename in [key_filename, gid_filename]:
453             os.unlink(filename)
454
455         return 1