xref: /OK3568_Linux_fs/yocto/poky/scripts/lib/wic/partition.py (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1#
2# Copyright (c) 2013-2016 Intel Corporation.
3#
4# SPDX-License-Identifier: GPL-2.0-only
5#
6# DESCRIPTION
7# This module provides the OpenEmbedded partition object definitions.
8#
9# AUTHORS
10# Tom Zanussi <tom.zanussi (at] linux.intel.com>
11# Ed Bartosh <ed.bartosh> (at] linux.intel.com>
12
13import logging
14import os
15import uuid
16
17from wic import WicError
18from wic.misc import exec_cmd, exec_native_cmd, get_bitbake_var
19from wic.pluginbase import PluginMgr
20
21logger = logging.getLogger('wic')
22
23class Partition():
24
25    def __init__(self, args, lineno):
26        self.args = args
27        self.active = args.active
28        self.align = args.align
29        self.disk = args.disk
30        self.device = None
31        self.extra_space = args.extra_space
32        self.exclude_path = args.exclude_path
33        self.include_path = args.include_path
34        self.change_directory = args.change_directory
35        self.fsopts = args.fsopts
36        self.fstype = args.fstype
37        self.label = args.label
38        self.use_label = args.use_label
39        self.mkfs_extraopts = args.mkfs_extraopts
40        self.mountpoint = args.mountpoint
41        self.no_table = args.no_table
42        self.num = None
43        self.offset = args.offset
44        self.overhead_factor = args.overhead_factor
45        self.part_name = args.part_name
46        self.part_type = args.part_type
47        self.rootfs_dir = args.rootfs_dir
48        self.size = args.size
49        self.fixed_size = args.fixed_size
50        self.source = args.source
51        self.sourceparams = args.sourceparams
52        self.system_id = args.system_id
53        self.use_uuid = args.use_uuid
54        self.uuid = args.uuid
55        self.fsuuid = args.fsuuid
56        self.type = args.type
57        self.no_fstab_update = args.no_fstab_update
58        self.updated_fstab_path = None
59        self.has_fstab = False
60        self.update_fstab_in_rootfs = False
61
62        self.lineno = lineno
63        self.source_file = ""
64
65    def get_extra_block_count(self, current_blocks):
66        """
67        The --size param is reflected in self.size (in kB), and we already
68        have current_blocks (1k) blocks, calculate and return the
69        number of (1k) blocks we need to add to get to --size, 0 if
70        we're already there or beyond.
71        """
72        logger.debug("Requested partition size for %s: %d",
73                     self.mountpoint, self.size)
74
75        if not self.size:
76            return 0
77
78        requested_blocks = self.size
79
80        logger.debug("Requested blocks %d, current_blocks %d",
81                     requested_blocks, current_blocks)
82
83        if requested_blocks > current_blocks:
84            return requested_blocks - current_blocks
85        else:
86            return 0
87
88    def get_rootfs_size(self, actual_rootfs_size=0):
89        """
90        Calculate the required size of rootfs taking into consideration
91        --size/--fixed-size flags as well as overhead and extra space, as
92        specified in kickstart file. Raises an error if the
93        `actual_rootfs_size` is larger than fixed-size rootfs.
94
95        """
96        if self.fixed_size:
97            rootfs_size = self.fixed_size
98            if actual_rootfs_size > rootfs_size:
99                raise WicError("Actual rootfs size (%d kB) is larger than "
100                               "allowed size %d kB" %
101                               (actual_rootfs_size, rootfs_size))
102        else:
103            extra_blocks = self.get_extra_block_count(actual_rootfs_size)
104            if extra_blocks < self.extra_space:
105                extra_blocks = self.extra_space
106
107            rootfs_size = actual_rootfs_size + extra_blocks
108            rootfs_size = int(rootfs_size * self.overhead_factor)
109
110            logger.debug("Added %d extra blocks to %s to get to %d total blocks",
111                         extra_blocks, self.mountpoint, rootfs_size)
112
113        return rootfs_size
114
115    @property
116    def disk_size(self):
117        """
118        Obtain on-disk size of partition taking into consideration
119        --size/--fixed-size options.
120
121        """
122        return self.fixed_size if self.fixed_size else self.size
123
124    def prepare(self, creator, cr_workdir, oe_builddir, rootfs_dir,
125                bootimg_dir, kernel_dir, native_sysroot, updated_fstab_path):
126        """
127        Prepare content for individual partitions, depending on
128        partition command parameters.
129        """
130        self.updated_fstab_path = updated_fstab_path
131        if self.updated_fstab_path and not (self.fstype.startswith("ext") or self.fstype == "msdos"):
132            self.update_fstab_in_rootfs = True
133
134        if not self.source:
135            if self.fstype == "none":
136                return
137            if not self.size and not self.fixed_size:
138                raise WicError("The %s partition has a size of zero. Please "
139                               "specify a non-zero --size/--fixed-size for that "
140                               "partition." % self.mountpoint)
141
142            if self.fstype == "swap":
143                self.prepare_swap_partition(cr_workdir, oe_builddir,
144                                            native_sysroot)
145                self.source_file = "%s/fs.%s" % (cr_workdir, self.fstype)
146            else:
147                if self.fstype in ('squashfs', 'erofs'):
148                    raise WicError("It's not possible to create empty %s "
149                                   "partition '%s'" % (self.fstype, self.mountpoint))
150
151                rootfs = "%s/fs_%s.%s.%s" % (cr_workdir, self.label,
152                                             self.lineno, self.fstype)
153                if os.path.isfile(rootfs):
154                    os.remove(rootfs)
155
156                prefix = "ext" if self.fstype.startswith("ext") else self.fstype
157                method = getattr(self, "prepare_empty_partition_" + prefix)
158                method(rootfs, oe_builddir, native_sysroot)
159                self.source_file = rootfs
160            return
161
162        plugins = PluginMgr.get_plugins('source')
163
164        if self.source not in plugins:
165            raise WicError("The '%s' --source specified for %s doesn't exist.\n\t"
166                           "See 'wic list source-plugins' for a list of available"
167                           " --sources.\n\tSee 'wic help source-plugins' for "
168                           "details on adding a new source plugin." %
169                           (self.source, self.mountpoint))
170
171        srcparams_dict = {}
172        if self.sourceparams:
173            # Split sourceparams string of the form key1=val1[,key2=val2,...]
174            # into a dict.  Also accepts valueless keys i.e. without =
175            splitted = self.sourceparams.split(',')
176            srcparams_dict = dict((par.split('=', 1) + [None])[:2] for par in splitted if par)
177
178        plugin = PluginMgr.get_plugins('source')[self.source]
179        plugin.do_configure_partition(self, srcparams_dict, creator,
180                                      cr_workdir, oe_builddir, bootimg_dir,
181                                      kernel_dir, native_sysroot)
182        plugin.do_stage_partition(self, srcparams_dict, creator,
183                                  cr_workdir, oe_builddir, bootimg_dir,
184                                  kernel_dir, native_sysroot)
185        plugin.do_prepare_partition(self, srcparams_dict, creator,
186                                    cr_workdir, oe_builddir, bootimg_dir,
187                                    kernel_dir, rootfs_dir, native_sysroot)
188        plugin.do_post_partition(self, srcparams_dict, creator,
189                                    cr_workdir, oe_builddir, bootimg_dir,
190                                    kernel_dir, rootfs_dir, native_sysroot)
191
192        # further processing required Partition.size to be an integer, make
193        # sure that it is one
194        if not isinstance(self.size, int):
195            raise WicError("Partition %s internal size is not an integer. "
196                           "This a bug in source plugin %s and needs to be fixed." %
197                           (self.mountpoint, self.source))
198
199        if self.fixed_size and self.size > self.fixed_size:
200            raise WicError("File system image of partition %s is "
201                           "larger (%d kB) than its allowed size %d kB" %
202                           (self.mountpoint, self.size, self.fixed_size))
203
204    def prepare_rootfs(self, cr_workdir, oe_builddir, rootfs_dir,
205                       native_sysroot, real_rootfs = True, pseudo_dir = None):
206        """
207        Prepare content for a rootfs partition i.e. create a partition
208        and fill it from a /rootfs dir.
209
210        Currently handles ext2/3/4, btrfs, vfat and squashfs.
211        """
212
213        rootfs = "%s/rootfs_%s.%s.%s" % (cr_workdir, self.label,
214                                         self.lineno, self.fstype)
215        if os.path.isfile(rootfs):
216            os.remove(rootfs)
217
218        p_prefix = os.environ.get("PSEUDO_PREFIX", "%s/usr" % native_sysroot)
219        if (pseudo_dir):
220            # Canonicalize the ignore paths. This corresponds to
221            # calling oe.path.canonicalize(), which is used in bitbake.conf.
222            ignore_paths = [rootfs] + (get_bitbake_var("PSEUDO_IGNORE_PATHS") or "").split(",")
223            canonical_paths = []
224            for path in ignore_paths:
225                if "$" not in path:
226                    trailing_slash = path.endswith("/") and "/" or ""
227                    canonical_paths.append(os.path.realpath(path) + trailing_slash)
228            ignore_paths = ",".join(canonical_paths)
229
230            pseudo = "export PSEUDO_PREFIX=%s;" % p_prefix
231            pseudo += "export PSEUDO_LOCALSTATEDIR=%s;" % pseudo_dir
232            pseudo += "export PSEUDO_PASSWD=%s;" % rootfs_dir
233            pseudo += "export PSEUDO_NOSYMLINKEXP=1;"
234            pseudo += "export PSEUDO_IGNORE_PATHS=%s;" % ignore_paths
235            pseudo += "%s " % get_bitbake_var("FAKEROOTCMD")
236        else:
237            pseudo = None
238
239        if not self.size and real_rootfs:
240            # The rootfs size is not set in .ks file so try to get it
241            # from bitbake variable
242            rsize_bb = get_bitbake_var('ROOTFS_SIZE')
243            rdir = get_bitbake_var('IMAGE_ROOTFS')
244            if rsize_bb and rdir == rootfs_dir:
245                # Bitbake variable ROOTFS_SIZE is calculated in
246                # Image._get_rootfs_size method from meta/lib/oe/image.py
247                # using IMAGE_ROOTFS_SIZE, IMAGE_ROOTFS_ALIGNMENT,
248                # IMAGE_OVERHEAD_FACTOR and IMAGE_ROOTFS_EXTRA_SPACE
249                self.size = int(round(float(rsize_bb)))
250            else:
251                # Bitbake variable ROOTFS_SIZE is not defined so compute it
252                # from the rootfs_dir size using the same logic found in
253                # get_rootfs_size() from meta/classes/image.bbclass
254                du_cmd = "du -ks %s" % rootfs_dir
255                out = exec_cmd(du_cmd)
256                self.size = int(out.split()[0])
257
258        prefix = "ext" if self.fstype.startswith("ext") else self.fstype
259        method = getattr(self, "prepare_rootfs_" + prefix)
260        method(rootfs, cr_workdir, oe_builddir, rootfs_dir, native_sysroot, pseudo)
261        self.source_file = rootfs
262
263        # get the rootfs size in the right units for kickstart (kB)
264        du_cmd = "du -Lbks %s" % rootfs
265        out = exec_cmd(du_cmd)
266        self.size = int(out.split()[0])
267
268    def prepare_rootfs_ext(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
269                           native_sysroot, pseudo):
270        """
271        Prepare content for an ext2/3/4 rootfs partition.
272        """
273        du_cmd = "du -ks %s" % rootfs_dir
274        out = exec_cmd(du_cmd)
275        actual_rootfs_size = int(out.split()[0])
276
277        rootfs_size = self.get_rootfs_size(actual_rootfs_size)
278
279        with open(rootfs, 'w') as sparse:
280            os.ftruncate(sparse.fileno(), rootfs_size * 1024)
281
282        extraopts = self.mkfs_extraopts or "-F -i 8192"
283
284        label_str = ""
285        if self.label:
286            label_str = "-L %s" % self.label
287
288        mkfs_cmd = "mkfs.%s %s %s %s -U %s -d %s" % \
289            (self.fstype, extraopts, rootfs, label_str, self.fsuuid, rootfs_dir)
290        exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
291
292        if self.updated_fstab_path and self.has_fstab and not self.no_fstab_update:
293            debugfs_script_path = os.path.join(cr_workdir, "debugfs_script")
294            with open(debugfs_script_path, "w") as f:
295                f.write("cd etc\n")
296                f.write("rm fstab\n")
297                f.write("write %s fstab\n" % (self.updated_fstab_path))
298            debugfs_cmd = "debugfs -w -f %s %s" % (debugfs_script_path, rootfs)
299            exec_native_cmd(debugfs_cmd, native_sysroot)
300
301        mkfs_cmd = "fsck.%s -pvfD %s" % (self.fstype, rootfs)
302        exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
303
304        if os.getenv('SOURCE_DATE_EPOCH'):
305            sde_time = hex(int(os.getenv('SOURCE_DATE_EPOCH')))
306            debugfs_script_path = os.path.join(cr_workdir, "debugfs_script")
307            files = []
308            for root, dirs, others in os.walk(rootfs_dir):
309                base = root.replace(rootfs_dir, "").rstrip(os.sep)
310                files += [ "/" if base == "" else base ]
311                files += [ base + "/" + n for n in dirs + others ]
312            with open(debugfs_script_path, "w") as f:
313                f.write("set_current_time %s\n" % (sde_time))
314                if self.updated_fstab_path and self.has_fstab and not self.no_fstab_update:
315                    f.write("set_inode_field /etc/fstab mtime %s\n" % (sde_time))
316                    f.write("set_inode_field /etc/fstab mtime_extra 0\n")
317                for file in set(files):
318                    for time in ["atime", "ctime", "crtime"]:
319                        f.write("set_inode_field \"%s\" %s %s\n" % (file, time, sde_time))
320                        f.write("set_inode_field \"%s\" %s_extra 0\n" % (file, time))
321                for time in ["wtime", "mkfs_time", "lastcheck"]:
322                    f.write("set_super_value %s %s\n" % (time, sde_time))
323                for time in ["mtime", "first_error_time", "last_error_time"]:
324                    f.write("set_super_value %s 0\n" % (time))
325            debugfs_cmd = "debugfs -w -f %s %s" % (debugfs_script_path, rootfs)
326            exec_native_cmd(debugfs_cmd, native_sysroot)
327
328        self.check_for_Y2038_problem(rootfs, native_sysroot)
329
330    def prepare_rootfs_btrfs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
331                             native_sysroot, pseudo):
332        """
333        Prepare content for a btrfs rootfs partition.
334        """
335        du_cmd = "du -ks %s" % rootfs_dir
336        out = exec_cmd(du_cmd)
337        actual_rootfs_size = int(out.split()[0])
338
339        rootfs_size = self.get_rootfs_size(actual_rootfs_size)
340
341        with open(rootfs, 'w') as sparse:
342            os.ftruncate(sparse.fileno(), rootfs_size * 1024)
343
344        label_str = ""
345        if self.label:
346            label_str = "-L %s" % self.label
347
348        mkfs_cmd = "mkfs.%s -b %d -r %s %s %s -U %s %s" % \
349            (self.fstype, rootfs_size * 1024, rootfs_dir, label_str,
350             self.mkfs_extraopts, self.fsuuid, rootfs)
351        exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
352
353    def prepare_rootfs_msdos(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
354                             native_sysroot, pseudo):
355        """
356        Prepare content for a msdos/vfat rootfs partition.
357        """
358        du_cmd = "du -bks %s" % rootfs_dir
359        out = exec_cmd(du_cmd)
360        blocks = int(out.split()[0])
361
362        rootfs_size = self.get_rootfs_size(blocks)
363
364        label_str = "-n boot"
365        if self.label:
366            label_str = "-n %s" % self.label
367
368        size_str = ""
369
370        extraopts = self.mkfs_extraopts or '-S 512'
371
372        dosfs_cmd = "mkdosfs %s -i %s %s %s -C %s %d" % \
373                    (label_str, self.fsuuid, size_str, extraopts, rootfs,
374                     rootfs_size)
375        exec_native_cmd(dosfs_cmd, native_sysroot)
376
377        mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (rootfs, rootfs_dir)
378        exec_native_cmd(mcopy_cmd, native_sysroot)
379
380        if self.updated_fstab_path and self.has_fstab and not self.no_fstab_update:
381            mcopy_cmd = "mcopy -m -i %s %s ::/etc/fstab" % (rootfs, self.updated_fstab_path)
382            exec_native_cmd(mcopy_cmd, native_sysroot)
383
384        chmod_cmd = "chmod 644 %s" % rootfs
385        exec_cmd(chmod_cmd)
386
387    prepare_rootfs_vfat = prepare_rootfs_msdos
388
389    def prepare_rootfs_squashfs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
390                                native_sysroot, pseudo):
391        """
392        Prepare content for a squashfs rootfs partition.
393        """
394        extraopts = self.mkfs_extraopts or '-noappend'
395        squashfs_cmd = "mksquashfs %s %s %s" % \
396                       (rootfs_dir, rootfs, extraopts)
397        exec_native_cmd(squashfs_cmd, native_sysroot, pseudo=pseudo)
398
399    def prepare_rootfs_erofs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
400                             native_sysroot, pseudo):
401        """
402        Prepare content for a erofs rootfs partition.
403        """
404        extraopts = self.mkfs_extraopts or ''
405        erofs_cmd = "mkfs.erofs %s -U %s %s %s" % \
406                       (extraopts, self.fsuuid, rootfs, rootfs_dir)
407        exec_native_cmd(erofs_cmd, native_sysroot, pseudo=pseudo)
408
409    def prepare_empty_partition_none(self, rootfs, oe_builddir, native_sysroot):
410        pass
411
412    def prepare_empty_partition_ext(self, rootfs, oe_builddir,
413                                    native_sysroot):
414        """
415        Prepare an empty ext2/3/4 partition.
416        """
417        size = self.disk_size
418        with open(rootfs, 'w') as sparse:
419            os.ftruncate(sparse.fileno(), size * 1024)
420
421        extraopts = self.mkfs_extraopts or "-i 8192"
422
423        label_str = ""
424        if self.label:
425            label_str = "-L %s" % self.label
426
427        mkfs_cmd = "mkfs.%s -F %s %s -U %s %s" % \
428            (self.fstype, extraopts, label_str, self.fsuuid, rootfs)
429        exec_native_cmd(mkfs_cmd, native_sysroot)
430
431        self.check_for_Y2038_problem(rootfs, native_sysroot)
432
433    def prepare_empty_partition_btrfs(self, rootfs, oe_builddir,
434                                      native_sysroot):
435        """
436        Prepare an empty btrfs partition.
437        """
438        size = self.disk_size
439        with open(rootfs, 'w') as sparse:
440            os.ftruncate(sparse.fileno(), size * 1024)
441
442        label_str = ""
443        if self.label:
444            label_str = "-L %s" % self.label
445
446        mkfs_cmd = "mkfs.%s -b %d %s -U %s %s %s" % \
447                   (self.fstype, self.size * 1024, label_str, self.fsuuid,
448                    self.mkfs_extraopts, rootfs)
449        exec_native_cmd(mkfs_cmd, native_sysroot)
450
451    def prepare_empty_partition_msdos(self, rootfs, oe_builddir,
452                                      native_sysroot):
453        """
454        Prepare an empty vfat partition.
455        """
456        blocks = self.disk_size
457
458        label_str = "-n boot"
459        if self.label:
460            label_str = "-n %s" % self.label
461
462        size_str = ""
463
464        extraopts = self.mkfs_extraopts or '-S 512'
465
466        dosfs_cmd = "mkdosfs %s -i %s %s %s -C %s %d" % \
467                    (label_str, self.fsuuid, extraopts, size_str, rootfs,
468                     blocks)
469
470        exec_native_cmd(dosfs_cmd, native_sysroot)
471
472        chmod_cmd = "chmod 644 %s" % rootfs
473        exec_cmd(chmod_cmd)
474
475    prepare_empty_partition_vfat = prepare_empty_partition_msdos
476
477    def prepare_swap_partition(self, cr_workdir, oe_builddir, native_sysroot):
478        """
479        Prepare a swap partition.
480        """
481        path = "%s/fs.%s" % (cr_workdir, self.fstype)
482
483        with open(path, 'w') as sparse:
484            os.ftruncate(sparse.fileno(), self.size * 1024)
485
486        label_str = ""
487        if self.label:
488            label_str = "-L %s" % self.label
489
490        mkswap_cmd = "mkswap %s -U %s %s" % (label_str, self.fsuuid, path)
491        exec_native_cmd(mkswap_cmd, native_sysroot)
492
493    def check_for_Y2038_problem(self, rootfs, native_sysroot):
494        """
495        Check if the filesystem is affected by the Y2038 problem
496        (Y2038 problem = 32 bit time_t overflow in January 2038)
497        """
498        def get_err_str(part):
499            err = "The {} filesystem {} has no Y2038 support."
500            if part.mountpoint:
501                args = [part.fstype, "mounted at %s" % part.mountpoint]
502            elif part.label:
503                args = [part.fstype, "labeled '%s'" % part.label]
504            elif part.part_name:
505                args = [part.fstype, "in partition '%s'" % part.part_name]
506            else:
507                args = [part.fstype, "in partition %s" % part.num]
508            return err.format(*args)
509
510        # ext2 and ext3 are always affected by the Y2038 problem
511        if self.fstype in ["ext2", "ext3"]:
512            logger.warn(get_err_str(self))
513            return
514
515        ret, out = exec_native_cmd("dumpe2fs %s" % rootfs, native_sysroot)
516
517        # if ext4 is affected by the Y2038 problem depends on the inode size
518        for line in out.splitlines():
519            if line.startswith("Inode size:"):
520                size = int(line.split(":")[1].strip())
521                if size < 256:
522                    logger.warn("%s Inodes (of size %d) are too small." %
523                                (get_err_str(self), size))
524                break
525
526