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