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