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