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