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