blob: 08baf76123e2a6c6af4174d46571d627c3dafe7e [file] [log] [blame]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001#!/usr/bin/env python -tt
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# Copyright (c) 2016 Intel, Inc.
6#
7# This program is free software; you can redistribute it and/or modify it
8# under the terms of the GNU General Public License as published by the Free
9# Software Foundation; version 2 of the License
10#
11# This program is distributed in the hope that it will be useful, but
12# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14# for more details.
15#
16# You should have received a copy of the GNU General Public License along
17# with this program; if not, write to the Free Software Foundation, Inc., 59
18# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19#
20# DESCRIPTION
21# This module provides parser for kickstart format
22#
23# AUTHORS
24# Ed Bartosh <ed.bartosh> (at] linux.intel.com>
25
26"""Kickstart parser module."""
27
28import os
29import shlex
Brad Bishop6e60e8b2018-02-01 10:27:11 -050030import logging
Brad Bishop19323692019-04-05 15:28:33 -040031import re
Brad Bishop6e60e8b2018-02-01 10:27:11 -050032
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050033from argparse import ArgumentParser, ArgumentError, ArgumentTypeError
34
Brad Bishop6e60e8b2018-02-01 10:27:11 -050035from wic.engine import find_canned
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050036from wic.partition import Partition
Brad Bishop19323692019-04-05 15:28:33 -040037from wic.misc import get_bitbake_var
Brad Bishop6e60e8b2018-02-01 10:27:11 -050038
39logger = logging.getLogger('wic')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050040
Brad Bishop19323692019-04-05 15:28:33 -040041__expand_var_regexp__ = re.compile(r"\${[^{}@\n\t :]+}")
42
43def expand_line(line):
44 while True:
45 m = __expand_var_regexp__.search(line)
46 if not m:
47 return line
48 key = m.group()[2:-1]
49 val = get_bitbake_var(key)
50 if val is None:
51 logger.warning("cannot expand variable %s" % key)
52 return line
53 line = line[:m.start()] + val + line[m.end():]
54
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050055class KickStartError(Exception):
56 """Custom exception."""
57 pass
58
59class KickStartParser(ArgumentParser):
60 """
61 This class overwrites error method to throw exception
62 instead of producing usage message(default argparse behavior).
63 """
64 def error(self, message):
65 raise ArgumentError(None, message)
66
67def sizetype(arg):
68 """
69 Custom type for ArgumentParser
70 Converts size string in <num>[K|k|M|G] format into the integer value
71 """
72 if arg.isdigit():
Patrick Williamsc0f7c042017-02-23 20:41:17 -060073 return int(arg) * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050074
75 if not arg[:-1].isdigit():
76 raise ArgumentTypeError("Invalid size: %r" % arg)
77
78 size = int(arg[:-1])
79 if arg.endswith("k") or arg.endswith("K"):
80 return size
81 if arg.endswith("M"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 return size * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050083 if arg.endswith("G"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060084 return size * 1024 * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050085
86 raise ArgumentTypeError("Invalid size: %r" % arg)
87
88def overheadtype(arg):
89 """
90 Custom type for ArgumentParser
91 Converts overhead string to float and checks if it's bigger than 1.0
92 """
93 try:
94 result = float(arg)
95 except ValueError:
96 raise ArgumentTypeError("Invalid value: %r" % arg)
97
98 if result < 1.0:
99 raise ArgumentTypeError("Overhead factor should be > 1.0" % arg)
100
101 return result
102
103def cannedpathtype(arg):
104 """
105 Custom type for ArgumentParser
106 Tries to find file in the list of canned wks paths
107 """
108 scripts_path = os.path.abspath(os.path.dirname(__file__) + '../../..')
109 result = find_canned(scripts_path, arg)
110 if not result:
111 raise ArgumentTypeError("file not found: %s" % arg)
112 return result
113
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600114def systemidtype(arg):
115 """
116 Custom type for ArgumentParser
117 Checks if the argument sutisfies system id requirements,
118 i.e. if it's one byte long integer > 0
119 """
120 error = "Invalid system type: %s. must be hex "\
121 "between 0x1 and 0xFF" % arg
122 try:
123 result = int(arg, 16)
124 except ValueError:
125 raise ArgumentTypeError(error)
126
127 if result <= 0 or result > 0xff:
128 raise ArgumentTypeError(error)
129
130 return arg
131
132class KickStart():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500133 """Kickstart parser implementation."""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500134
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500135 DEFAULT_EXTRA_SPACE = 10*1024
136 DEFAULT_OVERHEAD_FACTOR = 1.3
137
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500138 def __init__(self, confpath):
139
140 self.partitions = []
141 self.bootloader = None
142 self.lineno = 0
143 self.partnum = 0
144
145 parser = KickStartParser()
146 subparsers = parser.add_subparsers()
147
148 part = subparsers.add_parser('part')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600149 part.add_argument('mountpoint', nargs='?')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500150 part.add_argument('--active', action='store_true')
151 part.add_argument('--align', type=int)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500152 part.add_argument('--exclude-path', nargs='+')
153 part.add_argument("--extra-space", type=sizetype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500154 part.add_argument('--fsoptions', dest='fsopts')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500155 part.add_argument('--fstype', default='vfat',
156 choices=('ext2', 'ext3', 'ext4', 'btrfs',
157 'squashfs', 'vfat', 'msdos', 'swap'))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500158 part.add_argument('--mkfs-extraopts', default='')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500159 part.add_argument('--label')
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800160 part.add_argument('--use-label', action='store_true')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500161 part.add_argument('--no-table', action='store_true')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500162 part.add_argument('--ondisk', '--ondrive', dest='disk', default='sda')
163 part.add_argument("--overhead-factor", type=overheadtype)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500164 part.add_argument('--part-name')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500165 part.add_argument('--part-type')
166 part.add_argument('--rootfs-dir')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500167
168 # --size and --fixed-size cannot be specified together; options
169 # ----extra-space and --overhead-factor should also raise a parser
170 # --error, but since nesting mutually exclusive groups does not work,
171 # ----extra-space/--overhead-factor are handled later
172 sizeexcl = part.add_mutually_exclusive_group()
173 sizeexcl.add_argument('--size', type=sizetype, default=0)
174 sizeexcl.add_argument('--fixed-size', type=sizetype, default=0)
175
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500176 part.add_argument('--source')
177 part.add_argument('--sourceparams')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600178 part.add_argument('--system-id', type=systemidtype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500179 part.add_argument('--use-uuid', action='store_true')
180 part.add_argument('--uuid')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400181 part.add_argument('--fsuuid')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500182
183 bootloader = subparsers.add_parser('bootloader')
184 bootloader.add_argument('--append')
185 bootloader.add_argument('--configfile')
186 bootloader.add_argument('--ptable', choices=('msdos', 'gpt'),
187 default='msdos')
188 bootloader.add_argument('--timeout', type=int)
189 bootloader.add_argument('--source')
190
191 include = subparsers.add_parser('include')
192 include.add_argument('path', type=cannedpathtype)
193
194 self._parse(parser, confpath)
195 if not self.bootloader:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500196 logger.warning('bootloader config not specified, using defaults\n')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500197 self.bootloader = bootloader.parse_args([])
198
199 def _parse(self, parser, confpath):
200 """
201 Parse file in .wks format using provided parser.
202 """
203 with open(confpath) as conf:
204 lineno = 0
205 for line in conf:
206 line = line.strip()
207 lineno += 1
208 if line and line[0] != '#':
Brad Bishop19323692019-04-05 15:28:33 -0400209 line = expand_line(line)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500210 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500211 line_args = shlex.split(line)
212 parsed = parser.parse_args(line_args)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500213 except ArgumentError as err:
214 raise KickStartError('%s:%d: %s' % \
215 (confpath, lineno, err))
216 if line.startswith('part'):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800217 # SquashFS does not support filesystem UUID
218 if parsed.fstype == 'squashfs':
219 if parsed.fsuuid:
220 err = "%s:%d: SquashFS does not support UUID" \
221 % (confpath, lineno)
222 raise KickStartError(err)
223 if parsed.label:
224 err = "%s:%d: SquashFS does not support LABEL" \
225 % (confpath, lineno)
226 raise KickStartError(err)
227 if parsed.use_label and not parsed.label:
228 err = "%s:%d: Must set the label with --label" \
Brad Bishop316dfdd2018-06-25 12:45:53 -0400229 % (confpath, lineno)
230 raise KickStartError(err)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500231 # using ArgumentParser one cannot easily tell if option
232 # was passed as argument, if said option has a default
233 # value; --overhead-factor/--extra-space cannot be used
234 # with --fixed-size, so at least detect when these were
235 # passed with non-0 values ...
236 if parsed.fixed_size:
237 if parsed.overhead_factor or parsed.extra_space:
238 err = "%s:%d: arguments --overhead-factor and --extra-space not "\
239 "allowed with argument --fixed-size" \
240 % (confpath, lineno)
241 raise KickStartError(err)
242 else:
243 # ... and provide defaults if not using
244 # --fixed-size iff given option was not used
245 # (again, one cannot tell if option was passed but
246 # with value equal to 0)
247 if '--overhead-factor' not in line_args:
248 parsed.overhead_factor = self.DEFAULT_OVERHEAD_FACTOR
249 if '--extra-space' not in line_args:
250 parsed.extra_space = self.DEFAULT_EXTRA_SPACE
251
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500252 self.partnum += 1
253 self.partitions.append(Partition(parsed, self.partnum))
254 elif line.startswith('include'):
255 self._parse(parser, parsed.path)
256 elif line.startswith('bootloader'):
257 if not self.bootloader:
258 self.bootloader = parsed
259 else:
260 err = "%s:%d: more than one bootloader specified" \
261 % (confpath, lineno)
262 raise KickStartError(err)