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