blob: e590b2fe3c0d17febc0b97a8ec1754d6748c2e9f [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')
144 part.add_argument('--no-table', action='store_true')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500145 part.add_argument('--ondisk', '--ondrive', dest='disk', default='sda')
146 part.add_argument("--overhead-factor", type=overheadtype)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500147 part.add_argument('--part-name')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500148 part.add_argument('--part-type')
149 part.add_argument('--rootfs-dir')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500150
151 # --size and --fixed-size cannot be specified together; options
152 # ----extra-space and --overhead-factor should also raise a parser
153 # --error, but since nesting mutually exclusive groups does not work,
154 # ----extra-space/--overhead-factor are handled later
155 sizeexcl = part.add_mutually_exclusive_group()
156 sizeexcl.add_argument('--size', type=sizetype, default=0)
157 sizeexcl.add_argument('--fixed-size', type=sizetype, default=0)
158
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500159 part.add_argument('--source')
160 part.add_argument('--sourceparams')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600161 part.add_argument('--system-id', type=systemidtype)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500162 part.add_argument('--use-uuid', action='store_true')
163 part.add_argument('--uuid')
Brad Bishop316dfdd2018-06-25 12:45:53 -0400164 part.add_argument('--fsuuid')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500165
166 bootloader = subparsers.add_parser('bootloader')
167 bootloader.add_argument('--append')
168 bootloader.add_argument('--configfile')
169 bootloader.add_argument('--ptable', choices=('msdos', 'gpt'),
170 default='msdos')
171 bootloader.add_argument('--timeout', type=int)
172 bootloader.add_argument('--source')
173
174 include = subparsers.add_parser('include')
175 include.add_argument('path', type=cannedpathtype)
176
177 self._parse(parser, confpath)
178 if not self.bootloader:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500179 logger.warning('bootloader config not specified, using defaults\n')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500180 self.bootloader = bootloader.parse_args([])
181
182 def _parse(self, parser, confpath):
183 """
184 Parse file in .wks format using provided parser.
185 """
186 with open(confpath) as conf:
187 lineno = 0
188 for line in conf:
189 line = line.strip()
190 lineno += 1
191 if line and line[0] != '#':
192 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193 line_args = shlex.split(line)
194 parsed = parser.parse_args(line_args)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500195 except ArgumentError as err:
196 raise KickStartError('%s:%d: %s' % \
197 (confpath, lineno, err))
198 if line.startswith('part'):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400199 # SquashFS does not support UUID
200 if parsed.fstype == 'squashfs' and parsed.use_uuid:
201 err = "%s:%d: SquashFS does not support UUID" \
202 % (confpath, lineno)
203 raise KickStartError(err)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500204 # using ArgumentParser one cannot easily tell if option
205 # was passed as argument, if said option has a default
206 # value; --overhead-factor/--extra-space cannot be used
207 # with --fixed-size, so at least detect when these were
208 # passed with non-0 values ...
209 if parsed.fixed_size:
210 if parsed.overhead_factor or parsed.extra_space:
211 err = "%s:%d: arguments --overhead-factor and --extra-space not "\
212 "allowed with argument --fixed-size" \
213 % (confpath, lineno)
214 raise KickStartError(err)
215 else:
216 # ... and provide defaults if not using
217 # --fixed-size iff given option was not used
218 # (again, one cannot tell if option was passed but
219 # with value equal to 0)
220 if '--overhead-factor' not in line_args:
221 parsed.overhead_factor = self.DEFAULT_OVERHEAD_FACTOR
222 if '--extra-space' not in line_args:
223 parsed.extra_space = self.DEFAULT_EXTRA_SPACE
224
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500225 self.partnum += 1
226 self.partitions.append(Partition(parsed, self.partnum))
227 elif line.startswith('include'):
228 self._parse(parser, parsed.path)
229 elif line.startswith('bootloader'):
230 if not self.bootloader:
231 self.bootloader = parsed
232 else:
233 err = "%s:%d: more than one bootloader specified" \
234 % (confpath, lineno)
235 raise KickStartError(err)