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