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