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