removed another bunch of references to geni
[sfa.git] / sfa / managers / registry_manager_pl.py
1 import types
2 import time 
3 from sfa.server.registry import Registries
4 from sfa.util.prefixTree import prefixTree
5 from sfa.util.record import SfaRecord
6 from sfa.util.table import SfaTable
7 from sfa.util.record import SfaRecord
8 from sfa.trust.gid import GID 
9 from sfa.util.namespace import *
10 from sfa.trust.credential import *
11 from sfa.trust.certificate import *
12 from sfa.util.faults import *
13
14 def get_credential(api, hrn, type, is_self=False):    
15     # Is this a root or sub authority
16     auth_hrn = api.auth.get_authority(hrn)
17     if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
18         auth_hrn = hrn
19     # get record info
20     auth_info = api.auth.get_auth_info(auth_hrn)
21     table = SfaTable()
22     records = table.findObjects({'type': type, 'hrn': hrn})
23     if not records:
24         raise RecordNotFound(hrn)
25     record = records[0]
26
27     # verify_cancreate_credential requires that the member lists
28     # (researchers, pis, etc) be filled in
29     api.fill_record_info(record)
30
31     # get the callers gid
32     # if this is a self cred the record's gid is the caller's gid
33     if is_self:
34         caller_hrn = hrn
35         caller_gid = record.get_gid_object()
36     else:
37         caller_gid = api.auth.client_cred.get_gid_caller() 
38         caller_hrn = caller_gid.get_hrn()
39     
40     object_hrn = record.get_gid_object().get_hrn()
41     rights = api.auth.determine_user_rights(caller_hrn, record)
42     # make sure caller has rights to this object
43     if rights.is_empty():
44         raise PermissionError(caller_hrn + " has no rights to " + record['name'])
45
46     object_gid = GID(string=record['gid'])
47     new_cred = Credential(subject = object_gid.get_subject())
48     new_cred.set_gid_caller(caller_gid)
49     new_cred.set_gid_object(object_gid)
50     new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
51     new_cred.set_pubkey(object_gid.get_pubkey())
52     new_cred.set_privileges(rights)
53     new_cred.set_delegate(True)
54     auth_kind = "authority,ma,sa"
55     new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
56     new_cred.encode()
57     new_cred.sign()
58
59     return new_cred.save_to_string(save_parents=True)
60
61 def resolve(api, hrns, type=None, origin_hrn=None):
62
63     # load all know registry names into a prefix tree and attempt to find
64     # the longest matching prefix
65     if not isinstance(hrns, types.ListType):
66         hrns = [hrns]
67     
68     # create a dict whre key is an registry hrn and its value is a
69     # hrns at that registry (determined by the known prefix tree).  
70     hrn_dict = {}
71     registries = Registries(api)
72     tree = prefixTree()
73     registry_hrns = registries.keys()
74     tree.load(registry_hrns)
75     for hrn in hrns:
76         registry_hrn = tree.best_match(hrn)
77         if registry_hrn not in hrn_dict:
78             hrn_dict[registry_hrn] = []
79         hrn_dict[registry_hrn].append(hrn)
80         
81     records = [] 
82     for registry_hrn in hrn_dict:
83         # skip the hrn without a registry hrn
84         # XX should we let the user know the authority is unknown?       
85         if not registry_hrn:
86             continue
87
88         # if the best match (longest matching hrn) is not the local registry,
89         # forward the request
90         hrns = hrn_dict[registry_hrn]
91         if registry_hrn != api.hrn:
92             credential = api.getCredential()
93             peer_records = registries[registry_hrn].resolve(credential, hrn, origin_hrn)
94             records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
95
96     # try resolving the remaining unfound records at the local registry
97     remaining_hrns = set(hrns).difference([record['hrn'] for record in records])
98     remaining_hrns = [hrn for hrn in remaining_hrns] 
99     table = SfaTable()
100     local_records = table.findObjects({'hrn': remaining_hrns})
101     for record in local_records:
102         try:
103             api.fill_record_info(record)
104             records.append(dict(record))
105         except PlanetLabRecordDoesNotExist:
106             # silently drop the ones that are missing in PL
107             print >> log, "ignoring SFA record ", record['hrn'], \
108                               " because pl record does not exist"    
109             table.remove(record)
110
111     if not records:
112         raise RecordNotFound(str(hrns))
113
114     if type:
115         records = filter(lambda rec: rec['type'] in [type], records)
116
117     return records
118
119 def list(api, hrn):
120     # load all know registry names into a prefix tree and attempt to find
121     # the longest matching prefix
122     records = []
123     registries = Registries(api)
124     hrns = registries.keys()
125     tree = prefixTree()
126     tree.load(hrns)
127     registry_hrn = tree.best_match(hrn)
128     
129     #if there was no match then this record belongs to an unknow registry
130     if not registry_hrn:
131         raise MissingAuthority(hrn)
132     
133     # if the best match (longest matching hrn) is not the local registry,
134     # forward the request
135     records = []    
136     if registry_hrn != api.hrn:
137         credential = api.getCredential()
138         record_list = registries[registry_hrn].list(credential, hrn, origin_hrn)
139         records = [SfaRecord(dict=record).as_dict() for record in record_list]
140     
141     # if we still havnt found the record yet, try the local registry
142     if not records:
143         if not api.auth.hierarchy.auth_exists(hrn):
144             raise MissingAuthority(hrn)
145
146         table = SfaTable()
147         records = table.find({'authority': hrn})
148
149     return records
150
151
152 def register(api, record):
153
154     hrn, type = record['hrn'], record['type']
155
156     # validate the type
157     if type not in ['authority', 'slice', 'node', 'user']:
158         raise UnknownSfaType(type) 
159     
160     # check if record already exists
161     table = SfaTable()
162     existing_records = table.find({'type': type, 'hrn': hrn})
163     if existing_records:
164         raise ExistingRecord(hrn)
165        
166     record = SfaRecord(dict = record)
167     record['authority'] = get_authority(record['hrn'])
168     type = record['type']
169     hrn = record['hrn']
170     api.auth.verify_object_permission(hrn)
171     auth_info = api.auth.get_auth_info(record['authority'])
172     pub_key = None
173     # make sure record has a gid
174     if 'gid' not in record:
175         uuid = create_uuid()
176         pkey = Keypair(create=True)
177         if 'key' in record and record['key']:
178             if isinstance(record['key'], types.ListType):
179                 pub_key = record['key'][0]
180             else:
181                 pub_key = record['key']
182             pkey = convert_public_key(pub_key)
183
184         gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
185         gid = gid_object.save_to_string(save_parents=True)
186         record['gid'] = gid
187         record.set_gid(gid)
188
189     if type in ["authority"]:
190         # update the tree
191         if not api.auth.hierarchy.auth_exists(hrn):
192             api.auth.hierarchy.create_auth(hrn)
193
194         # get the GID from the newly created authority
195         gid = auth_info.get_gid_object()
196         record.set_gid(gid.save_to_string(save_parents=True))
197         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
198         sites = api.plshell.GetSites(api.plauth, [pl_record['login_base']])
199         if not sites:
200             pointer = api.plshell.AddSite(api.plauth, pl_record)
201         else:
202             pointer = sites[0]['site_id']
203
204         record.set_pointer(pointer)
205         record['pointer'] = pointer
206
207     elif (type == "slice"):
208         acceptable_fields=['url', 'instantiation', 'name', 'description']
209         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
210         for key in pl_record.keys():
211             if key not in acceptable_fields:
212                 pl_record.pop(key)
213             slices = api.plshell.GetSlices(api.plauth, [pl_record['name']])
214             if not slices:
215                 pointer = api.plshell.AddSlice(api.plauth, pl_record)
216             else:
217                 pointer = slices[0]['slice_id']
218             record.set_pointer(pointer)
219             record['pointer'] = pointer
220
221     elif  (type == "user"):
222         persons = api.plshell.GetPersons(api.plauth, [record['email']])
223         if not persons:
224             pointer = api.plshell.AddPerson(api.plauth, dict(record))
225         else:
226             pointer = persons[0]['person_id']
227
228         if 'enabled' in record and record['enabled']:
229             api.plshell.UpdatePerson(api.plauth, pointer, {'enabled': record['enabled']})
230         # add this persons to the site only if he is being added for the first
231         # time by sfa and doesont already exist in plc
232         if not persons or not persons[0]['site_ids']:
233             login_base = get_leaf(record['authority'])
234             api.plshell.AddPersonToSite(api.plauth, pointer, login_base)
235
236         # What roles should this user have?
237         api.plshell.AddRoleToPerson(api.plauth, 'user', pointer)
238         # Add the user's key
239         if pub_key:
240             api.plshell.AddPersonKey(api.plauth, pointer, {'key_type' : 'ssh', 'key' : pub_key})
241
242     elif (type == "node"):
243         pl_record = api.sfa_fields_to_pl_fields(type, hrn, record)
244         login_base = hrn_to_pl_login_base(record['authority'])
245         nodes = api.plshell.GetNodes(api.plauth, [pl_record['hostname']])
246         if not nodes:
247             pointer = api.plshell.AddNode(api.plauth, login_base, pl_record)
248         else:
249             pointer = nodes[0]['node_id']
250
251     record['pointer'] = pointer
252     record.set_pointer(pointer)
253     record_id = table.insert(record)
254     record['record_id'] = record_id
255
256     # update membership for researchers, pis, owners, operators
257     api.update_membership(None, record)
258
259     return record.get_gid_object().save_to_string(save_parents=True)
260
261 def update(api, record_dict):
262     new_record = SfaRecord(dict = record_dict)
263     type = new_record['type']
264     hrn = new_record['hrn']
265     api.auth.verify_object_permission(hrn)
266     table = SfaTable()
267     # make sure the record exists
268     records = table.findObjects({'type': type, 'hrn': hrn})
269     if not records:
270         raise RecordNotFound(hrn)
271     record = records[0]
272     record['last_updated'] = time.gmtime()
273
274     # Update_membership needs the membership lists in the existing record
275     # filled in, so it can see if members were added or removed
276     api.fill_record_info(record)
277
278     # Use the pointer from the existing record, not the one that the user
279     # gave us. This prevents the user from inserting a forged pointer
280     pointer = record['pointer']
281     # update the PLC information that was specified with the record
282
283     if (type == "authority"):
284         api.plshell.UpdateSite(api.plauth, pointer, new_record)
285
286     elif type == "slice":
287         pl_record=api.sfa_fields_to_pl_fields(type, hrn, new_record)
288         if 'name' in pl_record:
289             pl_record.pop('name')
290             api.plshell.UpdateSlice(api.plauth, pointer, pl_record)
291
292     elif type == "user":
293         # SMBAKER: UpdatePerson only allows a limited set of fields to be
294         #    updated. Ideally we should have a more generic way of doing
295         #    this. I copied the field names from UpdatePerson.py...
296         update_fields = {}
297         all_fields = new_record
298         for key in all_fields.keys():
299             if key in ['first_name', 'last_name', 'title', 'email',
300                        'password', 'phone', 'url', 'bio', 'accepted_aup',
301                        'enabled']:
302                 update_fields[key] = all_fields[key]
303         api.plshell.UpdatePerson(api.plauth, pointer, update_fields)
304
305         if 'key' in new_record and new_record['key']:
306             # must check this key against the previous one if it exists
307             persons = api.plshell.GetPersons(api.plauth, [pointer], ['key_ids'])
308             person = persons[0]
309             keys = person['key_ids']
310             keys = api.plshell.GetKeys(api.plauth, person['key_ids'])
311             key_exists = False
312             if isinstance(new_record['key'], types.ListType):
313                 new_key = new_record['key'][0]
314             else:
315                 new_key = new_record['key']
316             
317             # Delete all stale keys
318             for key in keys:
319                 if new_record['key'] != key['key']:
320                     api.plshell.DeleteKey(api.plauth, key['key_id'])
321                 else:
322                     key_exists = True
323             if not key_exists:
324                 api.plshell.AddPersonKey(api.plauth, pointer, {'key_type': 'ssh', 'key': new_key})
325
326             # update the openssl key and gid
327             pkey = convert_public_key(new_key)
328             uuid = create_uuid()
329             gid_object = api.auth.hierarchy.create_gid(hrn, uuid, pkey)
330             gid = gid_object.save_to_string(save_parents=True)
331             record['gid'] = gid
332             record = SfaRecord(dict=record)
333             table.update(record)
334
335     elif type == "node":
336         api.plshell.UpdateNode(api.plauth, pointer, new_record)
337
338     else:
339         raise UnknownSfaType(type)
340
341     # update membership for researchers, pis, owners, operators
342     api.update_membership(record, new_record)
343     
344     return 1 
345
346 def remove(api, hrn, type, origin_hrn=None):
347     table = SfaTable()
348     filter = {'hrn': hrn}
349     if type not in ['all', '*']:
350         filter['type'] = type
351     records = table.find(filter)
352     if not records:
353         raise RecordNotFound(hrn)
354     record = records[0]
355     type = record['type']
356
357     credential = api.getCredential()
358     registries = Registries(api)
359
360     # Try to remove the object from the PLCDB of federated agg.
361     # This is attempted before removing the object from the local agg's PLCDB and sfa table
362     if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
363         for registry in registries:
364             if registry not in [api.hrn]:
365                 try:
366                     result=registries[registry].remove_peer_object(credential, record, origin_hrn)
367                 except:
368                     pass
369     if type == "user":
370         persons = api.plshell.GetPersons(api.plauth, record['pointer'])
371         # only delete this person if he has site ids. if he doesnt, it probably means
372         # he was just removed from a site, not actually deleted
373         if persons and persons[0]['site_ids']:
374             api.plshell.DeletePerson(api.plauth, record['pointer'])
375     elif type == "slice":
376         if api.plshell.GetSlices(api.plauth, record['pointer']):
377             api.plshell.DeleteSlice(api.plauth, record['pointer'])
378     elif type == "node":
379         if api.plshell.GetNodes(api.plauth, record['pointer']):
380             api.plshell.DeleteNode(api.plauth, record['pointer'])
381     elif type == "authority":
382         if api.plshell.GetSites(api.plauth, record['pointer']):
383             api.plshell.DeleteSite(api.plauth, record['pointer'])
384     else:
385         raise UnknownSfaType(type)
386
387     table.remove(record)
388
389     return 1
390
391 def remove_peer_object(api, record, origin_hrn=None):
392     pass
393
394 def register_peer_object(api, record, origin_hrn=None):
395     pass