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