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