blob: 2b11e152636ab34d1fba4914560140cd4be91f47 [file] [log] [blame]
Xiaochu Liudeed0232018-06-26 10:25:34 -07001# -*- 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
8from __future__ import print_function
9
10import hashlib
11import json
12import math
13import os
14
15from chromite.lib import commandline
16from chromite.lib import cros_build_lib
17from chromite.lib import osutils
18
19
Amin Hassani2af75a92019-01-22 21:07:45 -080020DLC_META_DIR = 'opt/google/dlc/'
21DLC_IMAGE_DIR = 'build/rootfs/dlc/'
Amin Hassanid5742d32019-01-22 21:13:34 -080022LSB_RELEASE = 'etc/lsb-release'
23
24DLC_ID_KEY = 'DLC_ID'
25DLC_NAME_KEY = 'DLC_NAME'
Amin Hassani2af75a92019-01-22 21:07:45 -080026
Amin Hassani22a25eb2019-01-11 14:25:02 -080027_SQUASHFS_TYPE = 'squashfs'
28_EXT4_TYPE = 'ext4'
29
Amin Hassanid5742d32019-01-22 21:13:34 -080030
Xiaochu Liudeed0232018-06-26 10:25:34 -070031def 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 Hassani174eb7e2019-01-18 11:11:24 -080047class DlcGenerator(object):
Xiaochu Liudeed0232018-06-26 10:25:34 -070048 """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 Hassanicc7ffce2019-01-11 14:57:52 -080059 # The DLC root path inside the DLC module.
60 _DLC_ROOT_DIR = 'root'
61
Amin Hassani2af75a92019-01-22 21:07:45 -080062 def __init__(self, src_dir, install_root_dir, fs_type, pre_allocated_blocks,
Colin Howesfc607682018-09-28 16:46:32 -070063 version, dlc_id, name):
Xiaochu Liudeed0232018-06-26 10:25:34 -070064 """Object initializer.
65
66 Args:
Xiaochu Liudeed0232018-06-26 10:25:34 -070067 src_dir: (str) path to the DLC source root directory.
Amin Hassani2af75a92019-01-22 21:07:45 -080068 install_root_dir: (str) The path to the root installation directory.
Xiaochu Liudeed0232018-06-26 10:25:34 -070069 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 Hassani2af75a92019-01-22 21:07:45 -080076 self.install_root_dir = install_root_dir
Xiaochu Liudeed0232018-06-26 10:25:34 -070077 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 Hassani2af75a92019-01-22 21:07:45 -080082
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 Liudeed0232018-06-26 10:25:34 -070090 # Create path for all final artifacts.
Amin Hassani2af75a92019-01-22 21:07:45 -080091 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 Liudeed0232018-06-26 10:25:34 -070094
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 Hassanicc7ffce2019-01-11 14:57:52 -0800121
122 dlc_root_dir = os.path.join(mount_point, self._DLC_ROOT_DIR)
123 osutils.SafeMakedirs(dlc_root_dir)
Xiaochu Liudeed0232018-06-26 10:25:34 -0700124 try:
125 # Copy DLC files over to the image.
Colin Howes839c0042018-12-03 14:50:43 -0800126 osutils.CopyDirContents(self.src_dir, dlc_root_dir)
Amin Hassanid5742d32019-01-22 21:13:34 -0800127 self.PrepareLsbRelease(mount_point)
Colin Howes839c0042018-12-03 14:50:43 -0800128
Xiaochu Liudeed0232018-06-26 10:25:34 -0700129 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 Hassani22a25eb2019-01-11 14:25:02 -0800142 squashfs_root = os.path.join(temp_dir, 'squashfs-root')
Amin Hassanicc7ffce2019-01-11 14:57:52 -0800143 dlc_root_dir = os.path.join(squashfs_root, self._DLC_ROOT_DIR)
144 osutils.SafeMakedirs(dlc_root_dir)
Colin Howes839c0042018-12-03 14:50:43 -0800145 osutils.CopyDirContents(self.src_dir, dlc_root_dir)
Amin Hassanid5742d32019-01-22 21:13:34 -0800146 self.PrepareLsbRelease(squashfs_root)
Amin Hassanicc7ffce2019-01-11 14:57:52 -0800147
Amin Hassani22a25eb2019-01-11 14:25:02 -0800148 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 Liudeed0232018-06-26 10:25:34 -0700157
Amin Hassanid5742d32019-01-22 21:13:34 -0800158 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 Liudeed0232018-06-26 10:25:34 -0700177 def CreateImage(self):
178 """Create the image and copy the DLC files to it."""
Amin Hassani22a25eb2019-01-11 14:25:02 -0800179 if self.fs_type == _EXT4_TYPE:
Xiaochu Liudeed0232018-06-26 10:25:34 -0700180 self.CreateExt4Image()
Amin Hassani22a25eb2019-01-11 14:25:02 -0800181 elif self.fs_type == _SQUASHFS_TYPE:
Xiaochu Liudeed0232018-06-26 10:25:34 -0700182 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
249def 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 Hassani2af75a92019-01-22 21:07:45 -0800257 required.add_argument('--install-root-dir', type='path', metavar='DIR',
Xiaochu Liudeed0232018-06-26 10:25:34 -0700258 required=True,
Amin Hassani2af75a92019-01-22 21:07:45 -0800259 help='The root path to install DLC images (in %s) and '
260 'metadata (in %s).' % (DLC_IMAGE_DIR, DLC_META_DIR))
Xiaochu Liudeed0232018-06-26 10:25:34 -0700261 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 Hassani22a25eb2019-01-11 14:25:02 -0800271
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 Liudeed0232018-06-26 10:25:34 -0700277 return parser
278
279
280def main(argv):
281 opts = GetParser().parse_args(argv)
282 opts.Freeze()
283
Amin Hassani2af75a92019-01-22 21:07:45 -0800284 if opts.fs_type == _EXT4_TYPE:
285 raise Exception('ext4 unsupported, see https://crbug.com/890060')
286
Xiaochu Liudeed0232018-06-26 10:25:34 -0700287 # Generate final DLC files.
Amin Hassani2af75a92019-01-22 21:07:45 -0800288 dlc_generator = DlcGenerator(opts.src_dir, opts.install_root_dir,
Colin Howesfc607682018-09-28 16:46:32 -0700289 opts.fs_type, opts.pre_allocated_blocks,
290 opts.version, opts.id, opts.name)
Xiaochu Liudeed0232018-06-26 10:25:34 -0700291 dlc_generator.GenerateDLC()