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