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