more pep8-friendly
[sfa.git] / sfa / planetlab / plslices.py
1 import time
2 from collections import defaultdict
3
4 from sfa.util.sfatime import utcparse, datetime_to_epoch
5 from sfa.util.sfalogging import logger
6 from sfa.util.xrn import Xrn, get_leaf, get_authority, urn_to_hrn
7 from sfa.rspecs.rspec import RSpec
8 from sfa.planetlab.vlink import VLink
9 from sfa.planetlab.topology import Topology
10 from sfa.planetlab.plxrn import (PlXrn, hrn_to_pl_slicename, xrn_to_hostname,
11                                  top_auth, hash_loginbase)
12 from sfa.storage.model import SliverAllocation
13
14 MAXINT = 2L**31 - 1
15
16
17 class PlSlices:
18
19     rspec_to_slice_tag = {'max_rate': 'net_max_rate'}
20
21     def __init__(self, driver):
22         self.driver = driver
23
24     def get_slivers(self, xrn, node=None):
25         hrn, type = urn_to_hrn(xrn)
26
27         slice_name = hrn_to_pl_slicename(hrn)
28         # XX Should we just call PLCAPI.GetSliceTicket(slice_name) instead
29         # of doing all of this?
30         # return self.driver.shell.GetSliceTicket(self.auth, slice_name)
31
32         # from PLCAPI.GetSlivers.get_slivers()
33         slice_fields = ['slice_id', 'name', 'instantiation',
34                         'expires', 'person_ids', 'slice_tag_ids']
35         slices = self.driver.shell.GetSlices(slice_name, slice_fields)
36         # Build up list of users and slice attributes
37         person_ids = set()
38         all_slice_tag_ids = set()
39         for slice in slices:
40             person_ids.update(slice['person_ids'])
41             all_slice_tag_ids.update(slice['slice_tag_ids'])
42         person_ids = list(person_ids)
43         all_slice_tag_ids = list(all_slice_tag_ids)
44         # Get user information
45         all_persons_list = self.driver.shell.GetPersons(
46             {'person_id': person_ids, 'enabled': True},
47             ['person_id', 'enabled', 'key_ids'])
48         all_persons = {}
49         for person in all_persons_list:
50             all_persons[person['person_id']] = person
51
52         # Build up list of keys
53         key_ids = set()
54         for person in all_persons.values():
55             key_ids.update(person['key_ids'])
56         key_ids = list(key_ids)
57         # Get user account keys
58         all_keys_list = self.driver.shell.GetKeys(
59             key_ids, ['key_id', 'key', 'key_type'])
60         all_keys = {}
61         for key in all_keys_list:
62             all_keys[key['key_id']] = key
63         # Get slice attributes
64         all_slice_tags_list = self.driver.shell.GetSliceTags(all_slice_tag_ids)
65         all_slice_tags = {}
66         for slice_tag in all_slice_tags_list:
67             all_slice_tags[slice_tag['slice_tag_id']] = slice_tag
68
69         slivers = []
70         for slice in slices:
71             keys = []
72             for person_id in slice['person_ids']:
73                 if person_id in all_persons:
74                     person = all_persons[person_id]
75                     if not person['enabled']:
76                         continue
77                     for key_id in person['key_ids']:
78                         if key_id in all_keys:
79                             key = all_keys[key_id]
80                             keys += [{'key_type': key['key_type'],
81                                       'key': key['key']}]
82             attributes = []
83             # All (per-node and global) attributes for this slice
84             slice_tags = []
85             for slice_tag_id in slice['slice_tag_ids']:
86                 if slice_tag_id in all_slice_tags:
87                     slice_tags.append(all_slice_tags[slice_tag_id])
88             # Per-node sliver attributes take precedence over global
89             # slice attributes, so set them first.
90             # Then comes nodegroup slice attributes
91             # Followed by global slice attributes
92             sliver_attributes = []
93
94             if node is not None:
95                 for sliver_attribute in filter(
96                         lambda a: a['node_id'] == node['node_id'],
97                         slice_tags):
98                     sliver_attributes.append(sliver_attribute['tagname'])
99                     attributes.append({'tagname': sliver_attribute['tagname'],
100                                        'value': sliver_attribute['value']})
101
102             # set nodegroup slice attributes
103             for slice_tag in filter(
104                     lambda a: a['nodegroup_id'] in node['nodegroup_ids'],
105                     slice_tags):
106                 # Do not set any nodegroup slice attributes for
107                 # which there is at least one sliver attribute
108                 # already set.
109                 if slice_tag not in slice_tags:
110                     attributes.append({'tagname': slice_tag['tagname'],
111                                        'value': slice_tag['value']})
112
113             for slice_tag in filter(
114                     lambda a: a['node_id'] is None,
115                     slice_tags):
116                 # Do not set any global slice attributes for
117                 # which there is at least one sliver attribute
118                 # already set.
119                 if slice_tag['tagname'] not in sliver_attributes:
120                     attributes.append({'tagname': slice_tag['tagname'],
121                                        'value': slice_tag['value']})
122
123             # XXX Sanity check; though technically this should be a system invariant
124             # checked with an assertion
125             if slice['expires'] > MAXINT:
126                 slice['expires'] = MAXINT
127
128             slivers.append({
129                 'hrn': hrn,
130                 'name': slice['name'],
131                 'slice_id': slice['slice_id'],
132                 'instantiation': slice['instantiation'],
133                 'expires': slice['expires'],
134                 'keys': keys,
135                 'attributes': attributes
136             })
137
138         return slivers
139
140     def get_sfa_peer(self, xrn):
141         hrn, type = urn_to_hrn(xrn)
142
143         # return the authority for this hrn or None if we are the authority
144         sfa_peer = None
145         slice_authority = get_authority(hrn)
146         site_authority = get_authority(slice_authority)
147
148         if site_authority != self.driver.hrn:
149             sfa_peer = site_authority
150
151         return sfa_peer
152
153     def verify_slice_leases(self, slice, rspec_requested_leases):
154
155         leases = self.driver.shell.GetLeases(
156             {'name': slice['name'], 'clip': int(time.time())},
157             ['lease_id', 'name', 'hostname', 't_from', 't_until'])
158         grain = self.driver.shell.GetLeaseGranularity()
159
160         requested_leases = []
161         for lease in rspec_requested_leases:
162             requested_lease = {}
163             slice_hrn, _ = urn_to_hrn(lease['slice_id'])
164
165             top_auth_hrn = top_auth(slice_hrn)
166             site_hrn = '.'.join(slice_hrn.split('.')[:-1])
167             slice_part = slice_hrn.split('.')[-1]
168             if top_auth_hrn == self.driver.hrn:
169                 login_base = slice_hrn.split('.')[-2][:12]
170             else:
171                 login_base = hash_loginbase(site_hrn)
172
173             slice_name = '_'.join([login_base, slice_part])
174
175             if slice_name != slice['name']:
176                 continue
177             elif (Xrn(lease['component_id']).get_authority_urn().split(':')[0]
178                   != self.driver.hrn):
179                 continue
180
181             hostname = xrn_to_hostname(lease['component_id'])
182             # fill the requested node with nitos ids
183             requested_lease['name'] = slice['name']
184             requested_lease['hostname'] = hostname
185             requested_lease['t_from'] = int(lease['start_time'])
186             requested_lease['t_until'] = int(
187                 lease['duration']) * grain + int(lease['start_time'])
188             requested_leases.append(requested_lease)
189
190         # prepare actual slice leases by lease_id
191         leases_by_id = {}
192         for lease in leases:
193             leases_by_id[lease['lease_id']] = {
194                 'name': lease['name'], 'hostname': lease['hostname'],
195                 't_from': lease['t_from'], 't_until': lease['t_until']}
196
197         added_leases = []
198         kept_leases_id = []
199         deleted_leases_id = []
200         for lease_id in leases_by_id:
201             if leases_by_id[lease_id] not in requested_leases:
202                 deleted_leases_id.append(lease_id)
203             else:
204                 kept_leases_id.append(lease_id)
205                 requested_leases.remove(leases_by_id[lease_id])
206         added_leases = requested_leases
207
208         try:
209             self.driver.shell.DeleteLeases(deleted_leases_id)
210             for lease in added_leases:
211                 self.driver.shell.AddLeases(
212                     lease['hostname'], slice['name'],
213                     lease['t_from'], lease['t_until'])
214
215         except Exception:
216             logger.log_exc('Failed to add/remove slice leases')
217
218         return leases
219
220     def verify_slice_nodes(self, slice_urn, slice, rspec_nodes):
221
222         slivers = {}
223         for node in rspec_nodes:
224             hostname = node.get('component_name')
225             client_id = node.get('client_id')
226             component_id = node.get('component_id').strip()
227             if hostname:
228                 hostname = hostname.strip()
229             elif component_id:
230                 hostname = xrn_to_hostname(component_id)
231             if hostname:
232                 slivers[hostname] = {
233                     'client_id': client_id, 'component_id': component_id}
234
235         nodes = self.driver.shell.GetNodes(
236             slice['node_ids'], ['node_id', 'hostname', 'interface_ids'])
237         current_slivers = [node['hostname'] for node in nodes]
238
239         # remove nodes not in rspec
240         deleted_nodes = list(set(current_slivers).difference(slivers.keys()))
241
242         # add nodes from rspec
243         added_nodes = list(set(slivers.keys()).difference(current_slivers))
244
245         try:
246             self.driver.shell.AddSliceToNodes(slice['name'], added_nodes)
247             self.driver.shell.DeleteSliceFromNodes(
248                 slice['name'], deleted_nodes)
249
250         except Exception:
251             logger.log_exc('Failed to add/remove slice from nodes')
252
253         slices = self.driver.shell.GetSlices(slice['name'], ['node_ids'])
254         resulting_nodes = self.driver.shell.GetNodes(slices[0]['node_ids'])
255
256         # update sliver allocations
257         for node in resulting_nodes:
258             client_id = slivers[node['hostname']]['client_id']
259             component_id = slivers[node['hostname']]['component_id']
260             sliver_hrn = '{}.{}-{}'.format(self.driver.hrn,
261                                            slice['slice_id'], node['node_id'])
262             sliver_id = Xrn(sliver_hrn, type='sliver').urn
263             record = SliverAllocation(sliver_id=sliver_id, client_id=client_id,
264                                       component_id=component_id,
265                                       slice_urn=slice_urn,
266                                       allocation_state='geni_allocated')
267             record.sync(self.driver.api.dbsession())
268         return resulting_nodes
269
270     def free_egre_key(self):
271         used = set()
272         for tag in self.driver.shell.GetSliceTags({'tagname': 'egre_key'}):
273             used.add(int(tag['value']))
274
275         for i in range(1, 256):
276             if i not in used:
277                 key = i
278                 break
279         else:
280             raise KeyError("No more EGRE keys available")
281
282         return str(key)
283
284     def verify_slice_links(self, slice, requested_links, nodes):
285
286         if not requested_links:
287             return
288
289         # exit if links are not supported here
290         topology = Topology()
291         if not topology:
292             return
293
294         # build dict of nodes
295         nodes_dict = {}
296         interface_ids = []
297         for node in nodes:
298             nodes_dict[node['node_id']] = node
299             interface_ids.extend(node['interface_ids'])
300         # build dict of interfaces
301         interfaces = self.driver.shell.GetInterfaces(interface_ids)
302         interfaces_dict = {}
303         for interface in interfaces:
304             interfaces_dict[interface['interface_id']] = interface
305
306         slice_tags = []
307
308         # set egre key
309         slice_tags.append({'name': 'egre_key', 'value': self.free_egre_key()})
310
311         # set netns
312         slice_tags.append({'name': 'netns', 'value': '1'})
313
314         # set cap_net_admin
315         # need to update the attribute string?
316         slice_tags.append({'name': 'capabilities', 'value': 'CAP_NET_ADMIN'})
317
318         for link in requested_links:
319             # get the ip address of the first node in the link
320             ifname1 = Xrn(link['interface1']['component_id']).get_leaf()
321
322             if ifname1:
323                 ifname_parts = ifname1.split(':')
324                 node_raw = ifname_parts[0]
325                 device = None
326                 if len(ifname_parts) > 1:
327                     device = ifname_parts[1]
328                 node_id = int(node_raw.replace('node', ''))
329                 node = nodes_dict[node_id]
330                 if1 = interfaces_dict[node['interface_ids'][0]]
331                 ipaddr = if1['ip']
332                 topo_rspec = VLink.get_topo_rspec(link, ipaddr)
333                 # set topo_rspec tag
334                 slice_tags.append({'name': 'topo_rspec', 'value': str(
335                     [topo_rspec]), 'node_id': node_id})
336                 # set vini_topo tag
337                 slice_tags.append(
338                     {'name': 'vini_topo', 'value': 'manual', 'node_id': node_id})
339                 #self.driver.shell.AddSliceTag(slice['name'], 'topo_rspec', str([topo_rspec]), node_id)
340
341         self.verify_slice_tags(slice, slice_tags, {
342                                'pltags': 'append'}, admin=True)
343
344     def verify_site(self, slice_xrn,
345                     slice_record=None, sfa_peer=None, options=None):
346         if slice_record is None:
347             slice_record = {}
348         if options is None:
349             options = {}
350         (slice_hrn, type) = urn_to_hrn(slice_xrn)
351         top_auth_hrn = top_auth(slice_hrn)
352         site_hrn = '.'.join(slice_hrn.split('.')[:-1])
353         if top_auth_hrn == self.driver.hrn:
354             login_base = slice_hrn.split('.')[-2][:12]
355         else:
356             login_base = hash_loginbase(site_hrn)
357
358         # filter sites by hrn
359         sites = self.driver.shell.GetSites(
360             {'peer_id': None, 'hrn': site_hrn},
361             ['site_id', 'name', 'abbreviated_name', 'login_base', 'hrn'])
362
363         # alredy exists
364         if sites:
365             site = sites[0]
366         else:
367             # create new site record
368             site = {'name': 'sfa:{}'.format(site_hrn),
369                     'abbreviated_name': site_hrn,
370                     'login_base': login_base,
371                     'max_slices': 100,
372                     'max_slivers': 1000,
373                     'enabled': True,
374                     'peer_site_id': None,
375                     'hrn': site_hrn,
376                     'sfa_created': 'True',
377                     }
378             site_id = self.driver.shell.AddSite(site)
379             # plcapi tends to mess with the incoming hrn so let's make sure
380             self.driver.shell.SetSiteHrn(site_id, site_hrn)
381             site['site_id'] = site_id
382             # exempt federated sites from monitor policies
383             self.driver.shell.AddSiteTag(
384                 site_id, 'exempt_site_until', "20200101")
385
386         return site
387
388     def verify_slice(self, slice_hrn, slice_record,
389                      sfa_peer, expiration, options=None):
390         if options is None:
391             options = {}
392         top_auth_hrn = top_auth(slice_hrn)
393         site_hrn = '.'.join(slice_hrn.split('.')[:-1])
394         slice_part = slice_hrn.split('.')[-1]
395         if top_auth_hrn == self.driver.hrn:
396             login_base = slice_hrn.split('.')[-2][:12]
397         else:
398             login_base = hash_loginbase(site_hrn)
399         slice_name = '_'.join([login_base, slice_part])
400
401         expires = int(datetime_to_epoch(utcparse(expiration)))
402         # Filter slices by HRN
403         slices = self.driver.shell.GetSlices(
404             {'peer_id': None, 'hrn': slice_hrn},
405             ['slice_id', 'name', 'hrn', 'expires'])
406
407         if slices:
408             slice = slices[0]
409             slice_id = slice['slice_id']
410             # Update expiration if necessary
411             if slice.get('expires', None) != expires:
412                 self.driver.shell.UpdateSlice(slice_id, {'expires': expires})
413         else:
414             if slice_record:
415                 url = slice_record.get('url', slice_hrn)
416                 description = slice_record.get('description', slice_hrn)
417             else:
418                 url = slice_hrn
419                 description = slice_hrn
420             slice = {'name': slice_name,
421                      'url': url,
422                      'description': description,
423                      'hrn': slice_hrn,
424                      'sfa_created': 'True',
425                      #'expires': expires,
426                      }
427             # add the slice
428             slice_id = self.driver.shell.AddSlice(slice)
429             # plcapi tends to mess with the incoming hrn so let's make sure
430             self.driver.shell.SetSliceHrn(slice_id, slice_hrn)
431             # cannot be set with AddSlice
432             # set the expiration
433             self.driver.shell.UpdateSlice(slice_id, {'expires': expires})
434
435         return self.driver.shell.GetSlices(slice_id)[0]
436
437     # in the following code, we use
438     # 'person' to denote a PLCAPI-like record with typically 'person_id' and 'email'
439     # 'user' to denote an incoming record with typically 'urn' and 'email' - we add 'hrn' in there
440     #        'slice_record': it seems like the first of these 'users' also contains a 'slice_record'
441     #           key that holds stuff like 'hrn', 'slice_id', 'authority',...
442     #
443     def create_person_from_user(self, user, site_id):
444         user_hrn = user['hrn']
445         # the value to use if 'user' has no 'email' attached - or if the attached email already exists
446         # typically
447         (auth_hrn, _, leaf) = user_hrn.rpartition('.')
448         # somehow this has backslashes, get rid of them
449         auth_hrn = auth_hrn.replace('\\', '')
450         default_email = "{}@{}.stub".format(leaf, auth_hrn)
451
452         person_record = {
453             # required
454             'first_name': user.get('first_name', user_hrn),
455             'last_name': user.get('last_name', user_hrn),
456             'email': user.get('email', default_email),
457             # our additions
458             'enabled': True,
459             'sfa_created': 'True',
460             'hrn': user_hrn,
461         }
462
463         logger.debug(
464             "about to attempt to AddPerson with {}".format(person_record))
465         try:
466             # the thing is, the PLE db has a limitation on re-using the same e-mail
467             # in the case where people have an account on ple.upmc and then then come
468             # again from onelab.upmc, they will most likely have the same e-mail, and so kaboom..
469             # so we first try with the accurate email
470             person_id = int(self.driver.shell.AddPerson(person_record))
471         except:
472             logger.log_exc("caught during first attempt at AddPerson")
473             # and if that fails we start again with the email based on the hrn,
474             # which this time is unique..
475             person_record['email'] = default_email
476             logger.debug("second chance with email={}".format(
477                 person_record['email']))
478             person_id = int(self.driver.shell.AddPerson(person_record))
479         self.driver.shell.AddRoleToPerson('user', person_id)
480         self.driver.shell.AddPersonToSite(person_id, site_id)
481         # plcapi tends to mess with the incoming hrn so let's make sure
482         self.driver.shell.SetPersonHrn(person_id, user_hrn)
483         # also 'enabled':True does not seem to pass through with AddPerson
484         self.driver.shell.UpdatePerson(person_id, {'enabled': True})
485
486         return person_id
487
488     def verify_persons(self, slice_hrn, slice_record,
489                        users, sfa_peer, options=None):
490         if options is None:
491             options = {}
492
493         # first we annotate the incoming users arg with a 'hrn' key
494         for user in users:
495             user['hrn'], _ = urn_to_hrn(user['urn'])
496         # this is for retrieving users from a hrn
497         users_by_hrn = {user['hrn']: user for user in users}
498
499         for user in users:
500             logger.debug("incoming user {}".format(user))
501
502         # compute the hrn's for the authority and site
503         top_auth_hrn = top_auth(slice_hrn)
504         site_hrn = '.'.join(slice_hrn.split('.')[:-1])
505         slice_part = slice_hrn.split('.')[-1]
506         # deduce login_base and slice_name
507         if top_auth_hrn == self.driver.hrn:
508             login_base = slice_hrn.split('.')[-2][:12]
509         else:
510             login_base = hash_loginbase(site_hrn)
511         slice_name = '_'.join([login_base, slice_part])
512
513         # locate the site object
514         # due to a limitation in PLCAPI, we have to specify 'hrn' as part of
515         # the return fields
516         site = self.driver.shell.GetSites(
517             {'peer_id': None, 'hrn': site_hrn}, ['site_id', 'hrn'])[0]
518         site_id = site['site_id']
519
520         # locate the slice object
521         slice = self.driver.shell.GetSlices(
522             {'peer_id': None, 'hrn': slice_hrn},
523             ['slice_id', 'hrn', 'person_ids'])[0]
524         slice_id = slice['slice_id']
525         slice_person_ids = slice['person_ids']
526
527         # the common set of attributes for our calls to GetPersons
528         person_fields = ['person_id', 'email', 'hrn']
529
530         # for the intended set of hrns, locate existing persons
531         target_hrns = [user['hrn'] for user in users]
532         target_existing_persons = self.driver.shell.GetPersons(
533             {'peer_id': None, 'hrn': target_hrns}, person_fields)
534         target_existing_person_ids = [person['person_id']
535                                       for person in target_existing_persons]
536         # find out the hrns that *do not* have a corresponding person
537         existing_hrns = [person['hrn'] for person in target_existing_persons]
538         tocreate_hrns = set(target_hrns) - set(existing_hrns)
539         # create these
540         target_created_person_ids = [self.create_person_from_user(
541             users_by_hrn[hrn], site_id) for hrn in tocreate_hrns]
542
543         # we can partition the persons of interest into one of these 3 classes
544         add_person_ids = set(target_created_person_ids) | set(
545             target_existing_person_ids) - set(slice_person_ids)
546         keep_person_ids = set(
547             target_existing_person_ids) & set(slice_person_ids)
548         del_person_ids = set(slice_person_ids) - \
549             set(target_existing_person_ids)
550
551         # delete
552         for person_id in del_person_ids:
553             self.driver.shell.DeletePersonFromSlice(person_id, slice_id)
554
555         # about the last 2 sets, for managing keys, we need to trace back person_id -> user
556         # and for this we need all the Person objects; we already have the target_existing ones
557         # also we avoid issuing a call if possible
558         target_created_persons = [] if not target_created_person_ids \
559             else self.driver.shell.GetPersons(
560                 {'peer_id': None, 'person_id': target_created_person_ids},
561                 person_fields)
562         persons_by_person_id = {
563             person['person_id']: person
564             for person in target_existing_persons + target_created_persons}
565
566         def user_by_person_id(person_id):
567             person = persons_by_person_id[person_id]
568             hrn = person['hrn']
569             return users_by_hrn[hrn]
570
571         persons_to_verify_keys = {}
572         # add
573         for person_id in add_person_ids:
574             self.driver.shell.AddPersonToSlice(person_id, slice_id)
575             persons_to_verify_keys[person_id] = user_by_person_id(person_id)
576         # Update kept persons
577         for person_id in keep_person_ids:
578             persons_to_verify_keys[person_id] = user_by_person_id(person_id)
579         self.verify_keys(persons_to_verify_keys, options)
580
581         # return hrns of the newly added persons
582
583         return [persons_by_person_id[person_id]['hrn']
584                 for person_id in add_person_ids]
585
586     def verify_keys(self, persons_to_verify_keys, options=None):
587         if options is None:
588             options = {}
589         # we only add keys that comes from sfa to persons in PL
590         for person_id in persons_to_verify_keys:
591             person_sfa_keys = persons_to_verify_keys[person_id].get('keys', [])
592             person_pl_keys = self.driver.shell.GetKeys(
593                 {'person_id': int(person_id)})
594             person_pl_keys_list = [key['key'] for key in person_pl_keys]
595
596             keys_to_add = set(person_sfa_keys).difference(person_pl_keys_list)
597
598             for key_string in keys_to_add:
599                 key = {'key': key_string, 'key_type': 'ssh'}
600                 self.driver.shell.AddPersonKey(int(person_id), key)
601
602     def verify_slice_tags(self, slice, requested_slice_attributes,
603                           options=None, admin=False):
604         """
605         This function deals with slice tags, and supports 3 modes described
606         in the 'pltags' option that can be either
607         (*) 'ignore' (default) - do nothing
608         (*) 'append' - only add incoming tags, that do not match an existing tag
609         (*) 'sync' - tries to do the plain wholesale thing,
610             i.e. to leave the db in sync with incoming tags
611         """
612         if options is None:
613             options = {}
614
615         # lookup 'pltags' in options to find out which mode is requested here
616         pltags = options.get('pltags', 'ignore')
617         # make sure the default is 'ignore'
618         if pltags not in ('ignore', 'append', 'sync'):
619             pltags = 'ignore'
620
621         if pltags == 'ignore':
622             logger.info(
623                 'verify_slice_tags in ignore mode - leaving slice tags as-is')
624             return
625
626         # incoming data (attributes) have a (name, value) pair
627         # while PLC data (tags) have a (tagname, value) pair
628         # we must be careful not to mix these up
629
630         # get list of tags users are able to manage - based on category
631         filter = {'category': '*slice*'}
632         if not admin:
633             filter['|roles'] = ['user']
634         valid_tag_types = self.driver.shell.GetTagTypes(filter)
635         valid_tag_names = [tag_type['tagname'] for tag_type in valid_tag_types]
636         logger.debug(
637             "verify_slice_attributes: valid names={}".format(valid_tag_names))
638
639         # get slice tags
640         slice_attributes_to_add = []
641         slice_tags_to_remove = []
642         # we need to keep the slice hrn anyway
643         ignored_slice_tag_names = ['hrn']
644         existing_slice_tags = self.driver.shell.GetSliceTags(
645             {'slice_id': slice['slice_id']})
646
647         # get tags that should be removed
648         for slice_tag in existing_slice_tags:
649             if slice_tag['tagname'] in ignored_slice_tag_names:
650                 # If a slice already has a admin only role it was probably given to them by an
651                 # admin, so we should ignore it.
652                 ignored_slice_tag_names.append(slice_tag['tagname'])
653                 tag_found = True
654             else:
655                 # If an existing slice tag was not found in the request it should
656                 # be removed
657                 tag_found = False
658                 for requested_attribute in requested_slice_attributes:
659                     if (requested_attribute['name'] == slice_tag['tagname'] and
660                             requested_attribute['value'] == slice_tag['value']):
661                         tag_found = True
662                         break
663             # remove tags only if not in append mode
664             if not tag_found and pltags != 'append':
665                 slice_tags_to_remove.append(slice_tag)
666
667         # get tags that should be added:
668         for requested_attribute in requested_slice_attributes:
669             # if the requested attribute wasn't found  we should add it
670             if requested_attribute['name'] in valid_tag_names:
671                 tag_found = False
672                 for existing_attribute in existing_slice_tags:
673                     if (requested_attribute['name'] == existing_attribute['tagname'] and \
674                             requested_attribute['value'] == existing_attribute['value']):
675                         tag_found = True
676                         break
677                 if not tag_found:
678                     slice_attributes_to_add.append(requested_attribute)
679
680         def friendly_message(tag_or_att):
681             name = tag_or_att[
682                 'tagname'] if 'tagname' in tag_or_att else tag_or_att['name']
683             return "SliceTag slice={}, tagname={} value={}, node_id={}"\
684                 .format(slice['name'], tag_or_att['name'],
685                         tag_or_att['value'], tag_or_att.get('node_id'))
686
687         # remove stale tags
688         for tag in slice_tags_to_remove:
689             try:
690                 logger.info("Removing Slice Tag {}".format(
691                     friendly_message(tag)))
692                 self.driver.shell.DeleteSliceTag(tag['slice_tag_id'])
693             except Exception as e:
694                 logger.warning("Failed to remove slice tag {}\nCause:{}"
695                                .format(friendly_message(tag), e))
696
697         # add requested_tags
698         for attribute in slice_attributes_to_add:
699             try:
700                 logger.info("Adding Slice Tag {}".format(
701                     friendly_message(attribute)))
702                 self.driver.shell.AddSliceTag(
703                     slice['name'], attribute['name'],
704                     attribute['value'], attribute.get('node_id', None))
705             except Exception as e:
706                 logger.warning("Failed to add slice tag {}\nCause:{}"
707                                .format(friendly_message(attribute), e))