refine strategy to spot ip address, keep on calling guest_ipv4
[build.git] / pkgs.py
1 #!/usr/bin/env python3
2 #
3 # This is a replacement for the formerly bash-written function pl_parsePkgs ()
4 #
5 # Usage: $0  [-a arch] default_arch keyword fcdistro pldistro pkgs-file[..s]
6 # default_arch is $pl_DISTRO_ARCH, but can be overridden
7 #
8
9 #################### original language was (in this example, keyword=package)
10 ## to add to all distros
11 # package: p1 p2
12 ## to add in one distro
13 # package+f12: p1 p2
14 ## to remove in one distro
15 # package-f10: p1 p2
16 #################### replacement language
17 ## add in distro f10
18 # +package=f10: p1 p2
19 # or simply
20 # package=f10: p1 p2
21 ## add in fedora distros starting with f10
22 # +package>=f10: p1 p2
23 # or simply
24 # package>=f10: p1 p2
25 ## ditto but remove instead
26 # -package=centos5: p1 p2
27 # -package<=centos5: p1 p2
28
29 # pylint: disable=c0111
30
31
32 import sys
33 from sys import stderr
34 from optparse import OptionParser
35 import re
36
37 default_arch = 'x86_64'
38 known_archs = ['i386', 'i686', 'x86_64']
39 default_fcdistro = 'f33'
40 known_fcdistros = [
41     'centos5', 'centos6',
42     # oldies but we have references to that in the pkgs files
43     'f8', 'f10', 'f12', 'f14', 'f16', 'f18', 
44     'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f27', 
45     # these ones are still relevant;
46     # f32 is mentioned to be able to use create-vms with that distro
47     # as we're running into issues to build a minimal f33 from a f29 host
48     'f29', 'f31', 'f32', 'f33',
49     # scientific linux
50     'sl6',
51     # debians
52     'wheezy', 'jessie',
53     # ubuntus
54     'trusty',  # 14.04 LTS
55     'xenial',  # 16.04 LTS
56     'bionic',  # 18.04 LTS
57 ]
58 default_pldistro = 'onelab'
59
60 known_keywords = [
61     'group', 'groupname', 'groupdesc',
62      'package', 'pip', 'gem',
63     'nodeyumexclude', 'plcyumexclude', 'yumexclude',
64     'precious', 'junk', 'mirror',
65 ]
66
67
68 m_fcdistro_cutter = re.compile('([a-z]+)([0-9]+)')
69 re_ident = '[a-z]+'
70
71 class PkgsParser:
72
73     def __init__(self, arch, fcdistro, pldistro, keyword, inputs, options):
74         self.arch = arch
75         self.fcdistro = fcdistro
76         self.pldistro = pldistro
77         self.keyword = keyword
78         self.inputs = inputs
79         # for verbose, new_line, and the like
80         self.options = options
81         ok = False
82         for known in known_fcdistros:
83             if fcdistro == known:
84                 try:
85                     (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
86                 # debian-like names can't use numbering
87                 except:
88                     distro = fcdistro
89                     version = 0
90                 ok = True
91         if ok:
92             self.distro = distro
93             self.version = int(version)
94         else:
95             print('unrecognized fcdistro', fcdistro, file=stderr)
96             sys.exit(1)
97
98     # qualifier is either '>=','<=', or '='
99     def match(self, qualifier, version):
100         if qualifier == '=':
101             return self.version == version
102         elif qualifier == '>=':
103             return self.version >= version
104         elif qualifier == '<=':
105             return self.version <= version
106         else:
107             raise Exception(
108                 'Internal error - unexpected qualifier {}'.format(qualifier))
109
110     m_comment = re.compile(r'\A\s*#')
111     m_blank = re.compile(r'\A\s*\Z')
112
113     m_ident = re.compile(r'\A'+re_ident+r'\Z')
114     re_qualified = r'\s*'
115     re_qualified += r'(?P<plus_minus>[+-]?)'
116     re_qualified += r'\s*'
117     re_qualified += r'(?P<keyword>{re_ident})'.format(re_ident=re_ident)
118     re_qualified += r'\s*'
119     re_qualified += r'(?P<qualifier>>=|<=|=)'
120     re_qualified += r'\s*'
121     re_qualified += r'(?P<fcdistro>{re_ident}[0-9]+)'.format(re_ident=re_ident)
122     re_qualified += r'\s*'
123     m_qualified = re.compile(r'\A{re_qualified}\Z'.format(re_qualified=re_qualified))
124
125     re_old = '[a-z]+[+-][a-z]+[0-9]+'
126     m_old = re.compile(r'\A{}\Z'.format(re_old))
127
128     # returns a tuple (included, excluded)
129     def parse(self, filename):
130         ok = True
131         included = []
132         excluded = []
133         try:
134             with open(filename) as feed:
135                 for lineno, line in enumerate(feed, 1):
136                     line = line.strip()
137                     if self.m_comment.match(line) or self.m_blank.match(line):
138                         continue
139                     try:
140                         lefts, rights = line.split(':', 1)
141                         for left in lefts.split():
142                             ########## single ident
143                             if self.m_ident.match(left):
144                                 if left not in known_keywords:
145                                     raise Exception("Unknown keyword {left}".format(**locals()))
146                                 elif left == self.keyword:
147                                     included += rights.split()
148                             else:
149                                 m = self.m_qualified.match(left)
150                                 if m:
151                                     (plus_minus, kw, qual, fcdistro) = m.groups()
152                                     if kw not in known_keywords:
153                                         raise Exception("Unknown keyword in {left}".format(**locals()))
154                                     if fcdistro not in known_fcdistros:
155                                         raise Exception('Unknown fcdistro {fcdistro}'.format(**locals()))
156                                     # skip if another keyword
157                                     if kw != self.keyword: continue
158                                     # does this fcdistro match ?
159                                     (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
160                                     version = int (version)
161                                     # skip if another distro family
162                                     if distro != self.distro: continue
163                                     # skip if the qualifier does not fit
164                                     if not self.match (qual, version):
165                                         if self.options.verbose:
166                                             print('{filename}:{lineno}:qualifer {left} does not apply'
167                                                   .format(**locals()), file=stderr)
168                                         continue
169                                     # we're in, let's add (default) or remove (if plus_minus is minus)
170                                     if plus_minus == '-':
171                                         if self.options.verbose:
172                                             print('{filename}:{lineno}: from {left}, excluding {rights}'
173                                                   .format(**locals()), file=stderr)
174                                         excluded += rights.split()
175                                     else:
176                                         if self.options.verbose:
177                                             print('{filename}:{lineno}: from {left}, including {rights}'\
178                                                   .format(**locals()), file=stderr)
179                                         included += rights.split()
180                                 elif self.m_old.match(left):
181                                     raise Exception('Old-fashioned syntax not supported anymore {left}'.\
182                                                     format(**locals()))
183                                 else:
184                                     raise Exception('error in left expression {left}'.format(**locals()))
185
186                     except Exception as e:
187                         ok = False
188                         print("{filename}:{lineno}:syntax error: {e}".format(**locals()), file=stderr)
189         except Exception as exc:
190             ok = False
191             print('Could not parse file', filename, exc, file=stderr)
192         return (ok, included, excluded)
193
194     def run (self):
195         ok = True
196         included = []
197         excluded = []
198         for input in self.inputs:
199             (o, i, e) = self.parse (input)
200             included += i
201             excluded += e
202             ok = ok and o
203         # avoid set operations that would not preserve order
204         results = [x for x in included if x not in excluded]
205
206         results = [x.replace('@arch@', self.arch)
207                    .replace('@fcdistro@', self.fcdistro)
208                    .replace('@pldistro@', self.pldistro) for x in results]
209         if self.options.sort_results:
210             results.sort()
211         # default is space-separated
212         if not self.options.new_line:
213             print(" ".join(results))
214         # but for tests results are printed each on a line
215         else:
216             for result in results:
217                 print(result)
218         return ok
219
220 def main ():
221     usage = "Usage: %prog [options] keyword input[...]"
222     parser = OptionParser(usage=usage)
223     parser.add_option(
224         '-a', '--arch', dest='arch', action='store', default=default_arch,
225         help='target arch, e.g. i386 or x86_64, default={}'.format(default_arch))
226     parser.add_option(
227         '-f', '--fcdistro', dest='fcdistro', action='store', default=default_fcdistro,
228         help='fcdistro, e.g. f12 or centos5')
229     parser.add_option(
230         '-d', '--pldistro', dest='pldistro', action='store', default=default_pldistro,
231         help='pldistro, e.g. onelab or planetlab')
232     parser.add_option(
233         '-v', '--verbose', dest='verbose', action='store_true', default=False,
234         help='verbose when using qualifiers')
235     parser.add_option(
236         '-n', '--new-line', dest='new_line', action='store_true', default=False,
237         help='print outputs separated with newlines rather than with a space')
238     parser.add_option(
239         '-u', '--no-sort', dest='sort_results', default=True, action='store_false',
240         help='keep results in the same order as in the inputs')
241     (options, args) = parser.parse_args()
242
243     if len(args) <= 1:
244         parser.print_help(file=stderr)
245         sys.exit(1)
246     keyword = args[0]
247     inputs = args[1:]
248     if options.arch not in known_archs:
249         print('Unsupported arch', options.arch, file=stderr)
250         parser.print_help(file=stderr)
251         sys.exit(1)
252     if options.arch == 'i686':
253         options.arch = 'i386'
254     if options.fcdistro not in known_fcdistros:
255         print('Unsupported fcdistro', options.fcdistro, file=stderr)
256         parser.print_help(file=stderr)
257         sys.exit(1)
258
259     pkgs = PkgsParser(options.arch, options.fcdistro, options.pldistro,
260                       keyword, inputs, options)
261
262     if pkgs.run():
263         sys.exit(0)
264     else:
265         sys.exit(1)
266
267 if __name__ == '__main__':
268     if main():
269         sys.exit(0)
270     else:
271         sys.exit(1)