Initial commit
[ta/infra-ansible.git] / roles / change_kernel_cmdline / filter_plugins / change_kernel_cmdline_helpers.py
1 #!/usr/bin/python
2
3 # Copyright 2019 Nokia
4
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import itertools
18 import re
19
20 def cpulist_to_set(cl):
21     r = set()
22     for e in cl.split(','):
23         if '-' in e:
24             p = e.split('-')
25         else:
26             p = [e, e]
27         r.update(map(str, range(int(p[0]), int(p[1]) + 1)))
28     return list(r)
29
30 def set_to_cpulist(cs):
31     r = []
32     for k, g in itertools.groupby(enumerate(sorted(cs, key=int)), lambda (i, v): int(v) - i):
33         t = list(g)
34         if len(t) == 1:
35             r.append(str(t[0][1]))
36         else:
37             r.append('-'.join([str(t[0][1]), str(t[-1][1])]))
38     return ','.join(r)
39
40 def cpulist_combine(conf, name, lst):
41     r = set()
42     for s in lst:
43         if s in conf:
44             r.update(conf[s]['set'])
45     if len(r) > 0:
46         conf[name] = { 'set': sorted(r), 'list': set_to_cpulist(r) }
47     return conf
48
49 def cmdline_to_list(cmdl):
50     return re.findall('(?:[^" ]|"[^"]*")+', cmdl)
51
52 def list_to_cmdline(lst):
53     return ' '.join(lst)
54
55 class FilterModule(object):
56     def filters(self):
57         return {
58             'cpulist_to_set': cpulist_to_set,
59             'set_to_cpulist': set_to_cpulist,
60             'cpulist_combine': cpulist_combine,
61             'cmdline_to_list': cmdline_to_list,
62             'list_to_cmdline': list_to_cmdline
63         }
64