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