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