blob: 460aa46989e90bb08ad699e8eea6837d8d5bf50f [file] [log] [blame]
Kees Cookf4aa1b12012-02-15 16:09:10 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Thieu Le5c7d9752010-12-15 16:09:28 -08002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <algorithm>
6#include <string>
7#include <vector>
8
Alex Vakulenko75039d72014-03-25 12:36:28 -07009#include <base/strings/string_util.h>
10#include <base/strings/stringprintf.h>
Thieu Le5c7d9752010-12-15 16:09:28 -080011#include <et/com_err.h>
12#include <ext2fs/ext2_io.h>
13#include <ext2fs/ext2fs.h>
14
15#include "update_engine/bzip.h"
Thieu Le5c7d9752010-12-15 16:09:28 -080016#include "update_engine/extent_ranges.h"
Alex Deymo161c4a12014-05-16 15:56:21 -070017#include "update_engine/payload_generator/delta_diff_generator.h"
Alex Deymo5d527802014-07-18 14:24:13 -070018#include "update_engine/payload_generator/ext2_utils.h"
Alex Deymo161c4a12014-05-16 15:56:21 -070019#include "update_engine/payload_generator/graph_utils.h"
20#include "update_engine/payload_generator/metadata.h"
Thieu Le5c7d9752010-12-15 16:09:28 -080021#include "update_engine/utils.h"
22
Alex Deymo161c4a12014-05-16 15:56:21 -070023using base::StringPrintf;
Thieu Le5c7d9752010-12-15 16:09:28 -080024using std::min;
25using std::string;
26using std::vector;
27
28namespace chromeos_update_engine {
29
30namespace {
31const size_t kBlockSize = 4096;
32
33typedef DeltaDiffGenerator::Block Block;
34
35// Read data from the specified extents.
36bool ReadExtentsData(const ext2_filsys fs,
37 const vector<Extent>& extents,
38 vector<char>* data) {
39 // Resize the data buffer to hold all data in the extents
40 size_t num_data_blocks = 0;
41 for (vector<Extent>::const_iterator it = extents.begin();
42 it != extents.end(); it++) {
43 num_data_blocks += it->num_blocks();
44 }
45
46 data->resize(num_data_blocks * kBlockSize);
47
48 // Read in the data blocks
49 const size_t kMaxReadBlocks = 256;
50 vector<Block>::size_type blocks_copied_count = 0;
51 for (vector<Extent>::const_iterator it = extents.begin();
52 it != extents.end(); it++) {
53 vector<Block>::size_type blocks_read = 0;
54 while (blocks_read < it->num_blocks()) {
55 const int copy_block_cnt =
56 min(kMaxReadBlocks,
57 static_cast<size_t>(
58 it->num_blocks() - blocks_read));
59 TEST_AND_RETURN_FALSE_ERRCODE(
60 io_channel_read_blk(fs->io,
61 it->start_block() + blocks_read,
62 copy_block_cnt,
63 &(*data)[blocks_copied_count * kBlockSize]));
64 blocks_read += copy_block_cnt;
65 blocks_copied_count += copy_block_cnt;
66 }
67 }
68
69 return true;
70}
71
72// Compute the bsdiff between two metadata blobs.
73bool ComputeMetadataBsdiff(const vector<char>& old_metadata,
74 const vector<char>& new_metadata,
75 vector<char>* bsdiff_delta) {
Gilad Arnolda6742b32014-01-11 00:18:34 -080076 const string kTempFileTemplate("CrAU_temp_data.XXXXXX");
Thieu Le5c7d9752010-12-15 16:09:28 -080077
78 // Write the metadata buffers to temporary files
79 int old_fd;
80 string temp_old_file_path;
81 TEST_AND_RETURN_FALSE(
82 utils::MakeTempFile(kTempFileTemplate, &temp_old_file_path, &old_fd));
83 TEST_AND_RETURN_FALSE(old_fd >= 0);
84 ScopedPathUnlinker temp_old_file_path_unlinker(temp_old_file_path);
85 ScopedFdCloser old_fd_closer(&old_fd);
86 TEST_AND_RETURN_FALSE(utils::WriteAll(old_fd,
87 &old_metadata[0],
88 old_metadata.size()));
89
90 int new_fd;
91 string temp_new_file_path;
92 TEST_AND_RETURN_FALSE(
93 utils::MakeTempFile(kTempFileTemplate, &temp_new_file_path, &new_fd));
94 TEST_AND_RETURN_FALSE(new_fd >= 0);
95 ScopedPathUnlinker temp_new_file_path_unlinker(temp_new_file_path);
96 ScopedFdCloser new_fd_closer(&new_fd);
97 TEST_AND_RETURN_FALSE(utils::WriteAll(new_fd,
98 &new_metadata[0],
99 new_metadata.size()));
100
101 // Perform bsdiff on these files
102 TEST_AND_RETURN_FALSE(
103 DeltaDiffGenerator::BsdiffFiles(temp_old_file_path,
104 temp_new_file_path,
105 bsdiff_delta));
106
107 return true;
108}
109
110// Add the specified metadata extents to the graph and blocks vector.
111bool AddMetadataExtents(Graph* graph,
112 vector<Block>* blocks,
113 const ext2_filsys fs_old,
114 const ext2_filsys fs_new,
115 const string& metadata_name,
116 const vector<Extent>& extents,
117 int data_fd,
118 off_t* data_file_size) {
119 vector<char> data; // Data blob that will be written to delta file.
120 DeltaArchiveManifest_InstallOperation op;
121
122 {
123 // Read in the metadata blocks from the old and new image.
124 vector<char> old_data;
125 TEST_AND_RETURN_FALSE(ReadExtentsData(fs_old, extents, &old_data));
126
127 vector<char> new_data;
128 TEST_AND_RETURN_FALSE(ReadExtentsData(fs_new, extents, &new_data));
129
130 // Determine the best way to compress this.
131 vector<char> new_data_bz;
132 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
133 CHECK(!new_data_bz.empty());
134
135 size_t current_best_size = 0;
136 if (new_data.size() <= new_data_bz.size()) {
137 op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
138 current_best_size = new_data.size();
139 data = new_data;
140 } else {
141 op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
142 current_best_size = new_data_bz.size();
143 data = new_data_bz;
144 }
145
146 if (old_data == new_data) {
147 // No change in data.
148 op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
149 current_best_size = 0;
150 data.clear();
151 } else {
152 // Try bsdiff of old to new data
153 vector<char> bsdiff_delta;
154 TEST_AND_RETURN_FALSE(ComputeMetadataBsdiff(old_data,
155 new_data,
156 &bsdiff_delta));
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500157 CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
Thieu Le5c7d9752010-12-15 16:09:28 -0800158
159 if (bsdiff_delta.size() < current_best_size) {
160 op.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
161 current_best_size = bsdiff_delta.size();
162 data = bsdiff_delta;
163 }
164 }
165
166 CHECK_EQ(data.size(), current_best_size);
167
168 // Set the source and dest extents to be the same since the filesystem
169 // structures are identical
170 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
171 op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
172 DeltaDiffGenerator::StoreExtents(extents, op.mutable_src_extents());
173 op.set_src_length(old_data.size());
174 }
175
176 DeltaDiffGenerator::StoreExtents(extents, op.mutable_dst_extents());
177 op.set_dst_length(new_data.size());
178 }
179
180 // Write data to output file
181 if (op.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
182 op.set_data_offset(*data_file_size);
183 op.set_data_length(data.size());
184 }
185
186 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
187 *data_file_size += data.size();
188
189 // Now, insert into graph and blocks vector
190 graph->resize(graph->size() + 1);
191 Vertex::Index vertex = graph->size() - 1;
192 (*graph)[vertex].op = op;
193 CHECK((*graph)[vertex].op.has_type());
194 (*graph)[vertex].file_name = metadata_name;
195
196 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
197 (*graph)[vertex].op,
198 *graph,
199 vertex,
200 blocks));
201
202 return true;
203}
204
205// Reads the file system metadata extents.
206bool ReadFilesystemMetadata(Graph* graph,
207 vector<Block>* blocks,
208 const ext2_filsys fs_old,
209 const ext2_filsys fs_new,
210 int data_fd,
211 off_t* data_file_size) {
212 LOG(INFO) << "Processing <rootfs-metadata>";
213
214 // Read all the extents that belong to the main file system metadata.
215 // The metadata blocks are at the start of each block group and goes
216 // until the end of the inode table.
217 for (dgrp_t bg = 0; bg < fs_old->group_desc_count; bg++) {
Kees Cookf4aa1b12012-02-15 16:09:10 -0800218 struct ext2_group_desc* group_desc = ext2fs_group_desc(fs_old,
219 fs_old->group_desc,
220 bg);
Thieu Le5c7d9752010-12-15 16:09:28 -0800221 __u32 num_metadata_blocks = (group_desc->bg_inode_table +
222 fs_old->inode_blocks_per_group) -
223 (bg * fs_old->super->s_blocks_per_group);
224 __u32 bg_start_block = bg * fs_old->super->s_blocks_per_group;
225
226 // Due to bsdiff slowness, we're going to break each block group down
227 // into metadata chunks and feed them to bsdiff.
Thieu Lef6502192011-01-05 14:34:22 -0800228 __u32 num_chunks = 10;
Thieu Le5c7d9752010-12-15 16:09:28 -0800229 __u32 blocks_per_chunk = num_metadata_blocks / num_chunks;
230 __u32 curr_block = bg_start_block;
231 for (__u32 chunk = 0; chunk < num_chunks; chunk++) {
232 Extent extent;
233 if (chunk < num_chunks - 1) {
234 extent = ExtentForRange(curr_block, blocks_per_chunk);
235 } else {
236 extent = ExtentForRange(curr_block,
237 bg_start_block + num_metadata_blocks -
238 curr_block);
239 }
240
241 vector<Extent> extents;
242 extents.push_back(extent);
243
244 string metadata_name = StringPrintf("<rootfs-bg-%d-%d-metadata>",
245 bg, chunk);
246
247 LOG(INFO) << "Processing " << metadata_name;
248
249 TEST_AND_RETURN_FALSE(AddMetadataExtents(graph,
250 blocks,
251 fs_old,
252 fs_new,
253 metadata_name,
254 extents,
255 data_fd,
256 data_file_size));
257
258 curr_block += blocks_per_chunk;
259 }
260 }
261
262 return true;
263}
264
265// Processes all blocks belonging to an inode
266int ProcessInodeAllBlocks(ext2_filsys fs,
267 blk_t* blocknr,
268 e2_blkcnt_t blockcnt,
269 blk_t ref_blk,
270 int ref_offset,
271 void* priv) {
272 vector<Extent>* extents = static_cast<vector<Extent>*>(priv);
273 graph_utils::AppendBlockToExtents(extents, *blocknr);
274 return 0;
275}
276
277// Processes only indirect, double indirect or triple indirect metadata
278// blocks belonging to an inode
279int ProcessInodeMetadataBlocks(ext2_filsys fs,
280 blk_t* blocknr,
281 e2_blkcnt_t blockcnt,
282 blk_t ref_blk,
283 int ref_offset,
284 void* priv) {
285 vector<Extent>* extents = static_cast<vector<Extent>*>(priv);
286 if (blockcnt < 0) {
287 graph_utils::AppendBlockToExtents(extents, *blocknr);
288 }
289 return 0;
290}
291
292// Read inode metadata blocks.
293bool ReadInodeMetadata(Graph* graph,
294 vector<Block>* blocks,
295 const ext2_filsys fs_old,
296 const ext2_filsys fs_new,
297 int data_fd,
298 off_t* data_file_size) {
299 TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_read_inode_bitmap(fs_old));
300 TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_read_inode_bitmap(fs_new));
301
302 ext2_inode_scan iscan;
303 TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open_inode_scan(fs_old, 0, &iscan));
304
305 ext2_ino_t ino;
306 ext2_inode old_inode;
307 while (true) {
308 // Get the next inode on both file systems
309 errcode_t error = ext2fs_get_next_inode(iscan, &ino, &old_inode);
310
311 // If we get an error enumerating the inodes, we'll just log the error
312 // and exit from our loop which will eventually return a success code
313 // back to the caller. The inode blocks that we cannot account for will
314 // be handled by DeltaDiffGenerator::ReadUnwrittenBlocks().
315 if (error) {
316 LOG(ERROR) << "Failed to retrieve next inode (" << error << ")";
317 break;
318 }
319
320 if (ino == 0) {
321 break;
322 }
323
324 if (ino == EXT2_RESIZE_INO) {
325 continue;
326 }
327
328 ext2_inode new_inode;
329 error = ext2fs_read_inode(fs_new, ino, &new_inode);
330 if (error) {
331 LOG(ERROR) << "Failed to retrieve new inode (" << error << ")";
332 continue;
333 }
334
335 // Skip inodes that are not in use
336 if (!ext2fs_test_inode_bitmap(fs_old->inode_map, ino) ||
337 !ext2fs_test_inode_bitmap(fs_new->inode_map, ino)) {
338 continue;
339 }
340
341 // Skip inodes that have no data blocks
342 if (old_inode.i_blocks == 0 || new_inode.i_blocks == 0) {
343 continue;
344 }
345
346 // Skip inodes that are not the same type
347 bool is_old_dir = (ext2fs_check_directory(fs_old, ino) == 0);
348 bool is_new_dir = (ext2fs_check_directory(fs_new, ino) == 0);
349 if (is_old_dir != is_new_dir) {
350 continue;
351 }
352
353 // Process the inodes metadata blocks
354 // For normal files, metadata blocks are indirect, double indirect
355 // and triple indirect blocks (no data blocks). For directories and
356 // the journal, all blocks are considered metadata blocks.
357 LOG(INFO) << "Processing inode " << ino << " metadata";
358
359 bool all_blocks = ((ino == EXT2_JOURNAL_INO) || is_old_dir || is_new_dir);
360
361 vector<Extent> old_extents;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700362 error = ext2fs_block_iterate2(fs_old, ino, 0, nullptr,
Thieu Le5c7d9752010-12-15 16:09:28 -0800363 all_blocks ? ProcessInodeAllBlocks :
364 ProcessInodeMetadataBlocks,
365 &old_extents);
366 if (error) {
367 LOG(ERROR) << "Failed to enumerate old inode " << ino
368 << " blocks (" << error << ")";
369 continue;
370 }
371
372 vector<Extent> new_extents;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700373 error = ext2fs_block_iterate2(fs_new, ino, 0, nullptr,
Thieu Le5c7d9752010-12-15 16:09:28 -0800374 all_blocks ? ProcessInodeAllBlocks :
375 ProcessInodeMetadataBlocks,
376 &new_extents);
377 if (error) {
378 LOG(ERROR) << "Failed to enumerate new inode " << ino
379 << " blocks (" << error << ")";
380 continue;
381 }
382
383 // Skip inode if there are no metadata blocks
384 if (old_extents.size() == 0 || new_extents.size() == 0) {
385 continue;
386 }
387
388 // Make sure the two inodes have the same metadata blocks
389 if (old_extents.size() != new_extents.size()) {
390 continue;
391 }
392
393 bool same_metadata_extents = true;
394 vector<Extent>::iterator it_old;
395 vector<Extent>::iterator it_new;
396 for (it_old = old_extents.begin(),
397 it_new = new_extents.begin();
398 it_old != old_extents.end() && it_new != new_extents.end();
399 it_old++, it_new++) {
400 if (it_old->start_block() != it_new->start_block() ||
401 it_old->num_blocks() != it_new->num_blocks()) {
402 same_metadata_extents = false;
403 break;
404 }
405 }
406
407 if (!same_metadata_extents) {
408 continue;
409 }
410
411 // We have identical inode metadata blocks, we can now add them to
412 // our graph and blocks vector
413 string metadata_name = StringPrintf("<rootfs-inode-%d-metadata>", ino);
414 TEST_AND_RETURN_FALSE(AddMetadataExtents(graph,
415 blocks,
416 fs_old,
417 fs_new,
418 metadata_name,
419 old_extents,
420 data_fd,
421 data_file_size));
422 }
423
424 ext2fs_close_inode_scan(iscan);
425
426 return true;
427}
428
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700429} // namespace
Thieu Le5c7d9752010-12-15 16:09:28 -0800430
431// Reads metadata from old image and new image and determines
432// the smallest way to encode the metadata for the diff.
433// If there's no change in the metadata, it creates a MOVE
434// operation. If there is a change, the smallest of REPLACE, REPLACE_BZ,
435// or BSDIFF wins. It writes the diff to data_fd and updates data_file_size
436// accordingly. It also adds the required operation to the graph and adds the
437// metadata extents to blocks.
438// Returns true on success.
439bool Metadata::DeltaReadMetadata(Graph* graph,
440 vector<Block>* blocks,
441 const string& old_image,
442 const string& new_image,
443 int data_fd,
444 off_t* data_file_size) {
445 // Open the two file systems.
446 ext2_filsys fs_old;
447 TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open(old_image.c_str(), 0, 0, 0,
448 unix_io_manager, &fs_old));
449 ScopedExt2fsCloser fs_old_closer(fs_old);
450
451 ext2_filsys fs_new;
452 TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open(new_image.c_str(), 0, 0, 0,
453 unix_io_manager, &fs_new));
454 ScopedExt2fsCloser fs_new_closer(fs_new);
455
456 // Make sure these two file systems are the same.
457 // If they are not the same, the metadata blocks will be packaged up in its
458 // entirety by ReadUnwrittenBlocks().
459 if (fs_old->blocksize != fs_new->blocksize ||
460 fs_old->fragsize != fs_new->fragsize ||
461 fs_old->group_desc_count != fs_new->group_desc_count ||
462 fs_old->inode_blocks_per_group != fs_new->inode_blocks_per_group ||
463 fs_old->super->s_inodes_count != fs_new->super->s_inodes_count ||
464 fs_old->super->s_blocks_count != fs_new->super->s_blocks_count) {
465 return true;
466 }
467
468 // Process the main file system metadata (superblock, inode tables, etc)
469 TEST_AND_RETURN_FALSE(ReadFilesystemMetadata(graph,
470 blocks,
471 fs_old,
472 fs_new,
473 data_fd,
474 data_file_size));
475
476 // Process each inode metadata blocks.
477 TEST_AND_RETURN_FALSE(ReadInodeMetadata(graph,
478 blocks,
479 fs_old,
480 fs_new,
481 data_fd,
482 data_file_size));
483
484 return true;
485}
486
487}; // namespace chromeos_update_engine