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