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