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