blob: 7e5a9c5092b0c6268f5b93851ec64832be53962b [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
31
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050032from argparse import ArgumentParser, ArgumentError, ArgumentTypeError
33
Brad Bishop6e60e8b2018-02-01 10:27:11 -050034from wic.engine import find_canned
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050035from wic.partition import Partition
Brad Bishop6e60e8b2018-02-01 10:27:11 -050036
37logger = logging.getLogger('wic')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050038
39class KickStartError(Exception):
40 """Custom exception."""
41 pass
42
43class KickStartParser(ArgumentParser):
44 """
45 This class overwrites error method to throw exception
46 instead of producing usage message(default argparse behavior).
47 """
48 def error(self, message):
49 raise ArgumentError(None, message)
50
51def sizetype(arg):
52 """
53 Custom type for ArgumentParser
54 Converts size string in <num>[K|k|M|G] format into the integer value
55 """
56 if arg.isdigit():
Patrick Williamsc0f7c042017-02-23 20:41:17 -060057 return int(arg) * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050058
59 if not arg[:-1].isdigit():
60 raise ArgumentTypeError("Invalid size: %r" % arg)
61
62 size = int(arg[:-1])
63 if arg.endswith("k") or arg.endswith("K"):
64 return size
65 if arg.endswith("M"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060066 return size * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050067 if arg.endswith("G"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060068 return size * 1024 * 1024
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050069
70 raise ArgumentTypeError("Invalid size: %r" % arg)
71
72def overheadtype(arg):
73 """
74 Custom type for ArgumentParser
75 Converts overhead string to float and checks if it's bigger than 1.0
76 """
77 try:
78 result = float(arg)
79 except ValueError:
80 raise ArgumentTypeError("Invalid value: %r" % arg)
81
82 if result < 1.0:
83 raise ArgumentTypeError("Overhead factor should be > 1.0" % arg)
84
85 return result
86
87def cannedpathtype(arg):
88 """
89 Custom type for ArgumentParser
90 Tries to find file in the list of canned wks paths
91 """
92 scripts_path = os.path.abspath(os.path.dirname(__file__) + '../../..')
93 result = find_canned(scripts_path, arg)
94 if not result:
95 raise ArgumentTypeError("file not found: %s" % arg)
96 return result
97
Patrick Williamsc0f7c042017-02-23 20:41:17 -060098def systemidtype(arg):
99 """
100 Custom type for ArgumentParser
101 Checks if the argument sutisfies system id requirements,
102 i.e. if it's one byte long integer > 0
103 """
104 error = "Invalid system type: %s. must be hex "\
105 "between 0x1 and 0xFF" % arg
106 try:
107 result = int(arg, 16)
108 except ValueError:
109 raise ArgumentTypeError(error)
110
111 if result <= 0 or result > 0xff:
112 raise ArgumentTypeError(error)
113
114 return arg
115
116class KickStart():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 """Kickstart parser implementation."""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500118
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500119 DEFAULT_EXTRA_SPACE = 10*1024
120 DEFAULT_OVERHEAD_FACTOR = 1.3
121
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500122 def __init__(self, confpath):
123
124 self.partitions = []
125 self.bootloader = None
126 self.lineno = 0
127 self.partnum = 0
128
129 parser = KickStartParser()
130 subparsers = parser.add_subparsers()
131
132 part = subparsers.add_parser('part')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600133 part.add_argument('mountpoint', nargs='?')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500134 part.add_argument('--active', action='store_true')
135 part.add_argument('--align', type=int)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500136 part.add_argument('--exclude-path', nargs='+')
137 part.add_argument("--extra-space", type=sizetype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500138 part.add_argument('--fsoptions', dest='fsopts')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500139 part.add_argument('--fstype', default='vfat',
140 choices=('ext2', 'ext3', 'ext4', 'btrfs',
141 'squashfs', 'vfat', 'msdos', 'swap'))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500142 part.add_argument('--mkfs-extraopts', default='')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500143 part.add_argument('--label')
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800144 part.add_argument('--use-label', action='store_true')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500145 part.add_argument('--no-table', action='store_true')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500146 part.add_argument('--ondisk', '--ondrive', dest='disk', default='sda')
147 part.add_argument("--overhead-factor", type=overheadtype)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500148 part.add_argument('--part-name')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500149 part.add_argument('--part-type')
150 part.add_argument('--rootfs-dir')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500151
152 # --size and --fixed-size cannot be specified together; options
153 # ----extra-space and --overhead-factor should also raise a parser
154 # --error, but since nesting mutually exclusive groups does not work,
155 # ----extra-space/--overhead-factor are handled later
156 sizeexcl = part.add_mutually_exclusive_group()
157 sizeexcl.add_argument('--size', type=sizetype, default=0)
158 sizeexcl.add_argument('--fixed-size', type=sizetype, default=0)
159
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500160 part.add_argument('--source')
161 part.add_argument('--sourceparams')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600162 part.add_argument('--system-id', type=systemidtype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500163 part.add_argument('--use-uuid', action='store_true')
164 part.add_argument('--uuid')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400165 part.add_argument('--fsuuid')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500166
167 bootloader = subparsers.add_parser('bootloader')
168 bootloader.add_argument('--append')
169 bootloader.add_argument('--configfile')
170 bootloader.add_argument('--ptable', choices=('msdos', 'gpt'),
171 default='msdos')
172 bootloader.add_argument('--timeout', type=int)
173 bootloader.add_argument('--source')
174
175 include = subparsers.add_parser('include')
176 include.add_argument('path', type=cannedpathtype)
177
178 self._parse(parser, confpath)
179 if not self.bootloader:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500180 logger.warning('bootloader config not specified, using defaults\n')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500181 self.bootloader = bootloader.parse_args([])
182
183 def _parse(self, parser, confpath):
184 """
185 Parse file in .wks format using provided parser.
186 """
187 with open(confpath) as conf:
188 lineno = 0
189 for line in conf:
190 line = line.strip()
191 lineno += 1
192 if line and line[0] != '#':
193 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500194 line_args = shlex.split(line)
195 parsed = parser.parse_args(line_args)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500196 except ArgumentError as err:
197 raise KickStartError('%s:%d: %s' % \
198 (confpath, lineno, err))
199 if line.startswith('part'):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800200 # SquashFS does not support filesystem UUID
201 if parsed.fstype == 'squashfs':
202 if parsed.fsuuid:
203 err = "%s:%d: SquashFS does not support UUID" \
204 % (confpath, lineno)
205 raise KickStartError(err)
206 if parsed.label:
207 err = "%s:%d: SquashFS does not support LABEL" \
208 % (confpath, lineno)
209 raise KickStartError(err)
210 if parsed.use_label and not parsed.label:
211 err = "%s:%d: Must set the label with --label" \
Brad Bishop316dfdd2018-06-25 12:45:53 -0400212 % (confpath, lineno)
213 raise KickStartError(err)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500214 # using ArgumentParser one cannot easily tell if option
215 # was passed as argument, if said option has a default
216 # value; --overhead-factor/--extra-space cannot be used
217 # with --fixed-size, so at least detect when these were
218 # passed with non-0 values ...
219 if parsed.fixed_size:
220 if parsed.overhead_factor or parsed.extra_space:
221 err = "%s:%d: arguments --overhead-factor and --extra-space not "\
222 "allowed with argument --fixed-size" \
223 % (confpath, lineno)
224 raise KickStartError(err)
225 else:
226 # ... and provide defaults if not using
227 # --fixed-size iff given option was not used
228 # (again, one cannot tell if option was passed but
229 # with value equal to 0)
230 if '--overhead-factor' not in line_args:
231 parsed.overhead_factor = self.DEFAULT_OVERHEAD_FACTOR
232 if '--extra-space' not in line_args:
233 parsed.extra_space = self.DEFAULT_EXTRA_SPACE
234
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500235 self.partnum += 1
236 self.partitions.append(Partition(parsed, self.partnum))
237 elif line.startswith('include'):
238 self._parse(parser, parsed.path)
239 elif line.startswith('bootloader'):
240 if not self.bootloader:
241 self.bootloader = parsed
242 else:
243 err = "%s:%d: more than one bootloader specified" \
244 % (confpath, lineno)
245 raise KickStartError(err)