blob: c1ed86fc901963e40571e133db65590329c4bfb4 [file] [log] [blame]
Don Garrettf4b28742012-03-27 20:48:06 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_diff_generator.h"
Darin Petkov880335c2010-10-01 15:52:53 -07006
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07007#include <errno.h>
8#include <fcntl.h>
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07009#include <inttypes.h>
Darin Petkov880335c2010-10-01 15:52:53 -070010#include <sys/stat.h>
11#include <sys/types.h>
12
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070013#include <algorithm>
Andrew de los Reyesef017552010-10-06 17:57:52 -070014#include <map>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070015#include <set>
16#include <string>
17#include <utility>
18#include <vector>
Darin Petkov880335c2010-10-01 15:52:53 -070019
20#include <base/logging.h>
Darin Petkov7438a5c2011-08-29 11:56:44 -070021#include <base/memory/scoped_ptr.h>
Darin Petkov880335c2010-10-01 15:52:53 -070022#include <base/string_util.h>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070023#include <bzlib.h>
Darin Petkov880335c2010-10-01 15:52:53 -070024
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070025#include "update_engine/bzip.h"
26#include "update_engine/cycle_breaker.h"
27#include "update_engine/extent_mapper.h"
Andrew de los Reyesef017552010-10-06 17:57:52 -070028#include "update_engine/extent_ranges.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070029#include "update_engine/file_writer.h"
30#include "update_engine/filesystem_iterator.h"
Darin Petkov7a22d792010-11-08 14:10:00 -080031#include "update_engine/full_update_generator.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070032#include "update_engine/graph_types.h"
33#include "update_engine/graph_utils.h"
Thieu Le5c7d9752010-12-15 16:09:28 -080034#include "update_engine/metadata.h"
Darin Petkov36a58222010-10-07 22:00:09 -070035#include "update_engine/omaha_hash_calculator.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070036#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070037#include "update_engine/subprocess.h"
38#include "update_engine/topological_sort.h"
39#include "update_engine/update_metadata.pb.h"
40#include "update_engine/utils.h"
41
42using std::make_pair;
Andrew de los Reyesef017552010-10-06 17:57:52 -070043using std::map;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070044using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070045using std::min;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -070046using std::pair;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070047using std::set;
48using std::string;
49using std::vector;
50
51namespace chromeos_update_engine {
52
53typedef DeltaDiffGenerator::Block Block;
Darin Petkov9fa7ec52010-10-18 11:45:23 -070054typedef map<const DeltaArchiveManifest_InstallOperation*,
55 const string*> OperationNameMap;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070056
57namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070058const size_t kBlockSize = 4096; // bytes
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -080059const string kNonexistentPath = "";
Andrew de los Reyes927179d2010-12-02 11:26:48 -080060
61// TODO(adlr): switch from 1GiB to 2GiB when we no longer care about old
62// clients:
Darin Petkov9eadd642010-10-14 15:20:57 -070063const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // bytes
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070064const uint64_t kVersionNumber = 1;
Darin Petkov9eadd642010-10-14 15:20:57 -070065const uint64_t kFullUpdateChunkSize = 1024 * 1024; // bytes
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070066
Darin Petkov68c10d12010-10-14 09:24:37 -070067static const char* kInstallOperationTypes[] = {
68 "REPLACE",
69 "REPLACE_BZ",
70 "MOVE",
71 "BSDIFF"
72};
73
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070074// Stores all Extents for a file into 'out'. Returns true on success.
75bool GatherExtents(const string& path,
76 google::protobuf::RepeatedPtrField<Extent>* out) {
77 vector<Extent> extents;
78 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
79 DeltaDiffGenerator::StoreExtents(extents, out);
80 return true;
81}
82
Andrew de los Reyesef017552010-10-06 17:57:52 -070083// For a given regular file which must exist at new_root + path, and
84// may exist at old_root + path, creates a new InstallOperation and
85// adds it to the graph. Also, populates the |blocks| array as
86// necessary, if |blocks| is non-NULL. Also, writes the data
87// necessary to send the file down to the client into data_fd, which
88// has length *data_file_size. *data_file_size is updated
89// appropriately. If |existing_vertex| is no kInvalidIndex, use that
90// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070091bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -070092 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070093 vector<Block>* blocks,
94 const string& old_root,
95 const string& new_root,
96 const string& path, // within new_root
97 int data_fd,
98 off_t* data_file_size) {
99 vector<char> data;
100 DeltaArchiveManifest_InstallOperation operation;
101
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800102 string old_path = (old_root == kNonexistentPath) ? kNonexistentPath :
103 old_root + path;
104
Don Garrettf4b28742012-03-27 20:48:06 -0700105 // TODO(dgarrett): chromium-os:15274 Wire up this file all of the way to
106 // command line.
Don Garrett36e60772012-03-29 10:31:20 -0700107 //
108 // To hardcode for now, use the following instead of true.
109 // (path != "/opt/google/chrome/pepper/libnetflixidd.so");
110 bool bsdiff_allowed = true;
Don Garrettf4b28742012-03-27 20:48:06 -0700111
Don Garrett36e60772012-03-29 10:31:20 -0700112 if (!bsdiff_allowed)
113 LOG(INFO) << "bsdiff blacklisting: " << path;
Don Garrettf4b28742012-03-27 20:48:06 -0700114
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800115 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700116 new_root + path,
Don Garrett36e60772012-03-29 10:31:20 -0700117 bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700118 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700119 &operation,
120 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700121
122 // Write the data
123 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
124 operation.set_data_offset(*data_file_size);
125 operation.set_data_length(data.size());
126 }
127
128 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
129 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700130
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700131 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700132 Vertex::Index vertex = existing_vertex;
133 if (vertex == Vertex::kInvalidIndex) {
134 graph->resize(graph->size() + 1);
135 vertex = graph->size() - 1;
136 }
137 (*graph)[vertex].op = operation;
138 CHECK((*graph)[vertex].op.has_type());
139 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700140
Andrew de los Reyesef017552010-10-06 17:57:52 -0700141 if (blocks)
Thieu Le5c7d9752010-12-15 16:09:28 -0800142 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
143 (*graph)[vertex].op,
144 *graph,
145 vertex,
146 blocks));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700147 return true;
148}
149
150// For each regular file within new_root, creates a node in the graph,
151// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
152// and writes any necessary data to the end of data_fd.
153bool DeltaReadFiles(Graph* graph,
154 vector<Block>* blocks,
155 const string& old_root,
156 const string& new_root,
157 int data_fd,
158 off_t* data_file_size) {
159 set<ino_t> visited_inodes;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800160 set<ino_t> visited_src_inodes;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700161 for (FilesystemIterator fs_iter(new_root,
162 utils::SetWithValue<string>("/lost+found"));
163 !fs_iter.IsEnd(); fs_iter.Increment()) {
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800164 // We never diff symlinks (here, we check that dst file is not a symlink).
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700165 if (!S_ISREG(fs_iter.GetStat().st_mode))
166 continue;
167
168 // Make sure we visit each inode only once.
169 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
170 continue;
171 visited_inodes.insert(fs_iter.GetStat().st_ino);
172 if (fs_iter.GetStat().st_size == 0)
173 continue;
174
175 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700176
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800177 // We can't visit each dst image inode more than once, as that would
178 // duplicate work. Here, we avoid visiting each source image inode
179 // more than once. Technically, we could have multiple operations
180 // that read the same blocks from the source image for diffing, but
181 // we choose not to to avoid complexity. Eventually we will move away
182 // from using a graph/cycle detection/etc to generate diffs, and at that
183 // time, it will be easy (non-complex) to have many operations read
184 // from the same source blocks. At that time, this code can die. -adlr
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800185 bool should_diff_from_source = false;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800186 string src_path = old_root + fs_iter.GetPartialPath();
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800187 struct stat src_stbuf;
188 // We never diff symlinks (here, we check that src file is not a symlink).
189 if (0 == lstat(src_path.c_str(), &src_stbuf) &&
190 S_ISREG(src_stbuf.st_mode)) {
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800191 should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
192 src_stbuf.st_ino);
193 visited_src_inodes.insert(src_stbuf.st_ino);
194 }
195
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700196 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700197 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700198 blocks,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800199 (should_diff_from_source ?
200 old_root :
201 kNonexistentPath),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700202 new_root,
203 fs_iter.GetPartialPath(),
204 data_fd,
205 data_file_size));
206 }
207 return true;
208}
209
Andrew de los Reyesef017552010-10-06 17:57:52 -0700210// This class allocates non-existent temp blocks, starting from
211// kTempBlockStart. Other code is responsible for converting these
212// temp blocks into real blocks, as the client can't read or write to
213// these blocks.
214class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700215 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700216 explicit DummyExtentAllocator()
217 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700218 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700219 vector<Extent> ret(1);
220 ret[0].set_start_block(next_block_);
221 ret[0].set_num_blocks(block_count);
222 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700223 return ret;
224 }
225 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700226 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700227};
228
229// Reads blocks from image_path that are not yet marked as being written
230// in the blocks array. These blocks that remain are non-file-data blocks.
231// In the future we might consider intelligent diffing between this data
232// and data in the previous image, but for now we just bzip2 compress it
233// and include it in the update.
234// Creates a new node in the graph to write these blocks and writes the
235// appropriate blob to blobs_fd. Reads and updates blobs_length;
236bool ReadUnwrittenBlocks(const vector<Block>& blocks,
237 int blobs_fd,
238 off_t* blobs_length,
239 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700240 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700241 vertex->file_name = "<rootfs-non-file-data>";
242
Andrew de los Reyesef017552010-10-06 17:57:52 -0700243 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700244 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
245 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
246 ScopedFdCloser image_fd_closer(&image_fd);
247
248 string temp_file_path;
249 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
250 &temp_file_path,
251 NULL));
252
253 FILE* file = fopen(temp_file_path.c_str(), "w");
254 TEST_AND_RETURN_FALSE(file);
255 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700256
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700257 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
258 file,
259 9, // max compression
260 0, // verbosity
261 0); // default work factor
262 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700263
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700264 vector<Extent> extents;
265 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700266
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700267 LOG(INFO) << "Appending left over blocks to extents";
268 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
269 if (blocks[i].writer != Vertex::kInvalidIndex)
270 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700271 if (blocks[i].reader != Vertex::kInvalidIndex) {
272 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
273 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700274 graph_utils::AppendBlockToExtents(&extents, i);
275 block_count++;
276 }
277
278 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
279 // so we arbitrarily set it to 1024 * kBlockSize.
280 vector<char> buf(1024 * kBlockSize);
281
282 LOG(INFO) << "Reading left over blocks";
283 vector<Block>::size_type blocks_copied_count = 0;
284
285 // For each extent in extents, write the data into BZ2_bzWrite which
286 // sends it to an output file.
287 // We use the temporary buffer 'buf' to hold the data, which may be
288 // smaller than the extent, so in that case we have to loop to get
289 // the extent's data (that's the inner while loop).
290 for (vector<Extent>::const_iterator it = extents.begin();
291 it != extents.end(); ++it) {
292 vector<Block>::size_type blocks_read = 0;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800293 float printed_progress = -1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700294 while (blocks_read < it->num_blocks()) {
295 const int copy_block_cnt =
296 min(buf.size() / kBlockSize,
297 static_cast<vector<char>::size_type>(
298 it->num_blocks() - blocks_read));
299 ssize_t rc = pread(image_fd,
300 &buf[0],
301 copy_block_cnt * kBlockSize,
302 (it->start_block() + blocks_read) * kBlockSize);
303 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
304 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
305 copy_block_cnt * kBlockSize);
306 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
307 TEST_AND_RETURN_FALSE(err == BZ_OK);
308 blocks_read += copy_block_cnt;
309 blocks_copied_count += copy_block_cnt;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800310 float current_progress =
311 static_cast<float>(blocks_copied_count) / block_count;
312 if (printed_progress + 0.1 < current_progress ||
313 blocks_copied_count == block_count) {
314 LOG(INFO) << "progress: " << current_progress;
315 printed_progress = current_progress;
316 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700317 }
318 }
319 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
320 TEST_AND_RETURN_FALSE(err == BZ_OK);
321 bz_file = NULL;
322 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
323 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700324
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700325 vector<char> compressed_data;
326 LOG(INFO) << "Reading compressed data off disk";
327 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
328 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700329
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700330 // Add node to graph to write these blocks
331 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
332 out_op->set_data_offset(*blobs_length);
333 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700334 LOG(INFO) << "Rootfs non-data blocks compressed take up "
335 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700336 *blobs_length += compressed_data.size();
337 out_op->set_dst_length(kBlockSize * block_count);
338 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700339
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700340 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
341 &compressed_data[0],
342 compressed_data.size()));
343 LOG(INFO) << "done with extra blocks";
344 return true;
345}
346
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700347// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700348// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700349bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
350 uint64_t value_be = htobe64(value);
Don Garrette410e0f2011-11-10 15:39:01 -0800351 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700352 return true;
353}
354
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700355// Adds each operation from |graph| to |out_manifest| in the order specified by
356// |order| while building |out_op_name_map| with operation to name
357// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
358// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700359void InstallOperationsToManifest(
360 const Graph& graph,
361 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700362 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700363 DeltaArchiveManifest* out_manifest,
364 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365 for (vector<Vertex::Index>::const_iterator it = order.begin();
366 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700367 const Vertex& vertex = graph[*it];
368 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
369 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
370 continue;
371 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700372 DeltaArchiveManifest_InstallOperation* op =
373 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700374 *op = add_op;
375 (*out_op_name_map)[op] = &vertex.file_name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700376 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700377 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
378 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700379 const DeltaArchiveManifest_InstallOperation& add_op = *it;
380 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
381 continue;
382 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700383 DeltaArchiveManifest_InstallOperation* op =
384 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700385 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700386 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700387}
388
389void CheckGraph(const Graph& graph) {
390 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
391 CHECK(it->op.has_type());
392 }
393}
394
Darin Petkov68c10d12010-10-14 09:24:37 -0700395// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
396// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
397// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398bool DeltaCompressKernelPartition(
399 const string& old_kernel_part,
400 const string& new_kernel_part,
401 vector<DeltaArchiveManifest_InstallOperation>* ops,
402 int blobs_fd,
403 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700404 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700405 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700406
407 // Add a new install operation
408 ops->resize(1);
409 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700410
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700411 vector<char> data;
Don Garrett36e60772012-03-29 10:31:20 -0700412 TEST_AND_RETURN_FALSE(
413 DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
414 new_kernel_part,
415 true, // bsdiff_allowed
416 &data,
417 op,
418 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700419
Darin Petkov68c10d12010-10-14 09:24:37 -0700420 // Write the data
421 if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
422 op->set_data_offset(*blobs_length);
423 op->set_data_length(data.size());
424 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700425
Darin Petkov68c10d12010-10-14 09:24:37 -0700426 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
427 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700428
Darin Petkov68c10d12010-10-14 09:24:37 -0700429 LOG(INFO) << "Done delta compressing kernel partition: "
430 << kInstallOperationTypes[op->type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700431 return true;
432}
433
Darin Petkov880335c2010-10-01 15:52:53 -0700434struct DeltaObject {
435 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
436 : name(in_name),
437 type(in_type),
438 size(in_size) {}
439 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700440 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700441 }
442 string name;
443 int type;
444 off_t size;
445};
446
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700447void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
448 const int64_t manifest_metadata_size,
449 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700450 vector<DeltaObject> objects;
451 off_t total_size = 0;
452
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700453 // Rootfs install operations.
454 for (int i = 0; i < manifest.install_operations_size(); ++i) {
455 const DeltaArchiveManifest_InstallOperation& op =
456 manifest.install_operations(i);
457 objects.push_back(DeltaObject(*op_name_map.find(&op)->second,
458 op.type(),
459 op.data_length()));
460 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700461 }
462
Darin Petkov880335c2010-10-01 15:52:53 -0700463 // Kernel install operations.
464 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
465 const DeltaArchiveManifest_InstallOperation& op =
466 manifest.kernel_install_operations(i);
467 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
468 op.type(),
469 op.data_length()));
470 total_size += op.data_length();
471 }
472
Darin Petkov95cf01f2010-10-12 14:59:13 -0700473 objects.push_back(DeltaObject("<manifest-metadata>",
474 -1,
475 manifest_metadata_size));
476 total_size += manifest_metadata_size;
477
Darin Petkov880335c2010-10-01 15:52:53 -0700478 std::sort(objects.begin(), objects.end());
479
480 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
481 for (vector<DeltaObject>::const_iterator it = objects.begin();
482 it != objects.end(); ++it) {
483 const DeltaObject& object = *it;
484 fprintf(stderr, kFormatString,
485 object.size * 100.0 / total_size,
486 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700487 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700488 object.name.c_str());
489 }
490 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
491}
492
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700493} // namespace {}
494
495bool DeltaDiffGenerator::ReadFileToDiff(
496 const string& old_filename,
497 const string& new_filename,
Don Garrett36e60772012-03-29 10:31:20 -0700498 bool bsdiff_allowed,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700499 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700500 DeltaArchiveManifest_InstallOperation* out_op,
501 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700502 // Read new data in
503 vector<char> new_data;
504 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700505
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700506 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700507
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700508 vector<char> new_data_bz;
509 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
510 CHECK(!new_data_bz.empty());
511
512 vector<char> data; // Data blob that will be written to delta file.
513
514 DeltaArchiveManifest_InstallOperation operation;
515 size_t current_best_size = 0;
516 if (new_data.size() <= new_data_bz.size()) {
517 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
518 current_best_size = new_data.size();
519 data = new_data;
520 } else {
521 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
522 current_best_size = new_data_bz.size();
523 data = new_data_bz;
524 }
525
526 // Do we have an original file to consider?
527 struct stat old_stbuf;
Don Garrettf4b28742012-03-27 20:48:06 -0700528 bool original = !old_filename.empty();
529 if (original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700530 // If stat-ing the old file fails, it should be because it doesn't exist.
531 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Don Garrettf4b28742012-03-27 20:48:06 -0700532 original = false;
Darin Petkov68c10d12010-10-14 09:24:37 -0700533 }
Don Garrettf4b28742012-03-27 20:48:06 -0700534
535 if (original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700536 // Read old data
537 vector<char> old_data;
538 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
539 if (old_data == new_data) {
540 // No change in data.
541 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
542 current_best_size = 0;
543 data.clear();
Don Garrett36e60772012-03-29 10:31:20 -0700544 } else if (bsdiff_allowed) {
545 // If the source file is considered bsdiff safe (no bsdiff bugs
546 // triggered), see if BSDIFF encoding is smaller.
547 vector<char> bsdiff_delta;
548 TEST_AND_RETURN_FALSE(
549 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
550 CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
551 if (bsdiff_delta.size() < current_best_size) {
552 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
553 current_best_size = bsdiff_delta.size();
554 data = bsdiff_delta;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700555 }
556 }
557 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700558
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700559 // Set parameters of the operations
560 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700561
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700562 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
563 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700564 if (gather_extents) {
565 TEST_AND_RETURN_FALSE(
566 GatherExtents(old_filename, operation.mutable_src_extents()));
567 } else {
568 Extent* src_extent = operation.add_src_extents();
569 src_extent->set_start_block(0);
570 src_extent->set_num_blocks(
571 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
572 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700573 operation.set_src_length(old_stbuf.st_size);
574 }
575
Darin Petkov68c10d12010-10-14 09:24:37 -0700576 if (gather_extents) {
577 TEST_AND_RETURN_FALSE(
578 GatherExtents(new_filename, operation.mutable_dst_extents()));
579 } else {
580 Extent* dst_extent = operation.add_dst_extents();
581 dst_extent->set_start_block(0);
582 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
583 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700584 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700585
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 out_data->swap(data);
587 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700588
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700589 return true;
590}
591
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700592bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
593 const string& partition,
594 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700595 int64_t size = 0;
596 if (is_kernel) {
597 size = utils::FileSize(partition);
598 } else {
599 int block_count = 0, block_size = 0;
600 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
601 &block_count,
602 &block_size));
603 size = static_cast<int64_t>(block_count) * block_size;
604 }
605 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700606 info->set_size(size);
607 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700608 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700609 TEST_AND_RETURN_FALSE(hasher.Finalize());
610 const vector<char>& hash = hasher.raw_hash();
611 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700612 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700613 return true;
614}
615
616bool InitializePartitionInfos(const string& old_kernel,
617 const string& new_kernel,
618 const string& old_rootfs,
619 const string& new_rootfs,
620 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700621 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700622 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
623 true,
624 old_kernel,
625 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700626 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700627 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
628 true,
629 new_kernel,
630 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700631 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700632 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
633 false,
634 old_rootfs,
635 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700636 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700637 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
638 false,
639 new_rootfs,
640 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700641 return true;
642}
643
Andrew de los Reyesef017552010-10-06 17:57:52 -0700644namespace {
645
646// Takes a collection (vector or RepeatedPtrField) of Extent and
647// returns a vector of the blocks referenced, in order.
648template<typename T>
649vector<uint64_t> ExpandExtents(const T& extents) {
650 vector<uint64_t> ret;
651 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
652 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700653 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700654 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700655 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700656 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700657 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700658 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700659 }
660 }
661 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700662 return ret;
663}
664
665// Takes a vector of blocks and returns an equivalent vector of Extent
666// objects.
667vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
668 vector<Extent> new_extents;
669 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
670 it != e; ++it) {
671 graph_utils::AppendBlockToExtents(&new_extents, *it);
672 }
673 return new_extents;
674}
675
676} // namespace {}
677
678void DeltaDiffGenerator::SubstituteBlocks(
679 Vertex* vertex,
680 const vector<Extent>& remove_extents,
681 const vector<Extent>& replace_extents) {
682 // First, expand out the blocks that op reads from
683 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700684 {
685 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700686 vector<uint64_t> remove_extents_expanded =
687 ExpandExtents(remove_extents);
688 vector<uint64_t> replace_extents_expanded =
689 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700690 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700691 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700692 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700693 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700694 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
695 }
696 utils::ApplyMap(&read_blocks, conversion);
697 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
698 e = vertex->out_edges.end(); it != e; ++it) {
699 vector<uint64_t> write_before_deps_expanded =
700 ExpandExtents(it->second.write_extents);
701 utils::ApplyMap(&write_before_deps_expanded, conversion);
702 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700703 }
704 }
705 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700706 vertex->op.clear_src_extents();
707 vector<Extent> new_extents = CompressExtents(read_blocks);
708 DeltaDiffGenerator::StoreExtents(new_extents,
709 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700710}
711
712bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700713 const set<Edge>& edges,
714 vector<CutEdgeVertexes>* out_cuts) {
715 DummyExtentAllocator scratch_allocator;
716 vector<CutEdgeVertexes> cuts;
717 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700718
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700719 uint64_t scratch_blocks_used = 0;
720 for (set<Edge>::const_iterator it = edges.begin();
721 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700722 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700723 vector<Extent> old_extents =
724 (*graph)[it->first].out_edges[it->second].extents;
725 // Choose some scratch space
726 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700727 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700728 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
729 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700730 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700731 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700732 cuts.back().old_src = it->first;
733 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700734
Andrew de los Reyesef017552010-10-06 17:57:52 -0700735 EdgeProperties& cut_edge_properties =
736 (*graph)[it->first].out_edges.find(it->second)->second;
737
738 // This should never happen, as we should only be cutting edges between
739 // real file nodes, and write-before relationships are created from
740 // a real file node to a temp copy node:
741 CHECK(cut_edge_properties.write_extents.empty())
742 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700743
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700744 // make node depend on the copy operation
745 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700746 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700747
748 // Set src/dst extents and other proto variables for copy operation
749 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
750 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700751 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700752 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700753 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700754 graph->back().op.mutable_dst_extents());
755 graph->back().op.set_src_length(
756 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
757 graph->back().op.set_dst_length(graph->back().op.src_length());
758
759 // make the dest node read from the scratch space
760 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700761 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700762 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700763 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700764
765 // delete the old edge
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500766 CHECK_EQ(static_cast<Graph::size_type>(1),
767 (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700768
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700769 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700770 EdgeProperties write_before_edge_properties;
771 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
772 (*graph)[it->second].out_edges.insert(
773 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700774 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700775 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700776 return true;
777}
778
779// Stores all Extents in 'extents' into 'out'.
780void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700781 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700782 google::protobuf::RepeatedPtrField<Extent>* out) {
783 for (vector<Extent>::const_iterator it = extents.begin();
784 it != extents.end(); ++it) {
785 Extent* new_extent = out->Add();
786 *new_extent = *it;
787 }
788}
789
790// Creates all the edges for the graph. Writers of a block point to
791// readers of the same block. This is because for an edge A->B, B
792// must complete before A executes.
793void DeltaDiffGenerator::CreateEdges(Graph* graph,
794 const vector<Block>& blocks) {
795 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
796 // Blocks with both a reader and writer get an edge
797 if (blocks[i].reader == Vertex::kInvalidIndex ||
798 blocks[i].writer == Vertex::kInvalidIndex)
799 continue;
800 // Don't have a node depend on itself
801 if (blocks[i].reader == blocks[i].writer)
802 continue;
803 // See if there's already an edge we can add onto
804 Vertex::EdgeMap::iterator edge_it =
805 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
806 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
807 // No existing edge. Create one
808 (*graph)[blocks[i].writer].out_edges.insert(
809 make_pair(blocks[i].reader, EdgeProperties()));
810 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700811 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700812 }
813 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
814 }
815}
816
Andrew de los Reyesef017552010-10-06 17:57:52 -0700817namespace {
818
819class SortCutsByTopoOrderLess {
820 public:
821 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
822 : table_(table) {}
823 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
824 return table_[a.old_dst] < table_[b.old_dst];
825 }
826 private:
827 vector<vector<Vertex::Index>::size_type>& table_;
828};
829
830} // namespace {}
831
832void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
833 vector<Vertex::Index>& op_indexes,
834 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
835 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
836 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
837 i != e; ++i) {
838 Vertex::Index node = op_indexes[i];
839 if (table.size() < (node + 1)) {
840 table.resize(node + 1);
841 }
842 table[node] = i;
843 }
844 reverse_op_indexes->swap(table);
845}
846
847void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
848 vector<CutEdgeVertexes>* cuts) {
849 // first, make a reverse lookup table.
850 vector<vector<Vertex::Index>::size_type> table;
851 GenerateReverseTopoOrderMap(op_indexes, &table);
852 SortCutsByTopoOrderLess less(table);
853 sort(cuts->begin(), cuts->end(), less);
854}
855
856void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
857 vector<Vertex::Index>* op_indexes) {
858 vector<Vertex::Index> ret;
859 vector<Vertex::Index> full_ops;
860 ret.reserve(op_indexes->size());
861 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
862 ++i) {
863 DeltaArchiveManifest_InstallOperation_Type type =
864 (*graph)[(*op_indexes)[i]].op.type();
865 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
866 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
867 full_ops.push_back((*op_indexes)[i]);
868 } else {
869 ret.push_back((*op_indexes)[i]);
870 }
871 }
872 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
873 << (full_ops.size() + ret.size()) << " total ops.";
874 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
875 op_indexes->swap(ret);
876}
877
878namespace {
879
880template<typename T>
881bool TempBlocksExistInExtents(const T& extents) {
882 for (int i = 0, e = extents.size(); i < e; ++i) {
883 Extent extent = graph_utils::GetElement(extents, i);
884 uint64_t start = extent.start_block();
885 uint64_t num = extent.num_blocks();
886 if (start == kSparseHole)
887 continue;
888 if (start >= kTempBlockStart ||
889 (start + num) >= kTempBlockStart) {
890 LOG(ERROR) << "temp block!";
891 LOG(ERROR) << "start: " << start << ", num: " << num;
892 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
893 LOG(ERROR) << "returning true";
894 return true;
895 }
896 // check for wrap-around, which would be a bug:
897 CHECK(start <= (start + num));
898 }
899 return false;
900}
901
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700902// Convertes the cuts, which must all have the same |old_dst| member,
903// to full. It does this by converting the |old_dst| to REPLACE or
904// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
905// all temp nodes invalid.
906bool ConvertCutsToFull(
907 Graph* graph,
908 const string& new_root,
909 int data_fd,
910 off_t* data_file_size,
911 vector<Vertex::Index>* op_indexes,
912 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
913 const vector<CutEdgeVertexes>& cuts) {
914 CHECK(!cuts.empty());
915 set<Vertex::Index> deleted_nodes;
916 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
917 e = cuts.end(); it != e; ++it) {
918 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
919 graph,
920 *it,
921 new_root,
922 data_fd,
923 data_file_size));
924 deleted_nodes.insert(it->new_vertex);
925 }
926 deleted_nodes.insert(cuts[0].old_dst);
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700927
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700928 vector<Vertex::Index> new_op_indexes;
929 new_op_indexes.reserve(op_indexes->size());
930 for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
931 e = op_indexes->end(); it != e; ++it) {
932 if (utils::SetContainsKey(deleted_nodes, *it))
933 continue;
934 new_op_indexes.push_back(*it);
935 }
936 new_op_indexes.push_back(cuts[0].old_dst);
937 op_indexes->swap(new_op_indexes);
938 DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
939 reverse_op_indexes);
940 return true;
941}
942
943// Tries to assign temp blocks for a collection of cuts, all of which share
944// the same old_dst member. If temp blocks can't be found, old_dst will be
945// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
946// which can happen even if blocks are converted to full. Returns false
947// on exceptional error cases.
948bool AssignBlockForAdjoiningCuts(
949 Graph* graph,
950 const string& new_root,
951 int data_fd,
952 off_t* data_file_size,
953 vector<Vertex::Index>* op_indexes,
954 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
955 const vector<CutEdgeVertexes>& cuts) {
956 CHECK(!cuts.empty());
957 const Vertex::Index old_dst = cuts[0].old_dst;
958 // Calculate # of blocks needed
959 uint64_t blocks_needed = 0;
960 map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
961 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
962 e = cuts.end(); it != e; ++it) {
963 uint64_t cut_blocks_needed = 0;
964 for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
965 je = it->tmp_extents.end(); jt != je; ++jt) {
966 cut_blocks_needed += jt->num_blocks();
967 }
968 blocks_needed += cut_blocks_needed;
969 cuts_blocks_needed[&*it] = cut_blocks_needed;
970 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700971
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700972 // Find enough blocks
973 ExtentRanges scratch_ranges;
974 // Each block that's supplying temp blocks and the corresponding blocks:
975 typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
976 SupplierVector block_suppliers;
977 uint64_t scratch_blocks_found = 0;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700978 for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
979 e = op_indexes->size(); i < e; ++i) {
980 Vertex::Index test_node = (*op_indexes)[i];
981 if (!(*graph)[test_node].valid)
982 continue;
983 // See if this node has sufficient blocks
984 ExtentRanges ranges;
985 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
986 ranges.SubtractExtent(ExtentForRange(
987 kTempBlockStart, kSparseHole - kTempBlockStart));
988 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
989 // For now, for simplicity, subtract out all blocks in read-before
990 // dependencies.
991 for (Vertex::EdgeMap::const_iterator edge_i =
992 (*graph)[test_node].out_edges.begin(),
993 edge_e = (*graph)[test_node].out_edges.end();
994 edge_i != edge_e; ++edge_i) {
995 ranges.SubtractExtents(edge_i->second.extents);
996 }
997 if (ranges.blocks() == 0)
998 continue;
999
1000 if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
1001 // trim down ranges
1002 vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001003 blocks_needed - scratch_blocks_found);
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001004 ranges = ExtentRanges();
1005 ranges.AddExtents(new_ranges);
1006 }
1007 scratch_ranges.AddRanges(ranges);
1008 block_suppliers.push_back(make_pair(test_node, ranges));
1009 scratch_blocks_found += ranges.blocks();
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001010 if (scratch_ranges.blocks() >= blocks_needed)
1011 break;
1012 }
1013 if (scratch_ranges.blocks() < blocks_needed) {
1014 LOG(INFO) << "Unable to find sufficient scratch";
1015 TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1016 new_root,
1017 data_fd,
1018 data_file_size,
1019 op_indexes,
1020 reverse_op_indexes,
1021 cuts));
1022 return true;
1023 }
1024 // Use the scratch we found
1025 TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1026
1027 // Make all the suppliers depend on this node
1028 for (SupplierVector::iterator it = block_suppliers.begin(),
1029 e = block_suppliers.end(); it != e; ++it) {
1030 graph_utils::AddReadBeforeDepExtents(
1031 &(*graph)[it->first],
1032 old_dst,
1033 it->second.GetExtentsForBlockCount(it->second.blocks()));
1034 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001035
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001036 // Replace temp blocks in each cut
1037 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1038 e = cuts.end(); it != e; ++it) {
1039 vector<Extent> real_extents =
1040 scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[&*it]);
1041 scratch_ranges.SubtractExtents(real_extents);
1042
1043 // Fix the old dest node w/ the real blocks
1044 DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1045 it->tmp_extents,
1046 real_extents);
1047
1048 // Fix the new node w/ the real blocks. Since the new node is just a
1049 // copy operation, we can replace all the dest extents w/ the real
1050 // blocks.
1051 DeltaArchiveManifest_InstallOperation *op =
1052 &(*graph)[it->new_vertex].op;
1053 op->clear_dst_extents();
1054 DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1055 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001056 return true;
1057}
1058
Andrew de los Reyesef017552010-10-06 17:57:52 -07001059} // namespace {}
1060
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001061// Returns true if |op| is a no-op operation that doesn't do any useful work
1062// (e.g., a move operation that copies blocks onto themselves).
1063bool DeltaDiffGenerator::IsNoopOperation(
1064 const DeltaArchiveManifest_InstallOperation& op) {
1065 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1066 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1067}
1068
Andrew de los Reyesef017552010-10-06 17:57:52 -07001069bool DeltaDiffGenerator::AssignTempBlocks(
1070 Graph* graph,
1071 const string& new_root,
1072 int data_fd,
1073 off_t* data_file_size,
1074 vector<Vertex::Index>* op_indexes,
1075 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001076 const vector<CutEdgeVertexes>& cuts) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001077 CHECK(!cuts.empty());
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001078
1079 // group of cuts w/ the same old_dst:
1080 vector<CutEdgeVertexes> cuts_group;
1081
Andrew de los Reyesef017552010-10-06 17:57:52 -07001082 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1083 true ; --i) {
1084 LOG(INFO) << "Fixing temp blocks in cut " << i
1085 << ": old dst: " << cuts[i].old_dst << " new vertex: "
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001086 << cuts[i].new_vertex << " path: "
1087 << (*graph)[cuts[i].old_dst].file_name;
1088
1089 if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1090 cuts_group.push_back(cuts[i]);
1091 } else {
1092 CHECK(!cuts_group.empty());
1093 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1094 new_root,
1095 data_fd,
1096 data_file_size,
1097 op_indexes,
1098 reverse_op_indexes,
1099 cuts_group));
1100 cuts_group.clear();
1101 cuts_group.push_back(cuts[i]);
Andrew de los Reyesef017552010-10-06 17:57:52 -07001102 }
Darin Petkov36a58222010-10-07 22:00:09 -07001103
Andrew de los Reyesef017552010-10-06 17:57:52 -07001104 if (i == e) {
1105 // break out of for() loop
1106 break;
1107 }
1108 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001109 CHECK(!cuts_group.empty());
1110 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1111 new_root,
1112 data_fd,
1113 data_file_size,
1114 op_indexes,
1115 reverse_op_indexes,
1116 cuts_group));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001117 return true;
1118}
1119
1120bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1121 size_t idx = 0;
1122 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1123 ++it, ++idx) {
1124 if (!it->valid)
1125 continue;
1126 const DeltaArchiveManifest_InstallOperation& op = it->op;
1127 if (TempBlocksExistInExtents(op.dst_extents()) ||
1128 TempBlocksExistInExtents(op.src_extents())) {
1129 LOG(INFO) << "bad extents in node " << idx;
1130 LOG(INFO) << "so yeah";
1131 return false;
1132 }
1133
1134 // Check out-edges:
1135 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1136 je = it->out_edges.end(); jt != je; ++jt) {
1137 if (TempBlocksExistInExtents(jt->second.extents) ||
1138 TempBlocksExistInExtents(jt->second.write_extents)) {
1139 LOG(INFO) << "bad out edge in node " << idx;
1140 LOG(INFO) << "so yeah";
1141 return false;
1142 }
1143 }
1144 }
1145 return true;
1146}
1147
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001148bool DeltaDiffGenerator::ReorderDataBlobs(
1149 DeltaArchiveManifest* manifest,
1150 const std::string& data_blobs_path,
1151 const std::string& new_data_blobs_path) {
1152 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1153 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1154 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001155
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001156 DirectFileWriter writer;
1157 TEST_AND_RETURN_FALSE(
1158 writer.Open(new_data_blobs_path.c_str(),
1159 O_WRONLY | O_TRUNC | O_CREAT,
1160 0644) == 0);
1161 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001162 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001163
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001164 for (int i = 0; i < (manifest->install_operations_size() +
1165 manifest->kernel_install_operations_size()); i++) {
1166 DeltaArchiveManifest_InstallOperation* op = NULL;
1167 if (i < manifest->install_operations_size()) {
1168 op = manifest->mutable_install_operations(i);
1169 } else {
1170 op = manifest->mutable_kernel_install_operations(
1171 i - manifest->install_operations_size());
1172 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001173 if (!op->has_data_offset())
1174 continue;
1175 CHECK(op->has_data_length());
1176 vector<char> buf(op->data_length());
1177 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1178 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1179
1180 op->set_data_offset(out_file_size);
Don Garrette410e0f2011-11-10 15:39:01 -08001181 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001182 out_file_size += buf.size();
1183 }
1184 return true;
1185}
1186
Andrew de los Reyesef017552010-10-06 17:57:52 -07001187bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1188 const CutEdgeVertexes& cut,
1189 const string& new_root,
1190 int data_fd,
1191 off_t* data_file_size) {
1192 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001193
Andrew de los Reyesef017552010-10-06 17:57:52 -07001194 // Keep all outgoing edges
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001195 if ((*graph)[cut.old_dst].op.type() !=
1196 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1197 (*graph)[cut.old_dst].op.type() !=
1198 DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1199 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1200 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001201
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001202 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1203 cut.old_dst,
1204 NULL,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -08001205 kNonexistentPath,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001206 new_root,
1207 (*graph)[cut.old_dst].file_name,
1208 data_fd,
1209 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001210
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001211 (*graph)[cut.old_dst].out_edges = out_edges;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001212
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001213 // Right now we don't have doubly-linked edges, so we have to scan
1214 // the whole graph.
1215 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1216 }
Andrew de los Reyesef017552010-10-06 17:57:52 -07001217
1218 // Delete temp node
1219 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1220 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1221 (*graph)[cut.old_dst].out_edges.end());
1222 (*graph)[cut.new_vertex].valid = false;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001223 LOG(INFO) << "marked node invalid: " << cut.new_vertex;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001224 return true;
1225}
1226
1227bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1228 const string& new_root,
1229 int fd,
1230 off_t* data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001231 vector<Vertex::Index>* final_order,
1232 Vertex::Index scratch_vertex) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001233 CycleBreaker cycle_breaker;
1234 LOG(INFO) << "Finding cycles...";
1235 set<Edge> cut_edges;
1236 cycle_breaker.BreakCycles(*graph, &cut_edges);
1237 LOG(INFO) << "done finding cycles";
1238 CheckGraph(*graph);
1239
1240 // Calculate number of scratch blocks needed
1241
1242 LOG(INFO) << "Cutting cycles...";
1243 vector<CutEdgeVertexes> cuts;
1244 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1245 LOG(INFO) << "done cutting cycles";
1246 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1247 CheckGraph(*graph);
1248
1249 LOG(INFO) << "Creating initial topological order...";
1250 TopologicalSort(*graph, final_order);
1251 LOG(INFO) << "done with initial topo order";
1252 CheckGraph(*graph);
1253
1254 LOG(INFO) << "Moving full ops to the back";
1255 MoveFullOpsToBack(graph, final_order);
1256 LOG(INFO) << "done moving full ops to back";
1257
1258 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1259 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1260
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001261 SortCutsByTopoOrder(*final_order, &cuts);
1262
Andrew de los Reyesef017552010-10-06 17:57:52 -07001263 if (!cuts.empty())
1264 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1265 new_root,
1266 fd,
1267 data_file_size,
1268 final_order,
1269 &inverse_final_order,
1270 cuts));
1271 LOG(INFO) << "Making sure all temp blocks have been allocated";
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001272
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001273 // Remove the scratch node, if any
1274 if (scratch_vertex != Vertex::kInvalidIndex) {
1275 final_order->erase(final_order->begin() +
1276 inverse_final_order[scratch_vertex]);
1277 (*graph)[scratch_vertex].valid = false;
1278 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1279 }
1280
Andrew de los Reyesef017552010-10-06 17:57:52 -07001281 graph_utils::DumpGraph(*graph);
1282 CHECK(NoTempBlocksRemain(*graph));
1283 LOG(INFO) << "done making sure all temp blocks are allocated";
1284 return true;
1285}
1286
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001287void DeltaDiffGenerator::CreateScratchNode(uint64_t start_block,
1288 uint64_t num_blocks,
1289 Vertex* vertex) {
1290 vertex->file_name = "<scratch>";
1291 vertex->op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1292 vertex->op.set_data_offset(0);
1293 vertex->op.set_data_length(0);
1294 Extent* extent = vertex->op.add_dst_extents();
1295 extent->set_start_block(start_block);
1296 extent->set_num_blocks(num_blocks);
1297}
1298
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001299bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1300 const string& old_root,
1301 const string& old_image,
1302 const string& new_root,
1303 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001304 const string& old_kernel_part,
1305 const string& new_kernel_part,
1306 const string& output_path,
1307 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001308 int old_image_block_count = 0, old_image_block_size = 0;
1309 int new_image_block_count = 0, new_image_block_size = 0;
1310 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1311 &new_image_block_count,
1312 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001313 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001314 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1315 &old_image_block_count,
1316 &old_image_block_size));
1317 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1318 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1319 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001320 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001321 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001322 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1323
Darin Petkov7ea32332010-10-13 10:46:11 -07001324 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1325 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1326 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001327 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1328 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1329 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1330 }
1331 Graph graph;
1332 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001333
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001334 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1335 string temp_file_path;
Darin Petkov7438a5c2011-08-29 11:56:44 -07001336 scoped_ptr<ScopedPathUnlinker> temp_file_unlinker;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001337 off_t data_file_size = 0;
1338
1339 LOG(INFO) << "Reading files...";
1340
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001341 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1342
Andrew de los Reyesef017552010-10-06 17:57:52 -07001343 vector<Vertex::Index> final_order;
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001344 Vertex::Index scratch_vertex = Vertex::kInvalidIndex;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001345 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001346 int fd;
1347 TEST_AND_RETURN_FALSE(
1348 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001349 temp_file_unlinker.reset(new ScopedPathUnlinker(temp_file_path));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001350 TEST_AND_RETURN_FALSE(fd >= 0);
1351 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001352 if (!old_image.empty()) {
1353 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001354
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001355 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1356 &blocks,
1357 old_root,
1358 new_root,
1359 fd,
1360 &data_file_size));
1361 LOG(INFO) << "done reading normal files";
1362 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001363
Thieu Le5c7d9752010-12-15 16:09:28 -08001364 LOG(INFO) << "Starting metadata processing";
1365 TEST_AND_RETURN_FALSE(Metadata::DeltaReadMetadata(&graph,
1366 &blocks,
1367 old_image,
1368 new_image,
1369 fd,
1370 &data_file_size));
1371 LOG(INFO) << "Done metadata processing";
1372 CheckGraph(graph);
1373
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001374 graph.resize(graph.size() + 1);
1375 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1376 fd,
1377 &data_file_size,
1378 new_image,
1379 &graph.back()));
1380
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001381 // Final scratch block (if there's space)
1382 if (blocks.size() < (kRootFSPartitionSize / kBlockSize)) {
1383 scratch_vertex = graph.size();
1384 graph.resize(graph.size() + 1);
1385 CreateScratchNode(blocks.size(),
1386 (kRootFSPartitionSize / kBlockSize) - blocks.size(),
1387 &graph.back());
1388 }
1389
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001390 // Read kernel partition
1391 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1392 new_kernel_part,
1393 &kernel_ops,
1394 fd,
1395 &data_file_size));
1396
1397 LOG(INFO) << "done reading kernel";
1398 CheckGraph(graph);
1399
1400 LOG(INFO) << "Creating edges...";
1401 CreateEdges(&graph, blocks);
1402 LOG(INFO) << "Done creating edges";
1403 CheckGraph(graph);
1404
1405 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1406 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001407 fd,
1408 &data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001409 &final_order,
1410 scratch_vertex));
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001411 } else {
1412 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001413 off_t new_image_size =
1414 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Darin Petkov7a22d792010-11-08 14:10:00 -08001415 TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1416 new_kernel_part,
1417 new_image,
1418 new_image_size,
1419 fd,
1420 &data_file_size,
1421 kFullUpdateChunkSize,
1422 kBlockSize,
1423 &kernel_ops,
1424 &final_order));
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001425 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001426 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001427
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001428 // Convert to protobuf Manifest object
1429 DeltaArchiveManifest manifest;
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001430 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001431 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001432 InstallOperationsToManifest(graph,
1433 final_order,
1434 kernel_ops,
1435 &manifest,
1436 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001437 CheckGraph(graph);
1438 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001439
1440 // Reorder the data blobs with the newly ordered manifest
1441 string ordered_blobs_path;
1442 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1443 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1444 &ordered_blobs_path,
Andrew de los Reyese05fc282011-06-02 09:50:08 -07001445 NULL));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001446 ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001447 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1448 temp_file_path,
1449 ordered_blobs_path));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001450 temp_file_unlinker.reset();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001451
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001452 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001453 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001454 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001455 for (int i = 0; i < (manifest.install_operations_size() +
1456 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001457 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001458 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001459 manifest.mutable_install_operations(i) :
1460 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001461 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001462 if (op->has_data_offset()) {
1463 if (op->data_offset() != next_blob_offset) {
1464 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001465 << next_blob_offset;
1466 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001467 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001468 }
1469 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001470 }
1471
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001472 // Signatures appear at the end of the blobs. Note the offset in the
1473 // manifest
1474 if (!private_key_path.empty()) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001475 uint64_t signature_blob_length = 0;
1476 TEST_AND_RETURN_FALSE(
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001477 PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001478 &signature_blob_length));
Darin Petkov9574f7e2011-01-13 10:48:12 -08001479 AddSignatureOp(next_blob_offset, signature_blob_length, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001480 }
1481
Darin Petkov36a58222010-10-07 22:00:09 -07001482 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1483 new_kernel_part,
1484 old_image,
1485 new_image,
1486 &manifest));
1487
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001488 // Serialize protobuf
1489 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001490
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001491 CheckGraph(graph);
1492 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1493 CheckGraph(graph);
1494
1495 LOG(INFO) << "Writing final delta file header...";
1496 DirectFileWriter writer;
1497 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1498 O_WRONLY | O_CREAT | O_TRUNC,
1499 0644) == 0);
1500 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001501
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001502 // Write header
Don Garrette410e0f2011-11-10 15:39:01 -08001503 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001504
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001505 // Write version number
1506 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001507
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001508 // Write protobuf length
1509 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1510 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001511
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001512 // Write protobuf
1513 LOG(INFO) << "Writing final delta file protobuf... "
1514 << serialized_manifest.size();
1515 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
Don Garrette410e0f2011-11-10 15:39:01 -08001516 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001517
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001518 // Append the data blobs
1519 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001520 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001521 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1522 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1523 for (;;) {
1524 char buf[kBlockSize];
1525 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1526 if (0 == rc) {
1527 // EOF
1528 break;
1529 }
1530 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
Don Garrette410e0f2011-11-10 15:39:01 -08001531 TEST_AND_RETURN_FALSE(writer.Write(buf, rc));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001532 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001533
1534 // Write signature blob.
1535 if (!private_key_path.empty()) {
1536 LOG(INFO) << "Signing the update...";
1537 vector<char> signature_blob;
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001538 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
1539 output_path,
1540 vector<string>(1, private_key_path),
1541 &signature_blob));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001542 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
Don Garrette410e0f2011-11-10 15:39:01 -08001543 signature_blob.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001544 }
1545
Darin Petkov95cf01f2010-10-12 14:59:13 -07001546 int64_t manifest_metadata_size =
1547 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001548 ReportPayloadUsage(manifest, manifest_metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001549
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001550 LOG(INFO) << "All done. Successfully created delta file.";
1551 return true;
1552}
1553
Thieu Le5c7d9752010-12-15 16:09:28 -08001554// Runs the bsdiff tool on two files and returns the resulting delta in
1555// 'out'. Returns true on success.
1556bool DeltaDiffGenerator::BsdiffFiles(const string& old_file,
1557 const string& new_file,
1558 vector<char>* out) {
1559 const string kPatchFile = "/tmp/delta.patchXXXXXX";
1560 string patch_file_path;
1561
1562 TEST_AND_RETURN_FALSE(
1563 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
1564
1565 vector<string> cmd;
1566 cmd.push_back(kBsdiffPath);
1567 cmd.push_back(old_file);
1568 cmd.push_back(new_file);
1569 cmd.push_back(patch_file_path);
1570
1571 int rc = 1;
1572 vector<char> patch_file;
Darin Petkov85d02b72011-05-17 13:25:51 -07001573 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, NULL));
Thieu Le5c7d9752010-12-15 16:09:28 -08001574 TEST_AND_RETURN_FALSE(rc == 0);
1575 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
1576 unlink(patch_file_path.c_str());
1577 return true;
1578}
1579
1580// The |blocks| vector contains a reader and writer for each block on the
1581// filesystem that's being in-place updated. We populate the reader/writer
1582// fields of |blocks| by calling this function.
1583// For each block in |operation| that is read or written, find that block
1584// in |blocks| and set the reader/writer field to the vertex passed.
1585// |graph| is not strictly necessary, but useful for printing out
1586// error messages.
1587bool DeltaDiffGenerator::AddInstallOpToBlocksVector(
1588 const DeltaArchiveManifest_InstallOperation& operation,
1589 const Graph& graph,
1590 Vertex::Index vertex,
1591 vector<Block>* blocks) {
1592 // See if this is already present.
1593 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
1594
1595 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
1596 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
1597 const int extents_size =
1598 (field == READER) ? operation.src_extents_size() :
1599 operation.dst_extents_size();
1600 const char* past_participle = (field == READER) ? "read" : "written";
1601 const google::protobuf::RepeatedPtrField<Extent>& extents =
1602 (field == READER) ? operation.src_extents() : operation.dst_extents();
1603 Vertex::Index Block::*access_type =
1604 (field == READER) ? &Block::reader : &Block::writer;
1605
1606 for (int i = 0; i < extents_size; i++) {
1607 const Extent& extent = extents.Get(i);
1608 if (extent.start_block() == kSparseHole) {
1609 // Hole in sparse file. skip
1610 continue;
1611 }
1612 for (uint64_t block = extent.start_block();
1613 block < (extent.start_block() + extent.num_blocks()); block++) {
1614 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
1615 LOG(FATAL) << "Block " << block << " is already "
1616 << past_participle << " by "
1617 << (*blocks)[block].*access_type << "("
1618 << graph[(*blocks)[block].*access_type].file_name
1619 << ") and also " << vertex << "("
1620 << graph[vertex].file_name << ")";
1621 }
1622 (*blocks)[block].*access_type = vertex;
1623 }
1624 }
1625 }
1626 return true;
1627}
1628
Darin Petkov9574f7e2011-01-13 10:48:12 -08001629void DeltaDiffGenerator::AddSignatureOp(uint64_t signature_blob_offset,
1630 uint64_t signature_blob_length,
1631 DeltaArchiveManifest* manifest) {
1632 LOG(INFO) << "Making room for signature in file";
1633 manifest->set_signatures_offset(signature_blob_offset);
1634 LOG(INFO) << "set? " << manifest->has_signatures_offset();
1635 // Add a dummy op at the end to appease older clients
1636 DeltaArchiveManifest_InstallOperation* dummy_op =
1637 manifest->add_kernel_install_operations();
1638 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1639 dummy_op->set_data_offset(signature_blob_offset);
1640 manifest->set_signatures_offset(signature_blob_offset);
1641 dummy_op->set_data_length(signature_blob_length);
1642 manifest->set_signatures_size(signature_blob_length);
1643 Extent* dummy_extent = dummy_op->add_dst_extents();
1644 // Tell the dummy op to write this data to a big sparse hole
1645 dummy_extent->set_start_block(kSparseHole);
1646 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1647 kBlockSize);
1648}
1649
Andrew de los Reyes50f36492010-11-01 13:57:12 -07001650const char* const kBsdiffPath = "bsdiff";
1651const char* const kBspatchPath = "bspatch";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001652const char* const kDeltaMagic = "CrAU";
1653
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001654}; // namespace chromeos_update_engine