driver.remove
[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_entity (record, api.aggregates):
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         # xxx driver todo
141         if full:
142             self.driver.fill_record_info(local_records, api.aggregates)
143         
144         # convert local record objects to dicts
145         records.extend([dict(record) for record in local_records])
146         if type:
147             records = filter(lambda rec: rec['type'] in [type], records)
148     
149         if not records:
150             raise RecordNotFound(str(hrns))
151     
152         return records
153     
154     def List(self, api, xrn, origin_hrn=None):
155         hrn, type = urn_to_hrn(xrn)
156         # load all know registry names into a prefix tree and attempt to find
157         # the longest matching prefix
158         records = []
159         registries = api.registries
160         registry_hrns = registries.keys()
161         tree = prefixTree()
162         tree.load(registry_hrns)
163         registry_hrn = tree.best_match(hrn)
164        
165         #if there was no match then this record belongs to an unknow registry
166         if not registry_hrn:
167             raise MissingAuthority(xrn)
168         # if the best match (longest matching hrn) is not the local registry,
169         # forward the request
170         records = []    
171         if registry_hrn != api.hrn:
172             credential = api.getCredential()
173             interface = api.registries[registry_hrn]
174             server_proxy = api.server_proxy(interface, credential)
175             record_list = server_proxy.List(xrn, credential)
176             records = [SfaRecord(dict=record).as_dict() for record in record_list]
177         
178         # if we still have not found the record yet, try the local registry
179         if not records:
180             if not api.auth.hierarchy.auth_exists(hrn):
181                 raise MissingAuthority(hrn)
182     
183             table = SfaTable()
184             records = table.find({'authority': hrn})
185     
186         return records
187     
188     
189     def CreateGid(self, api, xrn, cert):
190         # get the authority
191         authority = Xrn(xrn=xrn).get_authority_hrn()
192         auth_info = api.auth.get_auth_info(authority)
193         if not cert:
194             pkey = Keypair(create=True)
195         else:
196             certificate = Certificate(string=cert)
197             pkey = certificate.get_pubkey()    
198         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
199         return gid.save_to_string(save_parents=True)
200         
201     def Register(self, api, record):
202     
203         hrn, type = record['hrn'], record['type']
204         urn = hrn_to_urn(hrn,type)
205         # validate the type
206         if type not in ['authority', 'slice', 'node', 'user']:
207             raise UnknownSfaType(type) 
208         
209         # check if record already exists
210         table = SfaTable()
211         existing_records = table.find({'type': type, 'hrn': hrn})
212         if existing_records:
213             raise ExistingRecord(hrn)
214            
215         record = SfaRecord(dict = record)
216         record['authority'] = get_authority(record['hrn'])
217         auth_info = api.auth.get_auth_info(record['authority'])
218         pub_key = None
219         # make sure record has a gid
220         if 'gid' not in record:
221             uuid = create_uuid()
222             pkey = Keypair(create=True)
223             if 'key' in record and record['key']:
224                 # use only first key in record
225                 if isinstance(record['key'], types.ListType):
226                     pub_key = record['key'][0]
227                 else:
228                     pub_key = record['key']
229                 pkey = convert_public_key(pub_key)
230     
231             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
232             gid = gid_object.save_to_string(save_parents=True)
233             record['gid'] = gid
234             record.set_gid(gid)
235     
236         if type in ["authority"]:
237             # update the tree
238             if not api.auth.hierarchy.auth_exists(hrn):
239                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
240     
241             # get the GID from the newly created authority
242             gid = auth_info.get_gid_object()
243             record.set_gid(gid.save_to_string(save_parents=True))
244
245         # update testbed-specific data f needed
246         logger.info("Getting driver from manager=%s"%self)
247         pointer = self.driver.register (hrn, record, pub_key)
248
249         record.set_pointer(pointer)
250         record_id = table.insert(record)
251         record['record_id'] = record_id
252     
253         # update membership for researchers, pis, owners, operators
254         self.driver.update_membership(None, record)
255     
256         return record.get_gid_object().save_to_string(save_parents=True)
257     
258     def Update(self, api, record_dict):
259         new_record = SfaRecord(dict = record_dict)
260         type = new_record['type']
261         hrn = new_record['hrn']
262         urn = hrn_to_urn(hrn,type)
263         table = SfaTable()
264         # make sure the record exists
265         records = table.findObjects({'type': type, 'hrn': hrn})
266         if not records:
267             raise RecordNotFound(hrn)
268         record = records[0]
269         record['last_updated'] = time.gmtime()
270     
271         # Update_membership needs the membership lists in the existing record
272         # filled in, so it can see if members were added or removed
273         self.driver.fill_record_info(record, api.aggregates)
274     
275         # Use the pointer from the existing record, not the one that the user
276         # gave us. This prevents the user from inserting a forged pointer
277         pointer = record['pointer']
278         # update the PLC information that was specified with the record
279     
280         if (type == "authority"):
281             self.driver.UpdateSite(pointer, new_record)
282     
283         elif type == "slice":
284             pl_record=self.driver.sfa_fields_to_pl_fields(type, hrn, new_record)
285             if 'name' in pl_record:
286                 pl_record.pop('name')
287                 self.driver.UpdateSlice(pointer, pl_record)
288     
289         elif type == "user":
290             # SMBAKER: UpdatePerson only allows a limited set of fields to be
291             #    updated. Ideally we should have a more generic way of doing
292             #    this. I copied the field names from UpdatePerson.py...
293             update_fields = {}
294             all_fields = new_record
295             for key in all_fields.keys():
296                 if key in ['first_name', 'last_name', 'title', 'email',
297                            'password', 'phone', 'url', 'bio', 'accepted_aup',
298                            'enabled']:
299                     update_fields[key] = all_fields[key]
300             self.driver.UpdatePerson(pointer, update_fields)
301     
302             if 'key' in new_record and new_record['key']:
303                 # must check this key against the previous one if it exists
304                 persons = self.driver.GetPersons([pointer], ['key_ids'])
305                 person = persons[0]
306                 keys = person['key_ids']
307                 keys = self.driver.GetKeys(person['key_ids'])
308                 key_exists = False
309                 if isinstance(new_record['key'], types.ListType):
310                     new_key = new_record['key'][0]
311                 else:
312                     new_key = new_record['key']
313                 
314                 # Delete all stale keys
315                 for key in keys:
316                     if new_record['key'] != key['key']:
317                         self.driver.DeleteKey(key['key_id'])
318                     else:
319                         key_exists = True
320                 if not key_exists:
321                     self.driver.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
322     
323                 # update the openssl key and gid
324                 pkey = convert_public_key(new_key)
325                 uuid = create_uuid()
326                 gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
327                 gid = gid_object.save_to_string(save_parents=True)
328                 record['gid'] = gid
329                 record = SfaRecord(dict=record)
330                 table.update(record)
331     
332         elif type == "node":
333             self.driver.UpdateNode(pointer, new_record)
334     
335         else:
336             raise UnknownSfaType(type)
337     
338         # update membership for researchers, pis, owners, operators
339         self.driver.update_membership(record, new_record)
340         
341         return 1 
342     
343     # expecting an Xrn instance
344     def Remove(self, api, xrn, origin_hrn=None):
345     
346         table = SfaTable()
347         filter = {'hrn': xrn.get_hrn()}
348         hrn=xrn.get_hrn()
349         type=xrn.get_type()
350         if type and type not in ['all', '*']:
351             filter['type'] = type
352     
353         records = table.find(filter)
354         if not records: raise RecordNotFound(hrn)
355         record = records[0]
356         type = record['type']
357         
358         if not type in ['slice', 'user', 'node', 'authority'] :
359             raise UnknownSfaType(type)
360
361         credential = api.getCredential()
362         registries = api.registries
363     
364         # Try to remove the object from the PLCDB of federated agg.
365         # This is attempted before removing the object from the local agg's PLCDB and sfa table
366         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
367             for registry in registries:
368                 if registry not in [api.hrn]:
369                     try:
370                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
371                     except:
372                         pass
373         # call testbed callback first
374         self.driver.remove(record)
375         # delete from sfa db
376         table.remove(record)
377     
378         return 1
379
380     # This is a PLC-specific thing...
381     def get_key_from_incoming_ip (self, api):
382         # verify that the callers's ip address exist in the db and is an interface
383         # for a node in the db
384         (ip, port) = api.remote_addr
385         interfaces = self.driver.GetInterfaces({'ip': ip}, ['node_id'])
386         if not interfaces:
387             raise NonExistingRecord("no such ip %(ip)s" % locals())
388         nodes = self.driver.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
389         if not nodes:
390             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
391         node = nodes[0]
392        
393         # look up the sfa record
394         table = SfaTable()
395         records = table.findObjects({'type': 'node', 'pointer': node['node_id']})
396         if not records:
397             raise RecordNotFound("pointer:" + str(node['node_id']))  
398         record = records[0]
399         
400         # generate a new keypair and gid
401         uuid = create_uuid()
402         pkey = Keypair(create=True)
403         urn = hrn_to_urn(record['hrn'], record['type'])
404         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
405         gid = gid_object.save_to_string(save_parents=True)
406         record['gid'] = gid
407         record.set_gid(gid)
408
409         # update the record
410         table.update(record)
411   
412         # attempt the scp the key
413         # and gid onto the node
414         # this will only work for planetlab based components
415         (kfd, key_filename) = tempfile.mkstemp() 
416         (gfd, gid_filename) = tempfile.mkstemp() 
417         pkey.save_to_file(key_filename)
418         gid_object.save_to_file(gid_filename, save_parents=True)
419         host = node['hostname']
420         key_dest="/etc/sfa/node.key"
421         gid_dest="/etc/sfa/node.gid" 
422         scp = "/usr/bin/scp" 
423         #identity = "/etc/planetlab/root_ssh_key.rsa"
424         identity = "/etc/sfa/root_ssh_key"
425         scp_options=" -i %(identity)s " % locals()
426         scp_options+="-o StrictHostKeyChecking=no " % locals()
427         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
428                          locals()
429         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
430                          locals()    
431
432         all_commands = [scp_key_command, scp_gid_command]
433         
434         for command in all_commands:
435             (status, output) = commands.getstatusoutput(command)
436             if status:
437                 raise Exception, output
438
439         for filename in [key_filename, gid_filename]:
440             os.unlink(filename)
441
442         return 1