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