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