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