blob: 3b2fcda6e13a950587ab356b51f22d22aa3e879e [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
Colin Howesfc607682018-09-28 16:46:32 -070051 def __init__(self, img_dir, meta_dir, src_dir, fs_type, pre_allocated_blocks,
52 version, dlc_id, name):
Xiaochu Liudeed0232018-06-26 10:25:34 -070053 """Object initializer.
54
55 Args:
Colin Howesfc607682018-09-28 16:46:32 -070056 img_dir: (str) path to the DLC image dest root directory.
57 meta_dir: (str) path to the DLC metadata dest root directory.
Xiaochu Liudeed0232018-06-26 10:25:34 -070058 src_dir: (str) path to the DLC source root directory.
59 fs_type: (str) file system type.
60 pre_allocated_blocks: (int) number of blocks pre-allocated on device.
61 version: (str) DLC version.
62 dlc_id: (str) DLC ID.
63 name: (str) DLC name.
64 """
65 self.src_dir = src_dir
66 self.fs_type = fs_type
67 self.pre_allocated_blocks = pre_allocated_blocks
68 self.version = version
69 self.dlc_id = dlc_id
70 self.name = name
71 # Create path for all final artifacts.
Colin Howesfc607682018-09-28 16:46:32 -070072 self.dest_image = os.path.join(img_dir, 'dlc.img')
73 self.dest_table = os.path.join(meta_dir, 'table')
74 self.dest_imageloader_json = os.path.join(meta_dir, 'imageloader.json')
Xiaochu Liudeed0232018-06-26 10:25:34 -070075
76 def SquashOwnerships(self, path):
77 """Squash the owernships & permissions for files.
78
79 Args:
80 path: (str) path that contains all files to be processed.
81 """
82 cros_build_lib.SudoRunCommand(['chown', '-R', '0:0', path])
83 cros_build_lib.SudoRunCommand(
84 ['find', path, '-exec', 'touch', '-h', '-t', '197001010000.00', '{}',
85 '+'])
86
87 def CreateExt4Image(self):
88 """Create an ext4 image."""
89 with osutils.TempDir(prefix='dlc_') as temp_dir:
90 mount_point = os.path.join(temp_dir, 'mount_point')
91 # Create a raw image file.
92 with open(self.dest_image, 'w') as f:
93 f.truncate(self._BLOCKS * self._BLOCK_SIZE)
94 # Create an ext4 file system on the raw image.
95 cros_build_lib.RunCommand(
96 ['/sbin/mkfs.ext4', '-b', str(self._BLOCK_SIZE), '-O',
97 '^has_journal', self.dest_image], capture_output=True)
98 # Create the mount_point directory.
99 osutils.SafeMakedirs(mount_point)
100 # Mount the ext4 image.
101 osutils.MountDir(self.dest_image, mount_point, mount_opts=('loop', 'rw'))
102 try:
103 # Copy DLC files over to the image.
104 cros_build_lib.SudoRunCommand(['cp', '-a', self.src_dir, mount_point])
105 self.SquashOwnerships(mount_point)
106 finally:
107 # Unmount the ext4 image.
108 osutils.UmountDir(mount_point)
109 # Shrink to minimum size.
110 cros_build_lib.RunCommand(
111 ['/sbin/e2fsck', '-y', '-f', self.dest_image], capture_output=True)
112 cros_build_lib.RunCommand(
113 ['/sbin/resize2fs', '-M', self.dest_image], capture_output=True)
114
115 def CreateSquashfsImage(self):
116 """Create a squashfs image."""
117 with osutils.TempDir(prefix='dlc_') as temp_dir:
Amin Hassani22a25eb2019-01-11 14:25:02 -0800118 squashfs_root = os.path.join(temp_dir, 'squashfs-root')
119 osutils.SafeMakedirs(squashfs_root)
120 cros_build_lib.SudoRunCommand(['cp', '-a', self.src_dir, squashfs_root])
121 self.SquashOwnerships(squashfs_root)
122
123 cros_build_lib.RunCommand(['mksquashfs', squashfs_root, self.dest_image,
124 '-4k-align', '-noappend'],
125 capture_output=True)
126
127 # We changed the ownership and permissions of the squashfs_root
128 # directory. Now we need to remove it manually.
129 osutils.RmDir(squashfs_root, sudo=True)
Xiaochu Liudeed0232018-06-26 10:25:34 -0700130
131 def CreateImage(self):
132 """Create the image and copy the DLC files to it."""
Amin Hassani22a25eb2019-01-11 14:25:02 -0800133 if self.fs_type == _EXT4_TYPE:
Xiaochu Liudeed0232018-06-26 10:25:34 -0700134 self.CreateExt4Image()
Amin Hassani22a25eb2019-01-11 14:25:02 -0800135 elif self.fs_type == _SQUASHFS_TYPE:
Xiaochu Liudeed0232018-06-26 10:25:34 -0700136 self.CreateSquashfsImage()
137 else:
138 raise ValueError('Wrong fs type: %s used:' % self.fs_type)
139
140 def GetImageloaderJsonContent(self, image_hash, table_hash, blocks):
141 """Return the content of imageloader.json file.
142
143 Args:
144 image_hash: (str) sha256 hash of the DLC image.
145 table_hash: (str) sha256 hash of the DLC table file.
146 blocks: (int) number of blocks in the DLC image.
147
148 Returns:
149 [str]: content of imageloader.json file.
150 """
151 return {
152 'fs-type': self.fs_type,
153 'id': self.dlc_id,
154 'image-sha256-hash': image_hash,
155 'image-type': 'dlc',
156 'is-removable': True,
157 'manifest-version': self._MANIFEST_VERSION,
158 'name': self.name,
159 'pre-allocated-size': self.pre_allocated_blocks * self._BLOCK_SIZE,
160 'size': blocks * self._BLOCK_SIZE,
161 'table-sha256-hash': table_hash,
162 'version': self.version,
163 }
164
165 def GenerateVerity(self):
166 """Generate verity parameters and hashes for the image."""
167 with osutils.TempDir(prefix='dlc_') as temp_dir:
168 hash_tree = os.path.join(temp_dir, 'hash_tree')
169 # Get blocks in the image.
170 blocks = math.ceil(
171 os.path.getsize(self.dest_image) / self._BLOCK_SIZE)
172 result = cros_build_lib.RunCommand(
173 ['verity', 'mode=create', 'alg=sha256', 'payload=' + self.dest_image,
174 'payload_blocks=' + str(blocks), 'hashtree=' + hash_tree,
175 'salt=random'], capture_output=True)
176 table = result.output
177
178 # Append the merkle tree to the image.
179 osutils.WriteFile(self.dest_image, osutils.ReadFile(hash_tree), 'a+')
180
181 # Write verity parameter to table file.
182 osutils.WriteFile(self.dest_table, table)
183
184 # Compute image hash.
185 image_hash = HashFile(self.dest_image)
186 table_hash = HashFile(self.dest_table)
187 # Write image hash to imageloader.json file.
188 blocks = math.ceil(
189 os.path.getsize(self.dest_image) / self._BLOCK_SIZE)
190 imageloader_json_content = self.GetImageloaderJsonContent(
191 image_hash, table_hash, int(blocks))
192 with open(self.dest_imageloader_json, 'w') as f:
193 json.dump(imageloader_json_content, f)
194
195 def GenerateDLC(self):
196 """Generate a DLC artifact."""
197 # Create the image and copy the DLC files to it.
198 self.CreateImage()
199 # Generate hash tree and other metadata.
200 self.GenerateVerity()
201
202
203def GetParser():
204 parser = commandline.ArgumentParser(description=__doc__)
205 # Required arguments:
206 required = parser.add_argument_group('Required Arguments')
207 required.add_argument('--src-dir', type='path', metavar='SRC_DIR_PATH',
208 required=True,
209 help='Root directory path that contains all DLC files '
210 'to be packed.')
Colin Howesfc607682018-09-28 16:46:32 -0700211 required.add_argument('--img-dir', type='path', metavar='IMG_DIR_PATH',
Xiaochu Liudeed0232018-06-26 10:25:34 -0700212 required=True,
Colin Howesfc607682018-09-28 16:46:32 -0700213 help='Root directory path that contains DLC image file '
214 'output.')
215 required.add_argument('--meta-dir', type='path', metavar='META_DIR_PATH',
216 required=True,
217 help='Root directory path that contains DLC metadata '
218 'output.')
Xiaochu Liudeed0232018-06-26 10:25:34 -0700219 required.add_argument('--pre-allocated-blocks', type=int,
220 metavar='PREALLOCATEDBLOCKS', required=True,
221 help='Number of blocks (block size is 4k) that need to'
222 'be pre-allocated on device.')
223 required.add_argument('--version', metavar='VERSION', required=True,
224 help='DLC Version.')
225 required.add_argument('--id', metavar='ID', required=True,
226 help='DLC ID (unique per DLC).')
227 required.add_argument('--name', metavar='NAME', required=True,
228 help='A human-readable name for the DLC.')
Amin Hassani22a25eb2019-01-11 14:25:02 -0800229
230 args = parser.add_argument_group('Arguments')
231 args.add_argument('--fs-type', metavar='FS_TYPE', default=_SQUASHFS_TYPE,
232 choices=(_SQUASHFS_TYPE, _EXT4_TYPE),
233 help='File system type of the image.')
234
Xiaochu Liudeed0232018-06-26 10:25:34 -0700235 return parser
236
237
238def main(argv):
239 opts = GetParser().parse_args(argv)
240 opts.Freeze()
241
242 # Generate final DLC files.
Colin Howesfc607682018-09-28 16:46:32 -0700243 dlc_generator = DLCGenerator(opts.img_dir, opts.meta_dir, opts.src_dir,
244 opts.fs_type, opts.pre_allocated_blocks,
245 opts.version, opts.id, opts.name)
Xiaochu Liudeed0232018-06-26 10:25:34 -0700246 dlc_generator.GenerateDLC()