blob: 8defd473265b33290f59c97944124c16a0b9ab4b [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
20def HashFile(file_path):
21 """Calculate the sha256 hash of a file.
22
23 Args:
24 file_path: (str) path to the file.
25
26 Returns:
27 [str]: The sha256 hash of the file.
28 """
29 sha256 = hashlib.sha256()
30 with open(file_path, 'rb') as f:
31 for b in iter(lambda: f.read(2048), b''):
32 sha256.update(b)
33 return sha256.hexdigest()
34
35
36class DLCGenerator(object):
37 """Object to generate DLC artifacts."""
38 # Block size for the DLC image.
39 # We use 4K for various reasons:
40 # 1. it's what imageloader (linux kernel) supports.
41 # 2. it's what verity supports.
42 _BLOCK_SIZE = 4096
43 # Blocks in the initial sparse image.
44 _BLOCKS = 500000
45 # Version of manifest file.
46 _MANIFEST_VERSION = 1
47
Colin Howesfc607682018-09-28 16:46:32 -070048 def __init__(self, img_dir, meta_dir, src_dir, fs_type, pre_allocated_blocks,
49 version, dlc_id, name):
Xiaochu Liudeed0232018-06-26 10:25:34 -070050 """Object initializer.
51
52 Args:
Colin Howesfc607682018-09-28 16:46:32 -070053 img_dir: (str) path to the DLC image dest root directory.
54 meta_dir: (str) path to the DLC metadata dest root directory.
Xiaochu Liudeed0232018-06-26 10:25:34 -070055 src_dir: (str) path to the DLC source root directory.
56 fs_type: (str) file system type.
57 pre_allocated_blocks: (int) number of blocks pre-allocated on device.
58 version: (str) DLC version.
59 dlc_id: (str) DLC ID.
60 name: (str) DLC name.
61 """
62 self.src_dir = src_dir
63 self.fs_type = fs_type
64 self.pre_allocated_blocks = pre_allocated_blocks
65 self.version = version
66 self.dlc_id = dlc_id
67 self.name = name
68 # Create path for all final artifacts.
Colin Howesfc607682018-09-28 16:46:32 -070069 self.dest_image = os.path.join(img_dir, 'dlc.img')
70 self.dest_table = os.path.join(meta_dir, 'table')
71 self.dest_imageloader_json = os.path.join(meta_dir, 'imageloader.json')
Xiaochu Liudeed0232018-06-26 10:25:34 -070072
73 def SquashOwnerships(self, path):
74 """Squash the owernships & permissions for files.
75
76 Args:
77 path: (str) path that contains all files to be processed.
78 """
79 cros_build_lib.SudoRunCommand(['chown', '-R', '0:0', path])
80 cros_build_lib.SudoRunCommand(
81 ['find', path, '-exec', 'touch', '-h', '-t', '197001010000.00', '{}',
82 '+'])
83
84 def CreateExt4Image(self):
85 """Create an ext4 image."""
86 with osutils.TempDir(prefix='dlc_') as temp_dir:
87 mount_point = os.path.join(temp_dir, 'mount_point')
88 # Create a raw image file.
89 with open(self.dest_image, 'w') as f:
90 f.truncate(self._BLOCKS * self._BLOCK_SIZE)
91 # Create an ext4 file system on the raw image.
92 cros_build_lib.RunCommand(
93 ['/sbin/mkfs.ext4', '-b', str(self._BLOCK_SIZE), '-O',
94 '^has_journal', self.dest_image], capture_output=True)
95 # Create the mount_point directory.
96 osutils.SafeMakedirs(mount_point)
97 # Mount the ext4 image.
98 osutils.MountDir(self.dest_image, mount_point, mount_opts=('loop', 'rw'))
99 try:
100 # Copy DLC files over to the image.
101 cros_build_lib.SudoRunCommand(['cp', '-a', self.src_dir, mount_point])
102 self.SquashOwnerships(mount_point)
103 finally:
104 # Unmount the ext4 image.
105 osutils.UmountDir(mount_point)
106 # Shrink to minimum size.
107 cros_build_lib.RunCommand(
108 ['/sbin/e2fsck', '-y', '-f', self.dest_image], capture_output=True)
109 cros_build_lib.RunCommand(
110 ['/sbin/resize2fs', '-M', self.dest_image], capture_output=True)
111
112 def CreateSquashfsImage(self):
113 """Create a squashfs image."""
114 with osutils.TempDir(prefix='dlc_') as temp_dir:
115 cros_build_lib.SudoRunCommand(['cp', '-a', self.src_dir, temp_dir])
116 self.SquashOwnerships(temp_dir)
117 cros_build_lib.SudoRunCommand(
118 ['mksquashfs', temp_dir, self.dest_image, '-4k-align', '-noappend'],
119 capture_output=True)
120
121 def CreateImage(self):
122 """Create the image and copy the DLC files to it."""
123 if self.fs_type == 'ext4':
124 self.CreateExt4Image()
125 elif self.fs_type == 'squashfs':
126 self.CreateSquashfsImage()
127 else:
128 raise ValueError('Wrong fs type: %s used:' % self.fs_type)
129
130 def GetImageloaderJsonContent(self, image_hash, table_hash, blocks):
131 """Return the content of imageloader.json file.
132
133 Args:
134 image_hash: (str) sha256 hash of the DLC image.
135 table_hash: (str) sha256 hash of the DLC table file.
136 blocks: (int) number of blocks in the DLC image.
137
138 Returns:
139 [str]: content of imageloader.json file.
140 """
141 return {
142 'fs-type': self.fs_type,
143 'id': self.dlc_id,
144 'image-sha256-hash': image_hash,
145 'image-type': 'dlc',
146 'is-removable': True,
147 'manifest-version': self._MANIFEST_VERSION,
148 'name': self.name,
149 'pre-allocated-size': self.pre_allocated_blocks * self._BLOCK_SIZE,
150 'size': blocks * self._BLOCK_SIZE,
151 'table-sha256-hash': table_hash,
152 'version': self.version,
153 }
154
155 def GenerateVerity(self):
156 """Generate verity parameters and hashes for the image."""
157 with osutils.TempDir(prefix='dlc_') as temp_dir:
158 hash_tree = os.path.join(temp_dir, 'hash_tree')
159 # Get blocks in the image.
160 blocks = math.ceil(
161 os.path.getsize(self.dest_image) / self._BLOCK_SIZE)
162 result = cros_build_lib.RunCommand(
163 ['verity', 'mode=create', 'alg=sha256', 'payload=' + self.dest_image,
164 'payload_blocks=' + str(blocks), 'hashtree=' + hash_tree,
165 'salt=random'], capture_output=True)
166 table = result.output
167
168 # Append the merkle tree to the image.
169 osutils.WriteFile(self.dest_image, osutils.ReadFile(hash_tree), 'a+')
170
171 # Write verity parameter to table file.
172 osutils.WriteFile(self.dest_table, table)
173
174 # Compute image hash.
175 image_hash = HashFile(self.dest_image)
176 table_hash = HashFile(self.dest_table)
177 # Write image hash to imageloader.json file.
178 blocks = math.ceil(
179 os.path.getsize(self.dest_image) / self._BLOCK_SIZE)
180 imageloader_json_content = self.GetImageloaderJsonContent(
181 image_hash, table_hash, int(blocks))
182 with open(self.dest_imageloader_json, 'w') as f:
183 json.dump(imageloader_json_content, f)
184
185 def GenerateDLC(self):
186 """Generate a DLC artifact."""
187 # Create the image and copy the DLC files to it.
188 self.CreateImage()
189 # Generate hash tree and other metadata.
190 self.GenerateVerity()
191
192
193def GetParser():
194 parser = commandline.ArgumentParser(description=__doc__)
195 # Required arguments:
196 required = parser.add_argument_group('Required Arguments')
197 required.add_argument('--src-dir', type='path', metavar='SRC_DIR_PATH',
198 required=True,
199 help='Root directory path that contains all DLC files '
200 'to be packed.')
Colin Howesfc607682018-09-28 16:46:32 -0700201 required.add_argument('--img-dir', type='path', metavar='IMG_DIR_PATH',
Xiaochu Liudeed0232018-06-26 10:25:34 -0700202 required=True,
Colin Howesfc607682018-09-28 16:46:32 -0700203 help='Root directory path that contains DLC image file '
204 'output.')
205 required.add_argument('--meta-dir', type='path', metavar='META_DIR_PATH',
206 required=True,
207 help='Root directory path that contains DLC metadata '
208 'output.')
Xiaochu Liudeed0232018-06-26 10:25:34 -0700209 required.add_argument('--fs-type', metavar='FS_TYPE', required=True,
210 choices=['squashfs', 'ext4'],
211 help='File system type of the image.')
212 required.add_argument('--pre-allocated-blocks', type=int,
213 metavar='PREALLOCATEDBLOCKS', required=True,
214 help='Number of blocks (block size is 4k) that need to'
215 'be pre-allocated on device.')
216 required.add_argument('--version', metavar='VERSION', required=True,
217 help='DLC Version.')
218 required.add_argument('--id', metavar='ID', required=True,
219 help='DLC ID (unique per DLC).')
220 required.add_argument('--name', metavar='NAME', required=True,
221 help='A human-readable name for the DLC.')
222 return parser
223
224
225def main(argv):
226 opts = GetParser().parse_args(argv)
227 opts.Freeze()
228
229 # Generate final DLC files.
Colin Howesfc607682018-09-28 16:46:32 -0700230 dlc_generator = DLCGenerator(opts.img_dir, opts.meta_dir, opts.src_dir,
231 opts.fs_type, opts.pre_allocated_blocks,
232 opts.version, opts.id, opts.name)
Xiaochu Liudeed0232018-06-26 10:25:34 -0700233 dlc_generator.GenerateDLC()