blob: cc8f3525e1fd07bbd29de6682265611b120aea69 [file] [log] [blame]
Darin Petkov85d02b72011-05-17 13:25:51 -07001// Copyright (c) 2011 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
105 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700106 new_root + path,
107 &data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700108 &operation,
109 true));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700110
111 // Write the data
112 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
113 operation.set_data_offset(*data_file_size);
114 operation.set_data_length(data.size());
115 }
116
117 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
118 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700119
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700120 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700121 Vertex::Index vertex = existing_vertex;
122 if (vertex == Vertex::kInvalidIndex) {
123 graph->resize(graph->size() + 1);
124 vertex = graph->size() - 1;
125 }
126 (*graph)[vertex].op = operation;
127 CHECK((*graph)[vertex].op.has_type());
128 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700129
Andrew de los Reyesef017552010-10-06 17:57:52 -0700130 if (blocks)
Thieu Le5c7d9752010-12-15 16:09:28 -0800131 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
132 (*graph)[vertex].op,
133 *graph,
134 vertex,
135 blocks));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700136 return true;
137}
138
139// For each regular file within new_root, creates a node in the graph,
140// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
141// and writes any necessary data to the end of data_fd.
142bool DeltaReadFiles(Graph* graph,
143 vector<Block>* blocks,
144 const string& old_root,
145 const string& new_root,
146 int data_fd,
147 off_t* data_file_size) {
148 set<ino_t> visited_inodes;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800149 set<ino_t> visited_src_inodes;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700150 for (FilesystemIterator fs_iter(new_root,
151 utils::SetWithValue<string>("/lost+found"));
152 !fs_iter.IsEnd(); fs_iter.Increment()) {
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800153 // We never diff symlinks (here, we check that dst file is not a symlink).
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700154 if (!S_ISREG(fs_iter.GetStat().st_mode))
155 continue;
156
157 // Make sure we visit each inode only once.
158 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
159 continue;
160 visited_inodes.insert(fs_iter.GetStat().st_ino);
161 if (fs_iter.GetStat().st_size == 0)
162 continue;
163
164 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700165
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800166 // We can't visit each dst image inode more than once, as that would
167 // duplicate work. Here, we avoid visiting each source image inode
168 // more than once. Technically, we could have multiple operations
169 // that read the same blocks from the source image for diffing, but
170 // we choose not to to avoid complexity. Eventually we will move away
171 // from using a graph/cycle detection/etc to generate diffs, and at that
172 // time, it will be easy (non-complex) to have many operations read
173 // from the same source blocks. At that time, this code can die. -adlr
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800174 bool should_diff_from_source = false;
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800175 string src_path = old_root + fs_iter.GetPartialPath();
Andrew de los Reyes48a0a482011-02-22 15:32:11 -0800176 struct stat src_stbuf;
177 // We never diff symlinks (here, we check that src file is not a symlink).
178 if (0 == lstat(src_path.c_str(), &src_stbuf) &&
179 S_ISREG(src_stbuf.st_mode)) {
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800180 should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
181 src_stbuf.st_ino);
182 visited_src_inodes.insert(src_stbuf.st_ino);
183 }
184
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700185 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700186 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700187 blocks,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -0800188 (should_diff_from_source ?
189 old_root :
190 kNonexistentPath),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700191 new_root,
192 fs_iter.GetPartialPath(),
193 data_fd,
194 data_file_size));
195 }
196 return true;
197}
198
Andrew de los Reyesef017552010-10-06 17:57:52 -0700199// This class allocates non-existent temp blocks, starting from
200// kTempBlockStart. Other code is responsible for converting these
201// temp blocks into real blocks, as the client can't read or write to
202// these blocks.
203class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700204 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700205 explicit DummyExtentAllocator()
206 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700207 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700208 vector<Extent> ret(1);
209 ret[0].set_start_block(next_block_);
210 ret[0].set_num_blocks(block_count);
211 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700212 return ret;
213 }
214 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700215 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700216};
217
218// Reads blocks from image_path that are not yet marked as being written
219// in the blocks array. These blocks that remain are non-file-data blocks.
220// In the future we might consider intelligent diffing between this data
221// and data in the previous image, but for now we just bzip2 compress it
222// and include it in the update.
223// Creates a new node in the graph to write these blocks and writes the
224// appropriate blob to blobs_fd. Reads and updates blobs_length;
225bool ReadUnwrittenBlocks(const vector<Block>& blocks,
226 int blobs_fd,
227 off_t* blobs_length,
228 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700229 Vertex* vertex) {
Darin Petkovabe7cc92010-10-08 12:29:32 -0700230 vertex->file_name = "<rootfs-non-file-data>";
231
Andrew de los Reyesef017552010-10-06 17:57:52 -0700232 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700233 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
234 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
235 ScopedFdCloser image_fd_closer(&image_fd);
236
237 string temp_file_path;
238 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
239 &temp_file_path,
240 NULL));
241
242 FILE* file = fopen(temp_file_path.c_str(), "w");
243 TEST_AND_RETURN_FALSE(file);
244 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700245
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700246 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
247 file,
248 9, // max compression
249 0, // verbosity
250 0); // default work factor
251 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700252
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700253 vector<Extent> extents;
254 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700255
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700256 LOG(INFO) << "Appending left over blocks to extents";
257 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
258 if (blocks[i].writer != Vertex::kInvalidIndex)
259 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700260 if (blocks[i].reader != Vertex::kInvalidIndex) {
261 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
262 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700263 graph_utils::AppendBlockToExtents(&extents, i);
264 block_count++;
265 }
266
267 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
268 // so we arbitrarily set it to 1024 * kBlockSize.
269 vector<char> buf(1024 * kBlockSize);
270
271 LOG(INFO) << "Reading left over blocks";
272 vector<Block>::size_type blocks_copied_count = 0;
273
274 // For each extent in extents, write the data into BZ2_bzWrite which
275 // sends it to an output file.
276 // We use the temporary buffer 'buf' to hold the data, which may be
277 // smaller than the extent, so in that case we have to loop to get
278 // the extent's data (that's the inner while loop).
279 for (vector<Extent>::const_iterator it = extents.begin();
280 it != extents.end(); ++it) {
281 vector<Block>::size_type blocks_read = 0;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800282 float printed_progress = -1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700283 while (blocks_read < it->num_blocks()) {
284 const int copy_block_cnt =
285 min(buf.size() / kBlockSize,
286 static_cast<vector<char>::size_type>(
287 it->num_blocks() - blocks_read));
288 ssize_t rc = pread(image_fd,
289 &buf[0],
290 copy_block_cnt * kBlockSize,
291 (it->start_block() + blocks_read) * kBlockSize);
292 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
293 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
294 copy_block_cnt * kBlockSize);
295 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
296 TEST_AND_RETURN_FALSE(err == BZ_OK);
297 blocks_read += copy_block_cnt;
298 blocks_copied_count += copy_block_cnt;
Andrew de los Reyes4b8740f2010-11-08 17:09:11 -0800299 float current_progress =
300 static_cast<float>(blocks_copied_count) / block_count;
301 if (printed_progress + 0.1 < current_progress ||
302 blocks_copied_count == block_count) {
303 LOG(INFO) << "progress: " << current_progress;
304 printed_progress = current_progress;
305 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700306 }
307 }
308 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
309 TEST_AND_RETURN_FALSE(err == BZ_OK);
310 bz_file = NULL;
311 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
312 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700313
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700314 vector<char> compressed_data;
315 LOG(INFO) << "Reading compressed data off disk";
316 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
317 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700318
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700319 // Add node to graph to write these blocks
320 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
321 out_op->set_data_offset(*blobs_length);
322 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700323 LOG(INFO) << "Rootfs non-data blocks compressed take up "
324 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700325 *blobs_length += compressed_data.size();
326 out_op->set_dst_length(kBlockSize * block_count);
327 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700328
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700329 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
330 &compressed_data[0],
331 compressed_data.size()));
332 LOG(INFO) << "done with extra blocks";
333 return true;
334}
335
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700336// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700337// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700338bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
339 uint64_t value_be = htobe64(value);
Don Garrette410e0f2011-11-10 15:39:01 -0800340 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700341 return true;
342}
343
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700344// Adds each operation from |graph| to |out_manifest| in the order specified by
345// |order| while building |out_op_name_map| with operation to name
346// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
347// operations.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700348void InstallOperationsToManifest(
349 const Graph& graph,
350 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700351 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700352 DeltaArchiveManifest* out_manifest,
353 OperationNameMap* out_op_name_map) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700354 for (vector<Vertex::Index>::const_iterator it = order.begin();
355 it != order.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700356 const Vertex& vertex = graph[*it];
357 const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
358 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
359 continue;
360 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700361 DeltaArchiveManifest_InstallOperation* op =
362 out_manifest->add_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700363 *op = add_op;
364 (*out_op_name_map)[op] = &vertex.file_name;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700366 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
367 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700368 const DeltaArchiveManifest_InstallOperation& add_op = *it;
369 if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
370 continue;
371 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700372 DeltaArchiveManifest_InstallOperation* op =
373 out_manifest->add_kernel_install_operations();
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700374 *op = add_op;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700375 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700376}
377
378void CheckGraph(const Graph& graph) {
379 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
380 CHECK(it->op.has_type());
381 }
382}
383
Darin Petkov68c10d12010-10-14 09:24:37 -0700384// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
385// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
386// string, generates a full update of the partition.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700387bool DeltaCompressKernelPartition(
388 const string& old_kernel_part,
389 const string& new_kernel_part,
390 vector<DeltaArchiveManifest_InstallOperation>* ops,
391 int blobs_fd,
392 off_t* blobs_length) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700393 LOG(INFO) << "Delta compressing kernel partition...";
Darin Petkov68c10d12010-10-14 09:24:37 -0700394 LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700395
396 // Add a new install operation
397 ops->resize(1);
398 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700399
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700400 vector<char> data;
Darin Petkov68c10d12010-10-14 09:24:37 -0700401 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
402 new_kernel_part,
403 &data,
404 op,
405 false));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700406
Darin Petkov68c10d12010-10-14 09:24:37 -0700407 // Write the data
408 if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
409 op->set_data_offset(*blobs_length);
410 op->set_data_length(data.size());
411 }
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700412
Darin Petkov68c10d12010-10-14 09:24:37 -0700413 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
414 *blobs_length += data.size();
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700415
Darin Petkov68c10d12010-10-14 09:24:37 -0700416 LOG(INFO) << "Done delta compressing kernel partition: "
417 << kInstallOperationTypes[op->type()];
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700418 return true;
419}
420
Darin Petkov880335c2010-10-01 15:52:53 -0700421struct DeltaObject {
422 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
423 : name(in_name),
424 type(in_type),
425 size(in_size) {}
426 bool operator <(const DeltaObject& object) const {
Darin Petkovd43d6902010-10-14 11:17:50 -0700427 return (size != object.size) ? (size < object.size) : (name < object.name);
Darin Petkov880335c2010-10-01 15:52:53 -0700428 }
429 string name;
430 int type;
431 off_t size;
432};
433
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700434void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
435 const int64_t manifest_metadata_size,
436 const OperationNameMap& op_name_map) {
Darin Petkov880335c2010-10-01 15:52:53 -0700437 vector<DeltaObject> objects;
438 off_t total_size = 0;
439
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700440 // Rootfs install operations.
441 for (int i = 0; i < manifest.install_operations_size(); ++i) {
442 const DeltaArchiveManifest_InstallOperation& op =
443 manifest.install_operations(i);
444 objects.push_back(DeltaObject(*op_name_map.find(&op)->second,
445 op.type(),
446 op.data_length()));
447 total_size += op.data_length();
Darin Petkov880335c2010-10-01 15:52:53 -0700448 }
449
Darin Petkov880335c2010-10-01 15:52:53 -0700450 // Kernel install operations.
451 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
452 const DeltaArchiveManifest_InstallOperation& op =
453 manifest.kernel_install_operations(i);
454 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
455 op.type(),
456 op.data_length()));
457 total_size += op.data_length();
458 }
459
Darin Petkov95cf01f2010-10-12 14:59:13 -0700460 objects.push_back(DeltaObject("<manifest-metadata>",
461 -1,
462 manifest_metadata_size));
463 total_size += manifest_metadata_size;
464
Darin Petkov880335c2010-10-01 15:52:53 -0700465 std::sort(objects.begin(), objects.end());
466
467 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
468 for (vector<DeltaObject>::const_iterator it = objects.begin();
469 it != objects.end(); ++it) {
470 const DeltaObject& object = *it;
471 fprintf(stderr, kFormatString,
472 object.size * 100.0 / total_size,
473 object.size,
Darin Petkov95cf01f2010-10-12 14:59:13 -0700474 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
Darin Petkov880335c2010-10-01 15:52:53 -0700475 object.name.c_str());
476 }
477 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
478}
479
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700480} // namespace {}
481
482bool DeltaDiffGenerator::ReadFileToDiff(
483 const string& old_filename,
484 const string& new_filename,
485 vector<char>* out_data,
Darin Petkov68c10d12010-10-14 09:24:37 -0700486 DeltaArchiveManifest_InstallOperation* out_op,
487 bool gather_extents) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700488 // Read new data in
489 vector<char> new_data;
490 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700491
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700492 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700493
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700494 vector<char> new_data_bz;
495 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
496 CHECK(!new_data_bz.empty());
497
498 vector<char> data; // Data blob that will be written to delta file.
499
500 DeltaArchiveManifest_InstallOperation operation;
501 size_t current_best_size = 0;
502 if (new_data.size() <= new_data_bz.size()) {
503 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
504 current_best_size = new_data.size();
505 data = new_data;
506 } else {
507 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
508 current_best_size = new_data_bz.size();
509 data = new_data_bz;
510 }
511
512 // Do we have an original file to consider?
513 struct stat old_stbuf;
Darin Petkov68c10d12010-10-14 09:24:37 -0700514 bool no_original = old_filename.empty();
515 if (!no_original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700516 // If stat-ing the old file fails, it should be because it doesn't exist.
517 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
Darin Petkov68c10d12010-10-14 09:24:37 -0700518 no_original = true;
519 }
520 if (!no_original) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700521 // Read old data
522 vector<char> old_data;
523 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
524 if (old_data == new_data) {
525 // No change in data.
526 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
527 current_best_size = 0;
528 data.clear();
529 } else {
530 // Try bsdiff of old to new data
531 vector<char> bsdiff_delta;
532 TEST_AND_RETURN_FALSE(
533 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
534 CHECK_GT(bsdiff_delta.size(), 0);
535 if (bsdiff_delta.size() < current_best_size) {
536 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
537 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700538
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700539 data = bsdiff_delta;
540 }
541 }
542 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700543
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700544 // Set parameters of the operations
545 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700546
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700547 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
548 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Darin Petkov68c10d12010-10-14 09:24:37 -0700549 if (gather_extents) {
550 TEST_AND_RETURN_FALSE(
551 GatherExtents(old_filename, operation.mutable_src_extents()));
552 } else {
553 Extent* src_extent = operation.add_src_extents();
554 src_extent->set_start_block(0);
555 src_extent->set_num_blocks(
556 (old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
557 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700558 operation.set_src_length(old_stbuf.st_size);
559 }
560
Darin Petkov68c10d12010-10-14 09:24:37 -0700561 if (gather_extents) {
562 TEST_AND_RETURN_FALSE(
563 GatherExtents(new_filename, operation.mutable_dst_extents()));
564 } else {
565 Extent* dst_extent = operation.add_dst_extents();
566 dst_extent->set_start_block(0);
567 dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
568 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700569 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700570
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700571 out_data->swap(data);
572 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700573
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700574 return true;
575}
576
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700577bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
578 const string& partition,
579 PartitionInfo* info) {
Darin Petkov7ea32332010-10-13 10:46:11 -0700580 int64_t size = 0;
581 if (is_kernel) {
582 size = utils::FileSize(partition);
583 } else {
584 int block_count = 0, block_size = 0;
585 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
586 &block_count,
587 &block_size));
588 size = static_cast<int64_t>(block_count) * block_size;
589 }
590 TEST_AND_RETURN_FALSE(size > 0);
Darin Petkov36a58222010-10-07 22:00:09 -0700591 info->set_size(size);
592 OmahaHashCalculator hasher;
Darin Petkov7ea32332010-10-13 10:46:11 -0700593 TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
Darin Petkov36a58222010-10-07 22:00:09 -0700594 TEST_AND_RETURN_FALSE(hasher.Finalize());
595 const vector<char>& hash = hasher.raw_hash();
596 info->set_hash(hash.data(), hash.size());
Darin Petkovd43d6902010-10-14 11:17:50 -0700597 LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
Darin Petkov36a58222010-10-07 22:00:09 -0700598 return true;
599}
600
601bool InitializePartitionInfos(const string& old_kernel,
602 const string& new_kernel,
603 const string& old_rootfs,
604 const string& new_rootfs,
605 DeltaArchiveManifest* manifest) {
Darin Petkovd43d6902010-10-14 11:17:50 -0700606 if (!old_kernel.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700607 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
608 true,
609 old_kernel,
610 manifest->mutable_old_kernel_info()));
Darin Petkovd43d6902010-10-14 11:17:50 -0700611 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700612 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
613 true,
614 new_kernel,
615 manifest->mutable_new_kernel_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700616 if (!old_rootfs.empty()) {
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700617 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
618 false,
619 old_rootfs,
620 manifest->mutable_old_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700621 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700622 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
623 false,
624 new_rootfs,
625 manifest->mutable_new_rootfs_info()));
Darin Petkov36a58222010-10-07 22:00:09 -0700626 return true;
627}
628
Andrew de los Reyesef017552010-10-06 17:57:52 -0700629namespace {
630
631// Takes a collection (vector or RepeatedPtrField) of Extent and
632// returns a vector of the blocks referenced, in order.
633template<typename T>
634vector<uint64_t> ExpandExtents(const T& extents) {
635 vector<uint64_t> ret;
636 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
637 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700638 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700639 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700640 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700642 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700643 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700644 }
645 }
646 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700647 return ret;
648}
649
650// Takes a vector of blocks and returns an equivalent vector of Extent
651// objects.
652vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
653 vector<Extent> new_extents;
654 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
655 it != e; ++it) {
656 graph_utils::AppendBlockToExtents(&new_extents, *it);
657 }
658 return new_extents;
659}
660
661} // namespace {}
662
663void DeltaDiffGenerator::SubstituteBlocks(
664 Vertex* vertex,
665 const vector<Extent>& remove_extents,
666 const vector<Extent>& replace_extents) {
667 // First, expand out the blocks that op reads from
668 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700669 {
670 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700671 vector<uint64_t> remove_extents_expanded =
672 ExpandExtents(remove_extents);
673 vector<uint64_t> replace_extents_expanded =
674 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700675 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700676 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700677 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700678 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700679 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
680 }
681 utils::ApplyMap(&read_blocks, conversion);
682 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
683 e = vertex->out_edges.end(); it != e; ++it) {
684 vector<uint64_t> write_before_deps_expanded =
685 ExpandExtents(it->second.write_extents);
686 utils::ApplyMap(&write_before_deps_expanded, conversion);
687 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700688 }
689 }
690 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700691 vertex->op.clear_src_extents();
692 vector<Extent> new_extents = CompressExtents(read_blocks);
693 DeltaDiffGenerator::StoreExtents(new_extents,
694 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700695}
696
697bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700698 const set<Edge>& edges,
699 vector<CutEdgeVertexes>* out_cuts) {
700 DummyExtentAllocator scratch_allocator;
701 vector<CutEdgeVertexes> cuts;
702 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700703
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700704 uint64_t scratch_blocks_used = 0;
705 for (set<Edge>::const_iterator it = edges.begin();
706 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700707 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700708 vector<Extent> old_extents =
709 (*graph)[it->first].out_edges[it->second].extents;
710 // Choose some scratch space
711 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700712 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700713 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
714 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700715 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700716 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700717 cuts.back().old_src = it->first;
718 cuts.back().old_dst = it->second;
Darin Petkov36a58222010-10-07 22:00:09 -0700719
Andrew de los Reyesef017552010-10-06 17:57:52 -0700720 EdgeProperties& cut_edge_properties =
721 (*graph)[it->first].out_edges.find(it->second)->second;
722
723 // This should never happen, as we should only be cutting edges between
724 // real file nodes, and write-before relationships are created from
725 // a real file node to a temp copy node:
726 CHECK(cut_edge_properties.write_extents.empty())
727 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700728
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700729 // make node depend on the copy operation
730 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700731 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700732
733 // Set src/dst extents and other proto variables for copy operation
734 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
735 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700736 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700737 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700738 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700739 graph->back().op.mutable_dst_extents());
740 graph->back().op.set_src_length(
741 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
742 graph->back().op.set_dst_length(graph->back().op.src_length());
743
744 // make the dest node read from the scratch space
745 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700746 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700747 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700748 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700749
750 // delete the old edge
751 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700752
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700753 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700754 EdgeProperties write_before_edge_properties;
755 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
756 (*graph)[it->second].out_edges.insert(
757 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700758 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700759 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700760 return true;
761}
762
763// Stores all Extents in 'extents' into 'out'.
764void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700765 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700766 google::protobuf::RepeatedPtrField<Extent>* out) {
767 for (vector<Extent>::const_iterator it = extents.begin();
768 it != extents.end(); ++it) {
769 Extent* new_extent = out->Add();
770 *new_extent = *it;
771 }
772}
773
774// Creates all the edges for the graph. Writers of a block point to
775// readers of the same block. This is because for an edge A->B, B
776// must complete before A executes.
777void DeltaDiffGenerator::CreateEdges(Graph* graph,
778 const vector<Block>& blocks) {
779 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
780 // Blocks with both a reader and writer get an edge
781 if (blocks[i].reader == Vertex::kInvalidIndex ||
782 blocks[i].writer == Vertex::kInvalidIndex)
783 continue;
784 // Don't have a node depend on itself
785 if (blocks[i].reader == blocks[i].writer)
786 continue;
787 // See if there's already an edge we can add onto
788 Vertex::EdgeMap::iterator edge_it =
789 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
790 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
791 // No existing edge. Create one
792 (*graph)[blocks[i].writer].out_edges.insert(
793 make_pair(blocks[i].reader, EdgeProperties()));
794 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700795 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700796 }
797 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
798 }
799}
800
Andrew de los Reyesef017552010-10-06 17:57:52 -0700801namespace {
802
803class SortCutsByTopoOrderLess {
804 public:
805 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
806 : table_(table) {}
807 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
808 return table_[a.old_dst] < table_[b.old_dst];
809 }
810 private:
811 vector<vector<Vertex::Index>::size_type>& table_;
812};
813
814} // namespace {}
815
816void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
817 vector<Vertex::Index>& op_indexes,
818 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
819 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
820 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
821 i != e; ++i) {
822 Vertex::Index node = op_indexes[i];
823 if (table.size() < (node + 1)) {
824 table.resize(node + 1);
825 }
826 table[node] = i;
827 }
828 reverse_op_indexes->swap(table);
829}
830
831void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
832 vector<CutEdgeVertexes>* cuts) {
833 // first, make a reverse lookup table.
834 vector<vector<Vertex::Index>::size_type> table;
835 GenerateReverseTopoOrderMap(op_indexes, &table);
836 SortCutsByTopoOrderLess less(table);
837 sort(cuts->begin(), cuts->end(), less);
838}
839
840void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
841 vector<Vertex::Index>* op_indexes) {
842 vector<Vertex::Index> ret;
843 vector<Vertex::Index> full_ops;
844 ret.reserve(op_indexes->size());
845 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
846 ++i) {
847 DeltaArchiveManifest_InstallOperation_Type type =
848 (*graph)[(*op_indexes)[i]].op.type();
849 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
850 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
851 full_ops.push_back((*op_indexes)[i]);
852 } else {
853 ret.push_back((*op_indexes)[i]);
854 }
855 }
856 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
857 << (full_ops.size() + ret.size()) << " total ops.";
858 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
859 op_indexes->swap(ret);
860}
861
862namespace {
863
864template<typename T>
865bool TempBlocksExistInExtents(const T& extents) {
866 for (int i = 0, e = extents.size(); i < e; ++i) {
867 Extent extent = graph_utils::GetElement(extents, i);
868 uint64_t start = extent.start_block();
869 uint64_t num = extent.num_blocks();
870 if (start == kSparseHole)
871 continue;
872 if (start >= kTempBlockStart ||
873 (start + num) >= kTempBlockStart) {
874 LOG(ERROR) << "temp block!";
875 LOG(ERROR) << "start: " << start << ", num: " << num;
876 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
877 LOG(ERROR) << "returning true";
878 return true;
879 }
880 // check for wrap-around, which would be a bug:
881 CHECK(start <= (start + num));
882 }
883 return false;
884}
885
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700886// Convertes the cuts, which must all have the same |old_dst| member,
887// to full. It does this by converting the |old_dst| to REPLACE or
888// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
889// all temp nodes invalid.
890bool ConvertCutsToFull(
891 Graph* graph,
892 const string& new_root,
893 int data_fd,
894 off_t* data_file_size,
895 vector<Vertex::Index>* op_indexes,
896 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
897 const vector<CutEdgeVertexes>& cuts) {
898 CHECK(!cuts.empty());
899 set<Vertex::Index> deleted_nodes;
900 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
901 e = cuts.end(); it != e; ++it) {
902 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
903 graph,
904 *it,
905 new_root,
906 data_fd,
907 data_file_size));
908 deleted_nodes.insert(it->new_vertex);
909 }
910 deleted_nodes.insert(cuts[0].old_dst);
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700911
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700912 vector<Vertex::Index> new_op_indexes;
913 new_op_indexes.reserve(op_indexes->size());
914 for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
915 e = op_indexes->end(); it != e; ++it) {
916 if (utils::SetContainsKey(deleted_nodes, *it))
917 continue;
918 new_op_indexes.push_back(*it);
919 }
920 new_op_indexes.push_back(cuts[0].old_dst);
921 op_indexes->swap(new_op_indexes);
922 DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
923 reverse_op_indexes);
924 return true;
925}
926
927// Tries to assign temp blocks for a collection of cuts, all of which share
928// the same old_dst member. If temp blocks can't be found, old_dst will be
929// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
930// which can happen even if blocks are converted to full. Returns false
931// on exceptional error cases.
932bool AssignBlockForAdjoiningCuts(
933 Graph* graph,
934 const string& new_root,
935 int data_fd,
936 off_t* data_file_size,
937 vector<Vertex::Index>* op_indexes,
938 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
939 const vector<CutEdgeVertexes>& cuts) {
940 CHECK(!cuts.empty());
941 const Vertex::Index old_dst = cuts[0].old_dst;
942 // Calculate # of blocks needed
943 uint64_t blocks_needed = 0;
944 map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
945 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
946 e = cuts.end(); it != e; ++it) {
947 uint64_t cut_blocks_needed = 0;
948 for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
949 je = it->tmp_extents.end(); jt != je; ++jt) {
950 cut_blocks_needed += jt->num_blocks();
951 }
952 blocks_needed += cut_blocks_needed;
953 cuts_blocks_needed[&*it] = cut_blocks_needed;
954 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -0700955
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700956 // Find enough blocks
957 ExtentRanges scratch_ranges;
958 // Each block that's supplying temp blocks and the corresponding blocks:
959 typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
960 SupplierVector block_suppliers;
961 uint64_t scratch_blocks_found = 0;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700962 for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
963 e = op_indexes->size(); i < e; ++i) {
964 Vertex::Index test_node = (*op_indexes)[i];
965 if (!(*graph)[test_node].valid)
966 continue;
967 // See if this node has sufficient blocks
968 ExtentRanges ranges;
969 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
970 ranges.SubtractExtent(ExtentForRange(
971 kTempBlockStart, kSparseHole - kTempBlockStart));
972 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
973 // For now, for simplicity, subtract out all blocks in read-before
974 // dependencies.
975 for (Vertex::EdgeMap::const_iterator edge_i =
976 (*graph)[test_node].out_edges.begin(),
977 edge_e = (*graph)[test_node].out_edges.end();
978 edge_i != edge_e; ++edge_i) {
979 ranges.SubtractExtents(edge_i->second.extents);
980 }
981 if (ranges.blocks() == 0)
982 continue;
983
984 if (ranges.blocks() + scratch_blocks_found > blocks_needed) {
985 // trim down ranges
986 vector<Extent> new_ranges = ranges.GetExtentsForBlockCount(
Andrew de los Reyes927179d2010-12-02 11:26:48 -0800987 blocks_needed - scratch_blocks_found);
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700988 ranges = ExtentRanges();
989 ranges.AddExtents(new_ranges);
990 }
991 scratch_ranges.AddRanges(ranges);
992 block_suppliers.push_back(make_pair(test_node, ranges));
993 scratch_blocks_found += ranges.blocks();
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -0700994 if (scratch_ranges.blocks() >= blocks_needed)
995 break;
996 }
997 if (scratch_ranges.blocks() < blocks_needed) {
998 LOG(INFO) << "Unable to find sufficient scratch";
999 TEST_AND_RETURN_FALSE(ConvertCutsToFull(graph,
1000 new_root,
1001 data_fd,
1002 data_file_size,
1003 op_indexes,
1004 reverse_op_indexes,
1005 cuts));
1006 return true;
1007 }
1008 // Use the scratch we found
1009 TEST_AND_RETURN_FALSE(scratch_ranges.blocks() == scratch_blocks_found);
1010
1011 // Make all the suppliers depend on this node
1012 for (SupplierVector::iterator it = block_suppliers.begin(),
1013 e = block_suppliers.end(); it != e; ++it) {
1014 graph_utils::AddReadBeforeDepExtents(
1015 &(*graph)[it->first],
1016 old_dst,
1017 it->second.GetExtentsForBlockCount(it->second.blocks()));
1018 }
Darin Petkovbc58a7b2010-11-03 11:52:53 -07001019
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001020 // Replace temp blocks in each cut
1021 for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
1022 e = cuts.end(); it != e; ++it) {
1023 vector<Extent> real_extents =
1024 scratch_ranges.GetExtentsForBlockCount(cuts_blocks_needed[&*it]);
1025 scratch_ranges.SubtractExtents(real_extents);
1026
1027 // Fix the old dest node w/ the real blocks
1028 DeltaDiffGenerator::SubstituteBlocks(&(*graph)[old_dst],
1029 it->tmp_extents,
1030 real_extents);
1031
1032 // Fix the new node w/ the real blocks. Since the new node is just a
1033 // copy operation, we can replace all the dest extents w/ the real
1034 // blocks.
1035 DeltaArchiveManifest_InstallOperation *op =
1036 &(*graph)[it->new_vertex].op;
1037 op->clear_dst_extents();
1038 DeltaDiffGenerator::StoreExtents(real_extents, op->mutable_dst_extents());
1039 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001040 return true;
1041}
1042
Andrew de los Reyesef017552010-10-06 17:57:52 -07001043} // namespace {}
1044
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001045// Returns true if |op| is a no-op operation that doesn't do any useful work
1046// (e.g., a move operation that copies blocks onto themselves).
1047bool DeltaDiffGenerator::IsNoopOperation(
1048 const DeltaArchiveManifest_InstallOperation& op) {
1049 return (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE &&
1050 ExpandExtents(op.src_extents()) == ExpandExtents(op.dst_extents()));
1051}
1052
Andrew de los Reyesef017552010-10-06 17:57:52 -07001053bool DeltaDiffGenerator::AssignTempBlocks(
1054 Graph* graph,
1055 const string& new_root,
1056 int data_fd,
1057 off_t* data_file_size,
1058 vector<Vertex::Index>* op_indexes,
1059 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001060 const vector<CutEdgeVertexes>& cuts) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001061 CHECK(!cuts.empty());
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001062
1063 // group of cuts w/ the same old_dst:
1064 vector<CutEdgeVertexes> cuts_group;
1065
Andrew de los Reyesef017552010-10-06 17:57:52 -07001066 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
1067 true ; --i) {
1068 LOG(INFO) << "Fixing temp blocks in cut " << i
1069 << ": old dst: " << cuts[i].old_dst << " new vertex: "
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001070 << cuts[i].new_vertex << " path: "
1071 << (*graph)[cuts[i].old_dst].file_name;
1072
1073 if (cuts_group.empty() || (cuts_group[0].old_dst == cuts[i].old_dst)) {
1074 cuts_group.push_back(cuts[i]);
1075 } else {
1076 CHECK(!cuts_group.empty());
1077 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1078 new_root,
1079 data_fd,
1080 data_file_size,
1081 op_indexes,
1082 reverse_op_indexes,
1083 cuts_group));
1084 cuts_group.clear();
1085 cuts_group.push_back(cuts[i]);
Andrew de los Reyesef017552010-10-06 17:57:52 -07001086 }
Darin Petkov36a58222010-10-07 22:00:09 -07001087
Andrew de los Reyesef017552010-10-06 17:57:52 -07001088 if (i == e) {
1089 // break out of for() loop
1090 break;
1091 }
1092 }
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001093 CHECK(!cuts_group.empty());
1094 TEST_AND_RETURN_FALSE(AssignBlockForAdjoiningCuts(graph,
1095 new_root,
1096 data_fd,
1097 data_file_size,
1098 op_indexes,
1099 reverse_op_indexes,
1100 cuts_group));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001101 return true;
1102}
1103
1104bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
1105 size_t idx = 0;
1106 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
1107 ++it, ++idx) {
1108 if (!it->valid)
1109 continue;
1110 const DeltaArchiveManifest_InstallOperation& op = it->op;
1111 if (TempBlocksExistInExtents(op.dst_extents()) ||
1112 TempBlocksExistInExtents(op.src_extents())) {
1113 LOG(INFO) << "bad extents in node " << idx;
1114 LOG(INFO) << "so yeah";
1115 return false;
1116 }
1117
1118 // Check out-edges:
1119 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
1120 je = it->out_edges.end(); jt != je; ++jt) {
1121 if (TempBlocksExistInExtents(jt->second.extents) ||
1122 TempBlocksExistInExtents(jt->second.write_extents)) {
1123 LOG(INFO) << "bad out edge in node " << idx;
1124 LOG(INFO) << "so yeah";
1125 return false;
1126 }
1127 }
1128 }
1129 return true;
1130}
1131
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001132bool DeltaDiffGenerator::ReorderDataBlobs(
1133 DeltaArchiveManifest* manifest,
1134 const std::string& data_blobs_path,
1135 const std::string& new_data_blobs_path) {
1136 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1137 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1138 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001139
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001140 DirectFileWriter writer;
1141 TEST_AND_RETURN_FALSE(
1142 writer.Open(new_data_blobs_path.c_str(),
1143 O_WRONLY | O_TRUNC | O_CREAT,
1144 0644) == 0);
1145 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001146 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001147
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001148 for (int i = 0; i < (manifest->install_operations_size() +
1149 manifest->kernel_install_operations_size()); i++) {
1150 DeltaArchiveManifest_InstallOperation* op = NULL;
1151 if (i < manifest->install_operations_size()) {
1152 op = manifest->mutable_install_operations(i);
1153 } else {
1154 op = manifest->mutable_kernel_install_operations(
1155 i - manifest->install_operations_size());
1156 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001157 if (!op->has_data_offset())
1158 continue;
1159 CHECK(op->has_data_length());
1160 vector<char> buf(op->data_length());
1161 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1162 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1163
1164 op->set_data_offset(out_file_size);
Don Garrette410e0f2011-11-10 15:39:01 -08001165 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001166 out_file_size += buf.size();
1167 }
1168 return true;
1169}
1170
Andrew de los Reyesef017552010-10-06 17:57:52 -07001171bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1172 const CutEdgeVertexes& cut,
1173 const string& new_root,
1174 int data_fd,
1175 off_t* data_file_size) {
1176 // Drop all incoming edges, keep all outgoing edges
Darin Petkov36a58222010-10-07 22:00:09 -07001177
Andrew de los Reyesef017552010-10-06 17:57:52 -07001178 // Keep all outgoing edges
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001179 if ((*graph)[cut.old_dst].op.type() !=
1180 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ &&
1181 (*graph)[cut.old_dst].op.type() !=
1182 DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
1183 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1184 graph_utils::DropWriteBeforeDeps(&out_edges);
Darin Petkov36a58222010-10-07 22:00:09 -07001185
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001186 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1187 cut.old_dst,
1188 NULL,
Andrew de los Reyes29da8aa2011-02-15 13:34:57 -08001189 kNonexistentPath,
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001190 new_root,
1191 (*graph)[cut.old_dst].file_name,
1192 data_fd,
1193 data_file_size));
Darin Petkov36a58222010-10-07 22:00:09 -07001194
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001195 (*graph)[cut.old_dst].out_edges = out_edges;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001196
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001197 // Right now we don't have doubly-linked edges, so we have to scan
1198 // the whole graph.
1199 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1200 }
Andrew de los Reyesef017552010-10-06 17:57:52 -07001201
1202 // Delete temp node
1203 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1204 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1205 (*graph)[cut.old_dst].out_edges.end());
1206 (*graph)[cut.new_vertex].valid = false;
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001207 LOG(INFO) << "marked node invalid: " << cut.new_vertex;
Andrew de los Reyesef017552010-10-06 17:57:52 -07001208 return true;
1209}
1210
1211bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1212 const string& new_root,
1213 int fd,
1214 off_t* data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001215 vector<Vertex::Index>* final_order,
1216 Vertex::Index scratch_vertex) {
Andrew de los Reyesef017552010-10-06 17:57:52 -07001217 CycleBreaker cycle_breaker;
1218 LOG(INFO) << "Finding cycles...";
1219 set<Edge> cut_edges;
1220 cycle_breaker.BreakCycles(*graph, &cut_edges);
1221 LOG(INFO) << "done finding cycles";
1222 CheckGraph(*graph);
1223
1224 // Calculate number of scratch blocks needed
1225
1226 LOG(INFO) << "Cutting cycles...";
1227 vector<CutEdgeVertexes> cuts;
1228 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1229 LOG(INFO) << "done cutting cycles";
1230 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1231 CheckGraph(*graph);
1232
1233 LOG(INFO) << "Creating initial topological order...";
1234 TopologicalSort(*graph, final_order);
1235 LOG(INFO) << "done with initial topo order";
1236 CheckGraph(*graph);
1237
1238 LOG(INFO) << "Moving full ops to the back";
1239 MoveFullOpsToBack(graph, final_order);
1240 LOG(INFO) << "done moving full ops to back";
1241
1242 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1243 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1244
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001245 SortCutsByTopoOrder(*final_order, &cuts);
1246
Andrew de los Reyesef017552010-10-06 17:57:52 -07001247 if (!cuts.empty())
1248 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1249 new_root,
1250 fd,
1251 data_file_size,
1252 final_order,
1253 &inverse_final_order,
1254 cuts));
1255 LOG(INFO) << "Making sure all temp blocks have been allocated";
Andrew de los Reyes4ba850d2010-10-25 12:12:40 -07001256
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001257 // Remove the scratch node, if any
1258 if (scratch_vertex != Vertex::kInvalidIndex) {
1259 final_order->erase(final_order->begin() +
1260 inverse_final_order[scratch_vertex]);
1261 (*graph)[scratch_vertex].valid = false;
1262 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1263 }
1264
Andrew de los Reyesef017552010-10-06 17:57:52 -07001265 graph_utils::DumpGraph(*graph);
1266 CHECK(NoTempBlocksRemain(*graph));
1267 LOG(INFO) << "done making sure all temp blocks are allocated";
1268 return true;
1269}
1270
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001271void DeltaDiffGenerator::CreateScratchNode(uint64_t start_block,
1272 uint64_t num_blocks,
1273 Vertex* vertex) {
1274 vertex->file_name = "<scratch>";
1275 vertex->op.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1276 vertex->op.set_data_offset(0);
1277 vertex->op.set_data_length(0);
1278 Extent* extent = vertex->op.add_dst_extents();
1279 extent->set_start_block(start_block);
1280 extent->set_num_blocks(num_blocks);
1281}
1282
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001283bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1284 const string& old_root,
1285 const string& old_image,
1286 const string& new_root,
1287 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001288 const string& old_kernel_part,
1289 const string& new_kernel_part,
1290 const string& output_path,
1291 const string& private_key_path) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001292 int old_image_block_count = 0, old_image_block_size = 0;
1293 int new_image_block_count = 0, new_image_block_size = 0;
1294 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(new_image,
1295 &new_image_block_count,
1296 &new_image_block_size));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001297 if (!old_image.empty()) {
Darin Petkov7ea32332010-10-13 10:46:11 -07001298 TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(old_image,
1299 &old_image_block_count,
1300 &old_image_block_size));
1301 TEST_AND_RETURN_FALSE(old_image_block_size == new_image_block_size);
1302 LOG_IF(WARNING, old_image_block_count != new_image_block_count)
1303 << "Old and new images have different block counts.";
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001304 }
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001305 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001306 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1307
Darin Petkov7ea32332010-10-13 10:46:11 -07001308 vector<Block> blocks(max(old_image_block_count, new_image_block_count));
1309 LOG(INFO) << "Invalid block index: " << Vertex::kInvalidIndex;
1310 LOG(INFO) << "Block count: " << blocks.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001311 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1312 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1313 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1314 }
1315 Graph graph;
1316 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001317
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001318 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1319 string temp_file_path;
Darin Petkov7438a5c2011-08-29 11:56:44 -07001320 scoped_ptr<ScopedPathUnlinker> temp_file_unlinker;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001321 off_t data_file_size = 0;
1322
1323 LOG(INFO) << "Reading files...";
1324
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001325 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1326
Andrew de los Reyesef017552010-10-06 17:57:52 -07001327 vector<Vertex::Index> final_order;
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001328 Vertex::Index scratch_vertex = Vertex::kInvalidIndex;
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001329 {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001330 int fd;
1331 TEST_AND_RETURN_FALSE(
1332 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001333 temp_file_unlinker.reset(new ScopedPathUnlinker(temp_file_path));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001334 TEST_AND_RETURN_FALSE(fd >= 0);
1335 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001336 if (!old_image.empty()) {
1337 // Delta update
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001338
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001339 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1340 &blocks,
1341 old_root,
1342 new_root,
1343 fd,
1344 &data_file_size));
1345 LOG(INFO) << "done reading normal files";
1346 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001347
Thieu Le5c7d9752010-12-15 16:09:28 -08001348 LOG(INFO) << "Starting metadata processing";
1349 TEST_AND_RETURN_FALSE(Metadata::DeltaReadMetadata(&graph,
1350 &blocks,
1351 old_image,
1352 new_image,
1353 fd,
1354 &data_file_size));
1355 LOG(INFO) << "Done metadata processing";
1356 CheckGraph(graph);
1357
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001358 graph.resize(graph.size() + 1);
1359 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1360 fd,
1361 &data_file_size,
1362 new_image,
1363 &graph.back()));
1364
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001365 // Final scratch block (if there's space)
1366 if (blocks.size() < (kRootFSPartitionSize / kBlockSize)) {
1367 scratch_vertex = graph.size();
1368 graph.resize(graph.size() + 1);
1369 CreateScratchNode(blocks.size(),
1370 (kRootFSPartitionSize / kBlockSize) - blocks.size(),
1371 &graph.back());
1372 }
1373
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001374 // Read kernel partition
1375 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1376 new_kernel_part,
1377 &kernel_ops,
1378 fd,
1379 &data_file_size));
1380
1381 LOG(INFO) << "done reading kernel";
1382 CheckGraph(graph);
1383
1384 LOG(INFO) << "Creating edges...";
1385 CreateEdges(&graph, blocks);
1386 LOG(INFO) << "Done creating edges";
1387 CheckGraph(graph);
1388
1389 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1390 new_root,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001391 fd,
1392 &data_file_size,
Andrew de los Reyes927179d2010-12-02 11:26:48 -08001393 &final_order,
1394 scratch_vertex));
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001395 } else {
1396 // Full update
Darin Petkov7ea32332010-10-13 10:46:11 -07001397 off_t new_image_size =
1398 static_cast<off_t>(new_image_block_count) * new_image_block_size;
Darin Petkov7a22d792010-11-08 14:10:00 -08001399 TEST_AND_RETURN_FALSE(FullUpdateGenerator::Run(&graph,
1400 new_kernel_part,
1401 new_image,
1402 new_image_size,
1403 fd,
1404 &data_file_size,
1405 kFullUpdateChunkSize,
1406 kBlockSize,
1407 &kernel_ops,
1408 &final_order));
Andrew de los Reyesf88144f2010-10-11 10:32:59 -07001409 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001410 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001411
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001412 // Convert to protobuf Manifest object
1413 DeltaArchiveManifest manifest;
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001414 OperationNameMap op_name_map;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001415 CheckGraph(graph);
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001416 InstallOperationsToManifest(graph,
1417 final_order,
1418 kernel_ops,
1419 &manifest,
1420 &op_name_map);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001421 CheckGraph(graph);
1422 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001423
1424 // Reorder the data blobs with the newly ordered manifest
1425 string ordered_blobs_path;
1426 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1427 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1428 &ordered_blobs_path,
Andrew de los Reyese05fc282011-06-02 09:50:08 -07001429 NULL));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001430 ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001431 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1432 temp_file_path,
1433 ordered_blobs_path));
Darin Petkov7438a5c2011-08-29 11:56:44 -07001434 temp_file_unlinker.reset();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001435
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001436 // Check that install op blobs are in order.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001437 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001438 {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001439 for (int i = 0; i < (manifest.install_operations_size() +
1440 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001441 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001442 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001443 manifest.mutable_install_operations(i) :
1444 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001445 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001446 if (op->has_data_offset()) {
1447 if (op->data_offset() != next_blob_offset) {
1448 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001449 << next_blob_offset;
1450 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001451 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001452 }
1453 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001454 }
1455
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001456 // Signatures appear at the end of the blobs. Note the offset in the
1457 // manifest
1458 if (!private_key_path.empty()) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001459 uint64_t signature_blob_length = 0;
1460 TEST_AND_RETURN_FALSE(
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001461 PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001462 &signature_blob_length));
Darin Petkov9574f7e2011-01-13 10:48:12 -08001463 AddSignatureOp(next_blob_offset, signature_blob_length, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001464 }
1465
Darin Petkov36a58222010-10-07 22:00:09 -07001466 TEST_AND_RETURN_FALSE(InitializePartitionInfos(old_kernel_part,
1467 new_kernel_part,
1468 old_image,
1469 new_image,
1470 &manifest));
1471
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001472 // Serialize protobuf
1473 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001474
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001475 CheckGraph(graph);
1476 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1477 CheckGraph(graph);
1478
1479 LOG(INFO) << "Writing final delta file header...";
1480 DirectFileWriter writer;
1481 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1482 O_WRONLY | O_CREAT | O_TRUNC,
1483 0644) == 0);
1484 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001485
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001486 // Write header
Don Garrette410e0f2011-11-10 15:39:01 -08001487 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001488
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001489 // Write version number
1490 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001491
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001492 // Write protobuf length
1493 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1494 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001495
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001496 // Write protobuf
1497 LOG(INFO) << "Writing final delta file protobuf... "
1498 << serialized_manifest.size();
1499 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
Don Garrette410e0f2011-11-10 15:39:01 -08001500 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001501
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001502 // Append the data blobs
1503 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001504 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001505 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1506 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1507 for (;;) {
1508 char buf[kBlockSize];
1509 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1510 if (0 == rc) {
1511 // EOF
1512 break;
1513 }
1514 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
Don Garrette410e0f2011-11-10 15:39:01 -08001515 TEST_AND_RETURN_FALSE(writer.Write(buf, rc));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001516 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001517
1518 // Write signature blob.
1519 if (!private_key_path.empty()) {
1520 LOG(INFO) << "Signing the update...";
1521 vector<char> signature_blob;
Andrew de los Reyesc24e3f32011-08-30 15:45:20 -07001522 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
1523 output_path,
1524 vector<string>(1, private_key_path),
1525 &signature_blob));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001526 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
Don Garrette410e0f2011-11-10 15:39:01 -08001527 signature_blob.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001528 }
1529
Darin Petkov95cf01f2010-10-12 14:59:13 -07001530 int64_t manifest_metadata_size =
1531 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
Darin Petkov9fa7ec52010-10-18 11:45:23 -07001532 ReportPayloadUsage(manifest, manifest_metadata_size, op_name_map);
Darin Petkov880335c2010-10-01 15:52:53 -07001533
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001534 LOG(INFO) << "All done. Successfully created delta file.";
1535 return true;
1536}
1537
Thieu Le5c7d9752010-12-15 16:09:28 -08001538// Runs the bsdiff tool on two files and returns the resulting delta in
1539// 'out'. Returns true on success.
1540bool DeltaDiffGenerator::BsdiffFiles(const string& old_file,
1541 const string& new_file,
1542 vector<char>* out) {
1543 const string kPatchFile = "/tmp/delta.patchXXXXXX";
1544 string patch_file_path;
1545
1546 TEST_AND_RETURN_FALSE(
1547 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
1548
1549 vector<string> cmd;
1550 cmd.push_back(kBsdiffPath);
1551 cmd.push_back(old_file);
1552 cmd.push_back(new_file);
1553 cmd.push_back(patch_file_path);
1554
1555 int rc = 1;
1556 vector<char> patch_file;
Darin Petkov85d02b72011-05-17 13:25:51 -07001557 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc, NULL));
Thieu Le5c7d9752010-12-15 16:09:28 -08001558 TEST_AND_RETURN_FALSE(rc == 0);
1559 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
1560 unlink(patch_file_path.c_str());
1561 return true;
1562}
1563
1564// The |blocks| vector contains a reader and writer for each block on the
1565// filesystem that's being in-place updated. We populate the reader/writer
1566// fields of |blocks| by calling this function.
1567// For each block in |operation| that is read or written, find that block
1568// in |blocks| and set the reader/writer field to the vertex passed.
1569// |graph| is not strictly necessary, but useful for printing out
1570// error messages.
1571bool DeltaDiffGenerator::AddInstallOpToBlocksVector(
1572 const DeltaArchiveManifest_InstallOperation& operation,
1573 const Graph& graph,
1574 Vertex::Index vertex,
1575 vector<Block>* blocks) {
1576 // See if this is already present.
1577 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
1578
1579 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
1580 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
1581 const int extents_size =
1582 (field == READER) ? operation.src_extents_size() :
1583 operation.dst_extents_size();
1584 const char* past_participle = (field == READER) ? "read" : "written";
1585 const google::protobuf::RepeatedPtrField<Extent>& extents =
1586 (field == READER) ? operation.src_extents() : operation.dst_extents();
1587 Vertex::Index Block::*access_type =
1588 (field == READER) ? &Block::reader : &Block::writer;
1589
1590 for (int i = 0; i < extents_size; i++) {
1591 const Extent& extent = extents.Get(i);
1592 if (extent.start_block() == kSparseHole) {
1593 // Hole in sparse file. skip
1594 continue;
1595 }
1596 for (uint64_t block = extent.start_block();
1597 block < (extent.start_block() + extent.num_blocks()); block++) {
1598 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
1599 LOG(FATAL) << "Block " << block << " is already "
1600 << past_participle << " by "
1601 << (*blocks)[block].*access_type << "("
1602 << graph[(*blocks)[block].*access_type].file_name
1603 << ") and also " << vertex << "("
1604 << graph[vertex].file_name << ")";
1605 }
1606 (*blocks)[block].*access_type = vertex;
1607 }
1608 }
1609 }
1610 return true;
1611}
1612
Darin Petkov9574f7e2011-01-13 10:48:12 -08001613void DeltaDiffGenerator::AddSignatureOp(uint64_t signature_blob_offset,
1614 uint64_t signature_blob_length,
1615 DeltaArchiveManifest* manifest) {
1616 LOG(INFO) << "Making room for signature in file";
1617 manifest->set_signatures_offset(signature_blob_offset);
1618 LOG(INFO) << "set? " << manifest->has_signatures_offset();
1619 // Add a dummy op at the end to appease older clients
1620 DeltaArchiveManifest_InstallOperation* dummy_op =
1621 manifest->add_kernel_install_operations();
1622 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1623 dummy_op->set_data_offset(signature_blob_offset);
1624 manifest->set_signatures_offset(signature_blob_offset);
1625 dummy_op->set_data_length(signature_blob_length);
1626 manifest->set_signatures_size(signature_blob_length);
1627 Extent* dummy_extent = dummy_op->add_dst_extents();
1628 // Tell the dummy op to write this data to a big sparse hole
1629 dummy_extent->set_start_block(kSparseHole);
1630 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1631 kBlockSize);
1632}
1633
Andrew de los Reyes50f36492010-11-01 13:57:12 -07001634const char* const kBsdiffPath = "bsdiff";
1635const char* const kBspatchPath = "bspatch";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001636const char* const kDeltaMagic = "CrAU";
1637
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001638}; // namespace chromeos_update_engine