Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2018 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Script to generate a DLC (Downloadable Content) artifact.""" |
| 7 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | import hashlib |
| 11 | import json |
| 12 | import math |
| 13 | import os |
| 14 | |
| 15 | from chromite.lib import commandline |
| 16 | from chromite.lib import cros_build_lib |
| 17 | from chromite.lib import osutils |
| 18 | |
| 19 | |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 20 | DLC_META_DIR = 'opt/google/dlc/' |
| 21 | DLC_IMAGE_DIR = 'build/rootfs/dlc/' |
Amin Hassani | d5742d3 | 2019-01-22 21:13:34 -0800 | [diff] [blame^] | 22 | LSB_RELEASE = 'etc/lsb-release' |
| 23 | |
| 24 | DLC_ID_KEY = 'DLC_ID' |
| 25 | DLC_NAME_KEY = 'DLC_NAME' |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 26 | |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 27 | _SQUASHFS_TYPE = 'squashfs' |
| 28 | _EXT4_TYPE = 'ext4' |
| 29 | |
Amin Hassani | d5742d3 | 2019-01-22 21:13:34 -0800 | [diff] [blame^] | 30 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 31 | def HashFile(file_path): |
| 32 | """Calculate the sha256 hash of a file. |
| 33 | |
| 34 | Args: |
| 35 | file_path: (str) path to the file. |
| 36 | |
| 37 | Returns: |
| 38 | [str]: The sha256 hash of the file. |
| 39 | """ |
| 40 | sha256 = hashlib.sha256() |
| 41 | with open(file_path, 'rb') as f: |
| 42 | for b in iter(lambda: f.read(2048), b''): |
| 43 | sha256.update(b) |
| 44 | return sha256.hexdigest() |
| 45 | |
| 46 | |
Amin Hassani | 174eb7e | 2019-01-18 11:11:24 -0800 | [diff] [blame] | 47 | class DlcGenerator(object): |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 48 | """Object to generate DLC artifacts.""" |
| 49 | # Block size for the DLC image. |
| 50 | # We use 4K for various reasons: |
| 51 | # 1. it's what imageloader (linux kernel) supports. |
| 52 | # 2. it's what verity supports. |
| 53 | _BLOCK_SIZE = 4096 |
| 54 | # Blocks in the initial sparse image. |
| 55 | _BLOCKS = 500000 |
| 56 | # Version of manifest file. |
| 57 | _MANIFEST_VERSION = 1 |
| 58 | |
Amin Hassani | cc7ffce | 2019-01-11 14:57:52 -0800 | [diff] [blame] | 59 | # The DLC root path inside the DLC module. |
| 60 | _DLC_ROOT_DIR = 'root' |
| 61 | |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 62 | def __init__(self, src_dir, install_root_dir, fs_type, pre_allocated_blocks, |
Colin Howes | fc60768 | 2018-09-28 16:46:32 -0700 | [diff] [blame] | 63 | version, dlc_id, name): |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 64 | """Object initializer. |
| 65 | |
| 66 | Args: |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 67 | src_dir: (str) path to the DLC source root directory. |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 68 | install_root_dir: (str) The path to the root installation directory. |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 69 | fs_type: (str) file system type. |
| 70 | pre_allocated_blocks: (int) number of blocks pre-allocated on device. |
| 71 | version: (str) DLC version. |
| 72 | dlc_id: (str) DLC ID. |
| 73 | name: (str) DLC name. |
| 74 | """ |
| 75 | self.src_dir = src_dir |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 76 | self.install_root_dir = install_root_dir |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 77 | self.fs_type = fs_type |
| 78 | self.pre_allocated_blocks = pre_allocated_blocks |
| 79 | self.version = version |
| 80 | self.dlc_id = dlc_id |
| 81 | self.name = name |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 82 | |
| 83 | self.meta_dir = os.path.join(self.install_root_dir, DLC_META_DIR, |
| 84 | self.dlc_id) |
| 85 | self.image_dir = os.path.join(self.install_root_dir, DLC_IMAGE_DIR, |
| 86 | self.dlc_id) |
| 87 | osutils.SafeMakedirs(self.meta_dir) |
| 88 | osutils.SafeMakedirs(self.image_dir) |
| 89 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 90 | # Create path for all final artifacts. |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 91 | self.dest_image = os.path.join(self.image_dir, 'dlc.img') |
| 92 | self.dest_table = os.path.join(self.meta_dir, 'table') |
| 93 | self.dest_imageloader_json = os.path.join(self.meta_dir, 'imageloader.json') |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 94 | |
| 95 | def SquashOwnerships(self, path): |
| 96 | """Squash the owernships & permissions for files. |
| 97 | |
| 98 | Args: |
| 99 | path: (str) path that contains all files to be processed. |
| 100 | """ |
| 101 | cros_build_lib.SudoRunCommand(['chown', '-R', '0:0', path]) |
| 102 | cros_build_lib.SudoRunCommand( |
| 103 | ['find', path, '-exec', 'touch', '-h', '-t', '197001010000.00', '{}', |
| 104 | '+']) |
| 105 | |
| 106 | def CreateExt4Image(self): |
| 107 | """Create an ext4 image.""" |
| 108 | with osutils.TempDir(prefix='dlc_') as temp_dir: |
| 109 | mount_point = os.path.join(temp_dir, 'mount_point') |
| 110 | # Create a raw image file. |
| 111 | with open(self.dest_image, 'w') as f: |
| 112 | f.truncate(self._BLOCKS * self._BLOCK_SIZE) |
| 113 | # Create an ext4 file system on the raw image. |
| 114 | cros_build_lib.RunCommand( |
| 115 | ['/sbin/mkfs.ext4', '-b', str(self._BLOCK_SIZE), '-O', |
| 116 | '^has_journal', self.dest_image], capture_output=True) |
| 117 | # Create the mount_point directory. |
| 118 | osutils.SafeMakedirs(mount_point) |
| 119 | # Mount the ext4 image. |
| 120 | osutils.MountDir(self.dest_image, mount_point, mount_opts=('loop', 'rw')) |
Amin Hassani | cc7ffce | 2019-01-11 14:57:52 -0800 | [diff] [blame] | 121 | |
| 122 | dlc_root_dir = os.path.join(mount_point, self._DLC_ROOT_DIR) |
| 123 | osutils.SafeMakedirs(dlc_root_dir) |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 124 | try: |
| 125 | # Copy DLC files over to the image. |
Colin Howes | 839c004 | 2018-12-03 14:50:43 -0800 | [diff] [blame] | 126 | osutils.CopyDirContents(self.src_dir, dlc_root_dir) |
Amin Hassani | d5742d3 | 2019-01-22 21:13:34 -0800 | [diff] [blame^] | 127 | self.PrepareLsbRelease(mount_point) |
Colin Howes | 839c004 | 2018-12-03 14:50:43 -0800 | [diff] [blame] | 128 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 129 | self.SquashOwnerships(mount_point) |
| 130 | finally: |
| 131 | # Unmount the ext4 image. |
| 132 | osutils.UmountDir(mount_point) |
| 133 | # Shrink to minimum size. |
| 134 | cros_build_lib.RunCommand( |
| 135 | ['/sbin/e2fsck', '-y', '-f', self.dest_image], capture_output=True) |
| 136 | cros_build_lib.RunCommand( |
| 137 | ['/sbin/resize2fs', '-M', self.dest_image], capture_output=True) |
| 138 | |
| 139 | def CreateSquashfsImage(self): |
| 140 | """Create a squashfs image.""" |
| 141 | with osutils.TempDir(prefix='dlc_') as temp_dir: |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 142 | squashfs_root = os.path.join(temp_dir, 'squashfs-root') |
Amin Hassani | cc7ffce | 2019-01-11 14:57:52 -0800 | [diff] [blame] | 143 | dlc_root_dir = os.path.join(squashfs_root, self._DLC_ROOT_DIR) |
| 144 | osutils.SafeMakedirs(dlc_root_dir) |
Colin Howes | 839c004 | 2018-12-03 14:50:43 -0800 | [diff] [blame] | 145 | osutils.CopyDirContents(self.src_dir, dlc_root_dir) |
Amin Hassani | d5742d3 | 2019-01-22 21:13:34 -0800 | [diff] [blame^] | 146 | self.PrepareLsbRelease(squashfs_root) |
Amin Hassani | cc7ffce | 2019-01-11 14:57:52 -0800 | [diff] [blame] | 147 | |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 148 | self.SquashOwnerships(squashfs_root) |
| 149 | |
| 150 | cros_build_lib.RunCommand(['mksquashfs', squashfs_root, self.dest_image, |
| 151 | '-4k-align', '-noappend'], |
| 152 | capture_output=True) |
| 153 | |
| 154 | # We changed the ownership and permissions of the squashfs_root |
| 155 | # directory. Now we need to remove it manually. |
| 156 | osutils.RmDir(squashfs_root, sudo=True) |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 157 | |
Amin Hassani | d5742d3 | 2019-01-22 21:13:34 -0800 | [diff] [blame^] | 158 | def PrepareLsbRelease(self, dlc_dir): |
| 159 | """Prepare the file /etc/lsb-release in the DLC module. |
| 160 | |
| 161 | This file is used dropping some identification parameters for the DLC. |
| 162 | |
| 163 | Args: |
| 164 | dlc_dir: (str) The path to root directory of the DLC. e.g. mounted point |
| 165 | when we are creating the image. |
| 166 | """ |
| 167 | lsb_release = os.path.join(dlc_dir, LSB_RELEASE) |
| 168 | osutils.SafeMakedirs(os.path.dirname(lsb_release)) |
| 169 | |
| 170 | fields = { |
| 171 | DLC_ID_KEY: self.dlc_id, |
| 172 | DLC_NAME_KEY: self.name, |
| 173 | } |
| 174 | content = ''.join(['%s=%s\n' % (k, v) for k, v in fields.items()]) |
| 175 | osutils.WriteFile(lsb_release, content) |
| 176 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 177 | def CreateImage(self): |
| 178 | """Create the image and copy the DLC files to it.""" |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 179 | if self.fs_type == _EXT4_TYPE: |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 180 | self.CreateExt4Image() |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 181 | elif self.fs_type == _SQUASHFS_TYPE: |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 182 | self.CreateSquashfsImage() |
| 183 | else: |
| 184 | raise ValueError('Wrong fs type: %s used:' % self.fs_type) |
| 185 | |
| 186 | def GetImageloaderJsonContent(self, image_hash, table_hash, blocks): |
| 187 | """Return the content of imageloader.json file. |
| 188 | |
| 189 | Args: |
| 190 | image_hash: (str) sha256 hash of the DLC image. |
| 191 | table_hash: (str) sha256 hash of the DLC table file. |
| 192 | blocks: (int) number of blocks in the DLC image. |
| 193 | |
| 194 | Returns: |
| 195 | [str]: content of imageloader.json file. |
| 196 | """ |
| 197 | return { |
| 198 | 'fs-type': self.fs_type, |
| 199 | 'id': self.dlc_id, |
| 200 | 'image-sha256-hash': image_hash, |
| 201 | 'image-type': 'dlc', |
| 202 | 'is-removable': True, |
| 203 | 'manifest-version': self._MANIFEST_VERSION, |
| 204 | 'name': self.name, |
| 205 | 'pre-allocated-size': self.pre_allocated_blocks * self._BLOCK_SIZE, |
| 206 | 'size': blocks * self._BLOCK_SIZE, |
| 207 | 'table-sha256-hash': table_hash, |
| 208 | 'version': self.version, |
| 209 | } |
| 210 | |
| 211 | def GenerateVerity(self): |
| 212 | """Generate verity parameters and hashes for the image.""" |
| 213 | with osutils.TempDir(prefix='dlc_') as temp_dir: |
| 214 | hash_tree = os.path.join(temp_dir, 'hash_tree') |
| 215 | # Get blocks in the image. |
| 216 | blocks = math.ceil( |
| 217 | os.path.getsize(self.dest_image) / self._BLOCK_SIZE) |
| 218 | result = cros_build_lib.RunCommand( |
| 219 | ['verity', 'mode=create', 'alg=sha256', 'payload=' + self.dest_image, |
| 220 | 'payload_blocks=' + str(blocks), 'hashtree=' + hash_tree, |
| 221 | 'salt=random'], capture_output=True) |
| 222 | table = result.output |
| 223 | |
| 224 | # Append the merkle tree to the image. |
| 225 | osutils.WriteFile(self.dest_image, osutils.ReadFile(hash_tree), 'a+') |
| 226 | |
| 227 | # Write verity parameter to table file. |
| 228 | osutils.WriteFile(self.dest_table, table) |
| 229 | |
| 230 | # Compute image hash. |
| 231 | image_hash = HashFile(self.dest_image) |
| 232 | table_hash = HashFile(self.dest_table) |
| 233 | # Write image hash to imageloader.json file. |
| 234 | blocks = math.ceil( |
| 235 | os.path.getsize(self.dest_image) / self._BLOCK_SIZE) |
| 236 | imageloader_json_content = self.GetImageloaderJsonContent( |
| 237 | image_hash, table_hash, int(blocks)) |
| 238 | with open(self.dest_imageloader_json, 'w') as f: |
| 239 | json.dump(imageloader_json_content, f) |
| 240 | |
| 241 | def GenerateDLC(self): |
| 242 | """Generate a DLC artifact.""" |
| 243 | # Create the image and copy the DLC files to it. |
| 244 | self.CreateImage() |
| 245 | # Generate hash tree and other metadata. |
| 246 | self.GenerateVerity() |
| 247 | |
| 248 | |
| 249 | def GetParser(): |
| 250 | parser = commandline.ArgumentParser(description=__doc__) |
| 251 | # Required arguments: |
| 252 | required = parser.add_argument_group('Required Arguments') |
| 253 | required.add_argument('--src-dir', type='path', metavar='SRC_DIR_PATH', |
| 254 | required=True, |
| 255 | help='Root directory path that contains all DLC files ' |
| 256 | 'to be packed.') |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 257 | required.add_argument('--install-root-dir', type='path', metavar='DIR', |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 258 | required=True, |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 259 | help='The root path to install DLC images (in %s) and ' |
| 260 | 'metadata (in %s).' % (DLC_IMAGE_DIR, DLC_META_DIR)) |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 261 | required.add_argument('--pre-allocated-blocks', type=int, |
| 262 | metavar='PREALLOCATEDBLOCKS', required=True, |
| 263 | help='Number of blocks (block size is 4k) that need to' |
| 264 | 'be pre-allocated on device.') |
| 265 | required.add_argument('--version', metavar='VERSION', required=True, |
| 266 | help='DLC Version.') |
| 267 | required.add_argument('--id', metavar='ID', required=True, |
| 268 | help='DLC ID (unique per DLC).') |
| 269 | required.add_argument('--name', metavar='NAME', required=True, |
| 270 | help='A human-readable name for the DLC.') |
Amin Hassani | 22a25eb | 2019-01-11 14:25:02 -0800 | [diff] [blame] | 271 | |
| 272 | args = parser.add_argument_group('Arguments') |
| 273 | args.add_argument('--fs-type', metavar='FS_TYPE', default=_SQUASHFS_TYPE, |
| 274 | choices=(_SQUASHFS_TYPE, _EXT4_TYPE), |
| 275 | help='File system type of the image.') |
| 276 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 277 | return parser |
| 278 | |
| 279 | |
| 280 | def main(argv): |
| 281 | opts = GetParser().parse_args(argv) |
| 282 | opts.Freeze() |
| 283 | |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 284 | if opts.fs_type == _EXT4_TYPE: |
| 285 | raise Exception('ext4 unsupported, see https://crbug.com/890060') |
| 286 | |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 287 | # Generate final DLC files. |
Amin Hassani | 2af75a9 | 2019-01-22 21:07:45 -0800 | [diff] [blame] | 288 | dlc_generator = DlcGenerator(opts.src_dir, opts.install_root_dir, |
Colin Howes | fc60768 | 2018-09-28 16:46:32 -0700 | [diff] [blame] | 289 | opts.fs_type, opts.pre_allocated_blocks, |
| 290 | opts.version, opts.id, opts.name) |
Xiaochu Liu | deed023 | 2018-06-26 10:25:34 -0700 | [diff] [blame] | 291 | dlc_generator.GenerateDLC() |