blob: 3453d9cb9d313a3e99a3ad871c29311a1eb591ff [file] [log] [blame]
Brad Bishop96ff1982019-08-19 13:50:42 -04001#!/usr/bin/env python3
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05002#
3# Copyright (c) 2016 Intel, Inc.
4#
Brad Bishopc342db32019-05-15 21:57:59 -04005# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05006#
7# DESCRIPTION
8# This module provides parser for kickstart format
9#
10# AUTHORS
11# Ed Bartosh <ed.bartosh> (at] linux.intel.com>
12
13"""Kickstart parser module."""
14
15import os
16import shlex
Brad Bishop6e60e8b2018-02-01 10:27:11 -050017import logging
Brad Bishop19323692019-04-05 15:28:33 -040018import re
Brad Bishop6e60e8b2018-02-01 10:27:11 -050019
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050020from argparse import ArgumentParser, ArgumentError, ArgumentTypeError
21
Brad Bishop6e60e8b2018-02-01 10:27:11 -050022from wic.engine import find_canned
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050023from wic.partition import Partition
Brad Bishop19323692019-04-05 15:28:33 -040024from wic.misc import get_bitbake_var
Brad Bishop6e60e8b2018-02-01 10:27:11 -050025
26logger = logging.getLogger('wic')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050027
Brad Bishop19323692019-04-05 15:28:33 -040028__expand_var_regexp__ = re.compile(r"\${[^{}@\n\t :]+}")
29
30def expand_line(line):
31 while True:
32 m = __expand_var_regexp__.search(line)
33 if not m:
34 return line
35 key = m.group()[2:-1]
36 val = get_bitbake_var(key)
37 if val is None:
38 logger.warning("cannot expand variable %s" % key)
39 return line
40 line = line[:m.start()] + val + line[m.end():]
41
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050042class KickStartError(Exception):
43 """Custom exception."""
44 pass
45
46class KickStartParser(ArgumentParser):
47 """
48 This class overwrites error method to throw exception
49 instead of producing usage message(default argparse behavior).
50 """
51 def error(self, message):
52 raise ArgumentError(None, message)
53
Andrew Geissler4ed12e12020-06-05 18:00:41 -050054def sizetype(default):
55 def f(arg):
56 """
57 Custom type for ArgumentParser
58 Converts size string in <num>[K|k|M|G] format into the integer value
59 """
60 try:
61 suffix = default
62 size = int(arg)
63 except ValueError:
64 try:
65 suffix = arg[-1:]
66 size = int(arg[:-1])
67 except ValueError:
68 raise ArgumentTypeError("Invalid size: %r" % arg)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050069
Andrew Geissler4ed12e12020-06-05 18:00:41 -050070 if suffix == "k" or suffix == "K":
71 return size
72 if suffix == "M":
73 return size * 1024
74 if suffix == "G":
75 return size * 1024 * 1024
76
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050077 raise ArgumentTypeError("Invalid size: %r" % arg)
Andrew Geissler4ed12e12020-06-05 18:00:41 -050078 return f
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050079
80def overheadtype(arg):
81 """
82 Custom type for ArgumentParser
83 Converts overhead string to float and checks if it's bigger than 1.0
84 """
85 try:
86 result = float(arg)
87 except ValueError:
88 raise ArgumentTypeError("Invalid value: %r" % arg)
89
90 if result < 1.0:
91 raise ArgumentTypeError("Overhead factor should be > 1.0" % arg)
92
93 return result
94
95def cannedpathtype(arg):
96 """
97 Custom type for ArgumentParser
98 Tries to find file in the list of canned wks paths
99 """
100 scripts_path = os.path.abspath(os.path.dirname(__file__) + '../../..')
101 result = find_canned(scripts_path, arg)
102 if not result:
103 raise ArgumentTypeError("file not found: %s" % arg)
104 return result
105
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600106def systemidtype(arg):
107 """
108 Custom type for ArgumentParser
109 Checks if the argument sutisfies system id requirements,
110 i.e. if it's one byte long integer > 0
111 """
112 error = "Invalid system type: %s. must be hex "\
113 "between 0x1 and 0xFF" % arg
114 try:
115 result = int(arg, 16)
116 except ValueError:
117 raise ArgumentTypeError(error)
118
119 if result <= 0 or result > 0xff:
120 raise ArgumentTypeError(error)
121
122 return arg
123
124class KickStart():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125 """Kickstart parser implementation."""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500126
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500127 DEFAULT_EXTRA_SPACE = 10*1024
128 DEFAULT_OVERHEAD_FACTOR = 1.3
129
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500130 def __init__(self, confpath):
131
132 self.partitions = []
133 self.bootloader = None
134 self.lineno = 0
135 self.partnum = 0
136
137 parser = KickStartParser()
138 subparsers = parser.add_subparsers()
139
140 part = subparsers.add_parser('part')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600141 part.add_argument('mountpoint', nargs='?')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500142 part.add_argument('--active', action='store_true')
143 part.add_argument('--align', type=int)
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500144 part.add_argument('--offset', type=sizetype("K"))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500145 part.add_argument('--exclude-path', nargs='+')
Andrew Geissler82c905d2020-04-13 13:39:40 -0500146 part.add_argument('--include-path', nargs='+', action='append')
147 part.add_argument('--change-directory')
Andrew Geissler5a43b432020-06-13 10:46:56 -0500148 part.add_argument("--extra-space", type=sizetype("M"))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500149 part.add_argument('--fsoptions', dest='fsopts')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500150 part.add_argument('--fstype', default='vfat',
151 choices=('ext2', 'ext3', 'ext4', 'btrfs',
152 'squashfs', 'vfat', 'msdos', 'swap'))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500153 part.add_argument('--mkfs-extraopts', default='')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500154 part.add_argument('--label')
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800155 part.add_argument('--use-label', action='store_true')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500156 part.add_argument('--no-table', action='store_true')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500157 part.add_argument('--ondisk', '--ondrive', dest='disk', default='sda')
158 part.add_argument("--overhead-factor", type=overheadtype)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500159 part.add_argument('--part-name')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500160 part.add_argument('--part-type')
161 part.add_argument('--rootfs-dir')
Brad Bishop08902b02019-08-20 09:16:51 -0400162 part.add_argument('--type', default='primary',
163 choices = ('primary', 'logical'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500164
165 # --size and --fixed-size cannot be specified together; options
166 # ----extra-space and --overhead-factor should also raise a parser
167 # --error, but since nesting mutually exclusive groups does not work,
168 # ----extra-space/--overhead-factor are handled later
169 sizeexcl = part.add_mutually_exclusive_group()
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500170 sizeexcl.add_argument('--size', type=sizetype("M"), default=0)
171 sizeexcl.add_argument('--fixed-size', type=sizetype("M"), default=0)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500172
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500173 part.add_argument('--source')
174 part.add_argument('--sourceparams')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600175 part.add_argument('--system-id', type=systemidtype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500176 part.add_argument('--use-uuid', action='store_true')
177 part.add_argument('--uuid')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400178 part.add_argument('--fsuuid')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500179
180 bootloader = subparsers.add_parser('bootloader')
181 bootloader.add_argument('--append')
182 bootloader.add_argument('--configfile')
183 bootloader.add_argument('--ptable', choices=('msdos', 'gpt'),
184 default='msdos')
185 bootloader.add_argument('--timeout', type=int)
186 bootloader.add_argument('--source')
187
188 include = subparsers.add_parser('include')
189 include.add_argument('path', type=cannedpathtype)
190
191 self._parse(parser, confpath)
192 if not self.bootloader:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193 logger.warning('bootloader config not specified, using defaults\n')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500194 self.bootloader = bootloader.parse_args([])
195
196 def _parse(self, parser, confpath):
197 """
198 Parse file in .wks format using provided parser.
199 """
200 with open(confpath) as conf:
201 lineno = 0
202 for line in conf:
203 line = line.strip()
204 lineno += 1
205 if line and line[0] != '#':
Brad Bishop19323692019-04-05 15:28:33 -0400206 line = expand_line(line)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500207 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500208 line_args = shlex.split(line)
209 parsed = parser.parse_args(line_args)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500210 except ArgumentError as err:
211 raise KickStartError('%s:%d: %s' % \
212 (confpath, lineno, err))
213 if line.startswith('part'):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800214 # SquashFS does not support filesystem UUID
215 if parsed.fstype == 'squashfs':
216 if parsed.fsuuid:
217 err = "%s:%d: SquashFS does not support UUID" \
218 % (confpath, lineno)
219 raise KickStartError(err)
220 if parsed.label:
221 err = "%s:%d: SquashFS does not support LABEL" \
222 % (confpath, lineno)
223 raise KickStartError(err)
224 if parsed.use_label and not parsed.label:
225 err = "%s:%d: Must set the label with --label" \
Brad Bishop316dfdd2018-06-25 12:45:53 -0400226 % (confpath, lineno)
227 raise KickStartError(err)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500228 # using ArgumentParser one cannot easily tell if option
229 # was passed as argument, if said option has a default
230 # value; --overhead-factor/--extra-space cannot be used
231 # with --fixed-size, so at least detect when these were
232 # passed with non-0 values ...
233 if parsed.fixed_size:
234 if parsed.overhead_factor or parsed.extra_space:
235 err = "%s:%d: arguments --overhead-factor and --extra-space not "\
236 "allowed with argument --fixed-size" \
237 % (confpath, lineno)
238 raise KickStartError(err)
239 else:
240 # ... and provide defaults if not using
241 # --fixed-size iff given option was not used
242 # (again, one cannot tell if option was passed but
243 # with value equal to 0)
244 if '--overhead-factor' not in line_args:
245 parsed.overhead_factor = self.DEFAULT_OVERHEAD_FACTOR
246 if '--extra-space' not in line_args:
247 parsed.extra_space = self.DEFAULT_EXTRA_SPACE
248
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500249 self.partnum += 1
250 self.partitions.append(Partition(parsed, self.partnum))
251 elif line.startswith('include'):
252 self._parse(parser, parsed.path)
253 elif line.startswith('bootloader'):
254 if not self.bootloader:
255 self.bootloader = parsed
Andrew Geissler82c905d2020-04-13 13:39:40 -0500256 # Concatenate the strings set in APPEND
257 append_var = get_bitbake_var("APPEND")
258 if append_var:
259 self.bootloader.append = ' '.join(filter(None, \
260 (self.bootloader.append, append_var)))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500261 else:
262 err = "%s:%d: more than one bootloader specified" \
263 % (confpath, lineno)
264 raise KickStartError(err)