blob: 6b880cd2d080503c2728c0c17f56fce804e96966 [file] [log] [blame]
adlr@google.com3defe6a2009-12-04 20:57:17 +00001// Copyright (c) 2009 The Chromium Authors. All rights reserved.
2// 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"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07006#include <sys/stat.h>
7#include <sys/types.h>
8#include <errno.h>
9#include <fcntl.h>
10#include <algorithm>
11#include <set>
12#include <string>
13#include <utility>
14#include <vector>
15#include <bzlib.h>
16#include "chromeos/obsolete_logging.h"
17#include "update_engine/bzip.h"
18#include "update_engine/cycle_breaker.h"
19#include "update_engine/extent_mapper.h"
20#include "update_engine/file_writer.h"
21#include "update_engine/filesystem_iterator.h"
22#include "update_engine/graph_types.h"
23#include "update_engine/graph_utils.h"
24#include "update_engine/subprocess.h"
25#include "update_engine/topological_sort.h"
26#include "update_engine/update_metadata.pb.h"
27#include "update_engine/utils.h"
28
29using std::make_pair;
30using std::min;
31using std::set;
32using std::string;
33using std::vector;
34
35namespace chromeos_update_engine {
36
37typedef DeltaDiffGenerator::Block Block;
38
39namespace {
40const size_t kBlockSize = 4096;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070041const uint64_t kVersionNumber = 1;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070042
43// Stores all Extents for a file into 'out'. Returns true on success.
44bool GatherExtents(const string& path,
45 google::protobuf::RepeatedPtrField<Extent>* out) {
46 vector<Extent> extents;
47 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
48 DeltaDiffGenerator::StoreExtents(extents, out);
49 return true;
50}
51
52// Runs the bsdiff tool on two files and returns the resulting delta in
53// 'out'. Returns true on success.
54bool BsdiffFiles(const string& old_file,
55 const string& new_file,
56 vector<char>* out) {
57 const string kPatchFile = "/tmp/delta.patchXXXXXX";
58 string patch_file_path;
59
60 TEST_AND_RETURN_FALSE(
61 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
62
63 vector<string> cmd;
64 cmd.push_back(kBsdiffPath);
65 cmd.push_back(old_file);
66 cmd.push_back(new_file);
67 cmd.push_back(patch_file_path);
68
69 int rc = 1;
70 vector<char> patch_file;
71 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
72 TEST_AND_RETURN_FALSE(rc == 0);
73 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
74 unlink(patch_file_path.c_str());
75 return true;
76}
77
78// The blocks vector contains a reader and writer for each block on the
79// filesystem that's being in-place updated. We populate the reader/writer
80// fields of blocks by calling this function.
81// For each block in 'operation' that is read or written, find that block
82// in 'blocks' and set the reader/writer field to the vertex passed.
83// 'graph' is not strictly necessary, but useful for printing out
84// error messages.
85bool AddInstallOpToBlocksVector(
86 const DeltaArchiveManifest_InstallOperation& operation,
87 vector<Block>* blocks,
88 const Graph& graph,
89 Vertex::Index vertex) {
90 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
91 << graph[vertex].file_name;
92 // See if this is already present.
93 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
94
95 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
96 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
97 const int extents_size =
98 (field == READER) ? operation.src_extents_size() :
99 operation.dst_extents_size();
100 const char* past_participle = (field == READER) ? "read" : "written";
101 const google::protobuf::RepeatedPtrField<Extent>& extents =
102 (field == READER) ? operation.src_extents() : operation.dst_extents();
103 Vertex::Index Block::*access_type =
104 (field == READER) ? &Block::reader : &Block::writer;
105
106 for (int i = 0; i < extents_size; i++) {
107 const Extent& extent = extents.Get(i);
108 if (extent.start_block() == kSparseHole) {
109 // Hole in sparse file. skip
110 continue;
111 }
112 for (uint64_t block = extent.start_block();
113 block < (extent.start_block() + extent.num_blocks()); block++) {
114 LOG(INFO) << "ext: " << i << " block: " << block;
115 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
116 LOG(FATAL) << "Block " << block << " is already "
117 << past_participle << " by "
118 << (*blocks)[block].*access_type << "("
119 << graph[(*blocks)[block].*access_type].file_name
120 << ") and also " << vertex << "("
121 << graph[vertex].file_name << ")";
122 }
123 (*blocks)[block].*access_type = vertex;
124 }
125 }
126 }
127 return true;
128}
129
130// For a given regular file which must exist at new_root + path, and may
131// exist at old_root + path, creates a new InstallOperation and adds it to
132// the graph. Also, populates the 'blocks' array as necessary.
133// Also, writes the data necessary to send the file down to the client
134// into data_fd, which has length *data_file_size. *data_file_size is
135// updated appropriately.
136// Returns true on success.
137bool DeltaReadFile(Graph* graph,
138 vector<Block>* blocks,
139 const string& old_root,
140 const string& new_root,
141 const string& path, // within new_root
142 int data_fd,
143 off_t* data_file_size) {
144 vector<char> data;
145 DeltaArchiveManifest_InstallOperation operation;
146
147 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
148 new_root + path,
149 &data,
150 &operation));
151
152 // Write the data
153 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
154 operation.set_data_offset(*data_file_size);
155 operation.set_data_length(data.size());
156 }
157
158 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
159 *data_file_size += data.size();
160
161 // Now, insert into graph and blocks vector
162 graph->resize(graph->size() + 1);
163 graph->back().op = operation;
164 CHECK(graph->back().op.has_type());
165 graph->back().file_name = path;
166
167 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector(graph->back().op,
168 blocks,
169 *graph,
170 graph->size() - 1));
171 return true;
172}
173
174// For each regular file within new_root, creates a node in the graph,
175// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
176// and writes any necessary data to the end of data_fd.
177bool DeltaReadFiles(Graph* graph,
178 vector<Block>* blocks,
179 const string& old_root,
180 const string& new_root,
181 int data_fd,
182 off_t* data_file_size) {
183 set<ino_t> visited_inodes;
184 for (FilesystemIterator fs_iter(new_root,
185 utils::SetWithValue<string>("/lost+found"));
186 !fs_iter.IsEnd(); fs_iter.Increment()) {
187 if (!S_ISREG(fs_iter.GetStat().st_mode))
188 continue;
189
190 // Make sure we visit each inode only once.
191 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
192 continue;
193 visited_inodes.insert(fs_iter.GetStat().st_ino);
194 if (fs_iter.GetStat().st_size == 0)
195 continue;
196
197 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
198
199 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
200 blocks,
201 old_root,
202 new_root,
203 fs_iter.GetPartialPath(),
204 data_fd,
205 data_file_size));
206 }
207 return true;
208}
209
210// Attempts to find block_count blocks to use as scratch space.
211// Returns true on success.
212// Right now we return exactly as many blocks as are required.
213// TODO(adlr): consider returning all scratch blocks,
214// even if there are extras, to make it easier for a scratch allocator
215// to find contiguous regions for specific scratch writes.
216bool FindScratchSpace(const vector<Block>& blocks,
217 vector<Block>::size_type block_count,
218 vector<Extent>* out) {
219 // Scan blocks for blocks that are neither read nor written.
220 // If we don't find enough of those, return false.
221 // TODO(adlr): return blocks that are written by
222 // operations that don't have incoming edges (and thus, can be
223 // deferred until all old blocks are read by other operations).
224 vector<Extent> ret;
225 vector<Block>::size_type blocks_found = 0;
226 for (vector<Block>::size_type i = 0;
227 i < blocks.size() && blocks_found < block_count; i++) {
228 if (blocks[i].reader == Vertex::kInvalidIndex &&
229 blocks[i].writer == Vertex::kInvalidIndex) {
230 graph_utils::AppendBlockToExtents(&ret, i);
231 blocks_found++;
232 }
233 }
234 if (blocks_found == block_count) {
235 LOG(INFO) << "returning " << blocks_found << " scratch blocks";
236 out->swap(ret);
237 return true;
238 }
239 return false;
240}
241
242// This class takes a collection of Extents and allows the client to
243// allocate space from these extents. The client must not request more
244// space then exists in the source extents. Space is allocated from the
245// beginning of the source extents on; no consideration is paid to
246// fragmentation.
247class LinearExtentAllocator {
248 public:
249 explicit LinearExtentAllocator(const vector<Extent>& extents)
250 : extents_(extents),
251 extent_index_(0),
252 extent_blocks_allocated_(0) {}
253 vector<Extent> Allocate(const uint64_t block_count) {
254 vector<Extent> ret;
255 for (uint64_t blocks = 0; blocks < block_count; blocks++) {
256 CHECK_LT(extent_index_, extents_.size());
257 CHECK_LT(extent_blocks_allocated_, extents_[extent_index_].num_blocks());
258 graph_utils::AppendBlockToExtents(
259 &ret,
260 extents_[extent_index_].start_block() + extent_blocks_allocated_);
261 extent_blocks_allocated_++;
262 if (extent_blocks_allocated_ >= extents_[extent_index_].num_blocks()) {
263 extent_blocks_allocated_ = 0;
264 extent_index_++;
265 }
266 }
267 return ret;
268 }
269 private:
270 const vector<Extent> extents_;
271 vector<Extent>::size_type extent_index_; // current Extent
272 // number of blocks allocated from the current extent
273 uint64_t extent_blocks_allocated_;
274};
275
276// Reads blocks from image_path that are not yet marked as being written
277// in the blocks array. These blocks that remain are non-file-data blocks.
278// In the future we might consider intelligent diffing between this data
279// and data in the previous image, but for now we just bzip2 compress it
280// and include it in the update.
281// Creates a new node in the graph to write these blocks and writes the
282// appropriate blob to blobs_fd. Reads and updates blobs_length;
283bool ReadUnwrittenBlocks(const vector<Block>& blocks,
284 int blobs_fd,
285 off_t* blobs_length,
286 const string& image_path,
287 DeltaArchiveManifest_InstallOperation* out_op) {
288 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
289 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
290 ScopedFdCloser image_fd_closer(&image_fd);
291
292 string temp_file_path;
293 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
294 &temp_file_path,
295 NULL));
296
297 FILE* file = fopen(temp_file_path.c_str(), "w");
298 TEST_AND_RETURN_FALSE(file);
299 int err = BZ_OK;
300
301 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
302 file,
303 9, // max compression
304 0, // verbosity
305 0); // default work factor
306 TEST_AND_RETURN_FALSE(err == BZ_OK);
307
308 vector<Extent> extents;
309 vector<Block>::size_type block_count = 0;
310
311 LOG(INFO) << "Appending left over blocks to extents";
312 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
313 if (blocks[i].writer != Vertex::kInvalidIndex)
314 continue;
315 graph_utils::AppendBlockToExtents(&extents, i);
316 block_count++;
317 }
318
319 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
320 // so we arbitrarily set it to 1024 * kBlockSize.
321 vector<char> buf(1024 * kBlockSize);
322
323 LOG(INFO) << "Reading left over blocks";
324 vector<Block>::size_type blocks_copied_count = 0;
325
326 // For each extent in extents, write the data into BZ2_bzWrite which
327 // sends it to an output file.
328 // We use the temporary buffer 'buf' to hold the data, which may be
329 // smaller than the extent, so in that case we have to loop to get
330 // the extent's data (that's the inner while loop).
331 for (vector<Extent>::const_iterator it = extents.begin();
332 it != extents.end(); ++it) {
333 vector<Block>::size_type blocks_read = 0;
334 while (blocks_read < it->num_blocks()) {
335 const int copy_block_cnt =
336 min(buf.size() / kBlockSize,
337 static_cast<vector<char>::size_type>(
338 it->num_blocks() - blocks_read));
339 ssize_t rc = pread(image_fd,
340 &buf[0],
341 copy_block_cnt * kBlockSize,
342 (it->start_block() + blocks_read) * kBlockSize);
343 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
344 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
345 copy_block_cnt * kBlockSize);
346 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
347 TEST_AND_RETURN_FALSE(err == BZ_OK);
348 blocks_read += copy_block_cnt;
349 blocks_copied_count += copy_block_cnt;
350 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
351 }
352 }
353 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
354 TEST_AND_RETURN_FALSE(err == BZ_OK);
355 bz_file = NULL;
356 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
357 file = NULL;
358
359 vector<char> compressed_data;
360 LOG(INFO) << "Reading compressed data off disk";
361 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
362 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
363
364 // Add node to graph to write these blocks
365 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
366 out_op->set_data_offset(*blobs_length);
367 out_op->set_data_length(compressed_data.size());
368 *blobs_length += compressed_data.size();
369 out_op->set_dst_length(kBlockSize * block_count);
370 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
371
372 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
373 &compressed_data[0],
374 compressed_data.size()));
375 LOG(INFO) << "done with extra blocks";
376 return true;
377}
378
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700379// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700380// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700381bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
382 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700383 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
384 sizeof(value_be));
385 return true;
386}
387
388// Adds each operation from the graph to the manifest in the order
389// specified by 'order'.
390void InstallOperationsToManifest(
391 const Graph& graph,
392 const vector<Vertex::Index>& order,
393 DeltaArchiveManifest* out_manifest) {
394 for (vector<Vertex::Index>::const_iterator it = order.begin();
395 it != order.end(); ++it) {
396 DeltaArchiveManifest_InstallOperation* op =
397 out_manifest->add_install_operations();
398 *op = graph[*it].op;
399 }
400}
401
402void CheckGraph(const Graph& graph) {
403 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
404 CHECK(it->op.has_type());
405 }
406}
407
408} // namespace {}
409
410bool DeltaDiffGenerator::ReadFileToDiff(
411 const string& old_filename,
412 const string& new_filename,
413 vector<char>* out_data,
414 DeltaArchiveManifest_InstallOperation* out_op) {
415 // Read new data in
416 vector<char> new_data;
417 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
418
419 TEST_AND_RETURN_FALSE(!new_data.empty());
420
421 vector<char> new_data_bz;
422 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
423 CHECK(!new_data_bz.empty());
424
425 vector<char> data; // Data blob that will be written to delta file.
426
427 DeltaArchiveManifest_InstallOperation operation;
428 size_t current_best_size = 0;
429 if (new_data.size() <= new_data_bz.size()) {
430 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
431 current_best_size = new_data.size();
432 data = new_data;
433 } else {
434 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
435 current_best_size = new_data_bz.size();
436 data = new_data_bz;
437 }
438
439 // Do we have an original file to consider?
440 struct stat old_stbuf;
441 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
442 // If stat-ing the old file fails, it should be because it doesn't exist.
443 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
444 } else {
445 // Read old data
446 vector<char> old_data;
447 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
448 if (old_data == new_data) {
449 // No change in data.
450 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
451 current_best_size = 0;
452 data.clear();
453 } else {
454 // Try bsdiff of old to new data
455 vector<char> bsdiff_delta;
456 TEST_AND_RETURN_FALSE(
457 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
458 CHECK_GT(bsdiff_delta.size(), 0);
459 if (bsdiff_delta.size() < current_best_size) {
460 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
461 current_best_size = bsdiff_delta.size();
462
463 data = bsdiff_delta;
464 }
465 }
466 }
467
468 // Set parameters of the operations
469 CHECK_EQ(data.size(), current_best_size);
470
471 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
472 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
473 TEST_AND_RETURN_FALSE(
474 GatherExtents(old_filename, operation.mutable_src_extents()));
475 operation.set_src_length(old_stbuf.st_size);
476 }
477
478 TEST_AND_RETURN_FALSE(
479 GatherExtents(new_filename, operation.mutable_dst_extents()));
480 operation.set_dst_length(new_data.size());
481
482 out_data->swap(data);
483 *out_op = operation;
484
485 return true;
486}
487
488void DeltaDiffGenerator::SubstituteBlocks(
489 DeltaArchiveManifest_InstallOperation* op,
490 const vector<Extent>& remove_extents,
491 const vector<Extent>& replace_extents) {
492 // First, expand out the blocks that op reads from
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700493 vector<uint64_t> read_blocks;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700494 for (int i = 0; i < op->src_extents_size(); i++) {
495 const Extent& extent = op->src_extents(i);
496 if (extent.start_block() == kSparseHole) {
497 read_blocks.resize(read_blocks.size() + extent.num_blocks(), kSparseHole);
498 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700499 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700500 block < (extent.start_block() + extent.num_blocks()); block++) {
501 read_blocks.push_back(block);
502 }
503 }
504 }
505 {
506 // Expand remove_extents and replace_extents
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700507 vector<uint64_t> remove_extents_expanded;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700508 for (vector<Extent>::const_iterator it = remove_extents.begin();
509 it != remove_extents.end(); ++it) {
510 const Extent& extent = *it;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700511 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700512 block < (extent.start_block() + extent.num_blocks()); block++) {
513 remove_extents_expanded.push_back(block);
514 }
515 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700516 vector<uint64_t> replace_extents_expanded;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700517 for (vector<Extent>::const_iterator it = replace_extents.begin();
518 it != replace_extents.end(); ++it) {
519 const Extent& extent = *it;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700520 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700521 block < (extent.start_block() + extent.num_blocks()); block++) {
522 replace_extents_expanded.push_back(block);
523 }
524 }
525 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700526 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700527 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700528 vector<uint64_t>::size_type index = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700529 CHECK(utils::VectorIndexOf(read_blocks,
530 remove_extents_expanded[i],
531 &index));
532 CHECK(read_blocks[index] == remove_extents_expanded[i]);
533 read_blocks[index] = replace_extents_expanded[i];
534 }
535 }
536 // Convert read_blocks back to extents
537 op->clear_src_extents();
538 vector<Extent> new_extents;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700539 for (vector<uint64_t>::const_iterator it = read_blocks.begin();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700540 it != read_blocks.end(); ++it) {
541 graph_utils::AppendBlockToExtents(&new_extents, *it);
542 }
543 DeltaDiffGenerator::StoreExtents(new_extents, op->mutable_src_extents());
544}
545
546bool DeltaDiffGenerator::CutEdges(Graph* graph,
547 const vector<Block>& blocks,
548 const set<Edge>& edges) {
549 // First, find enough scratch space for the edges we'll be cutting.
550 vector<Block>::size_type blocks_required = 0;
551 for (set<Edge>::const_iterator it = edges.begin(); it != edges.end(); ++it) {
552 blocks_required += graph_utils::EdgeWeight(*graph, *it);
553 }
554 vector<Extent> scratch_extents;
555 LOG(INFO) << "requesting " << blocks_required << " blocks of scratch";
556 TEST_AND_RETURN_FALSE(
557 FindScratchSpace(blocks, blocks_required, &scratch_extents));
558 LinearExtentAllocator scratch_allocator(scratch_extents);
559
560 uint64_t scratch_blocks_used = 0;
561 for (set<Edge>::const_iterator it = edges.begin();
562 it != edges.end(); ++it) {
563 vector<Extent> old_extents =
564 (*graph)[it->first].out_edges[it->second].extents;
565 // Choose some scratch space
566 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
567 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
568 << " scratch blocks ("
569 << scratch_blocks_used << ")";
570 vector<Extent> scratch =
571 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
572 // create vertex to copy original->scratch
573 graph->resize(graph->size() + 1);
574
575 // make node depend on the copy operation
576 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
577 EdgeProperties()));
578
579 // Set src/dst extents and other proto variables for copy operation
580 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
581 DeltaDiffGenerator::StoreExtents(
582 (*graph)[it->first].out_edges[it->second].extents,
583 graph->back().op.mutable_src_extents());
584 DeltaDiffGenerator::StoreExtents(scratch,
585 graph->back().op.mutable_dst_extents());
586 graph->back().op.set_src_length(
587 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
588 graph->back().op.set_dst_length(graph->back().op.src_length());
589
590 // make the dest node read from the scratch space
591 DeltaDiffGenerator::SubstituteBlocks(
592 &((*graph)[it->second].op),
593 (*graph)[it->first].out_edges[it->second].extents,
594 scratch);
595
596 // delete the old edge
597 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
598 }
599 return true;
600}
601
602// Stores all Extents in 'extents' into 'out'.
603void DeltaDiffGenerator::StoreExtents(
604 vector<Extent>& extents,
605 google::protobuf::RepeatedPtrField<Extent>* out) {
606 for (vector<Extent>::const_iterator it = extents.begin();
607 it != extents.end(); ++it) {
608 Extent* new_extent = out->Add();
609 *new_extent = *it;
610 }
611}
612
613// Creates all the edges for the graph. Writers of a block point to
614// readers of the same block. This is because for an edge A->B, B
615// must complete before A executes.
616void DeltaDiffGenerator::CreateEdges(Graph* graph,
617 const vector<Block>& blocks) {
618 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
619 // Blocks with both a reader and writer get an edge
620 if (blocks[i].reader == Vertex::kInvalidIndex ||
621 blocks[i].writer == Vertex::kInvalidIndex)
622 continue;
623 // Don't have a node depend on itself
624 if (blocks[i].reader == blocks[i].writer)
625 continue;
626 // See if there's already an edge we can add onto
627 Vertex::EdgeMap::iterator edge_it =
628 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
629 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
630 // No existing edge. Create one
631 (*graph)[blocks[i].writer].out_edges.insert(
632 make_pair(blocks[i].reader, EdgeProperties()));
633 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
634 CHECK_NE(edge_it, (*graph)[blocks[i].writer].out_edges.end());
635 }
636 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
637 }
638}
639
640bool DeltaDiffGenerator::ReorderDataBlobs(
641 DeltaArchiveManifest* manifest,
642 const std::string& data_blobs_path,
643 const std::string& new_data_blobs_path) {
644 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
645 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
646 ScopedFdCloser in_fd_closer(&in_fd);
647
648 DirectFileWriter writer;
649 TEST_AND_RETURN_FALSE(
650 writer.Open(new_data_blobs_path.c_str(),
651 O_WRONLY | O_TRUNC | O_CREAT,
652 0644) == 0);
653 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 uint64_t out_file_size = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700655
656 for (int i = 0; i < manifest->install_operations_size(); i++) {
657 DeltaArchiveManifest_InstallOperation* op =
658 manifest->mutable_install_operations(i);
659 if (!op->has_data_offset())
660 continue;
661 CHECK(op->has_data_length());
662 vector<char> buf(op->data_length());
663 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
664 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
665
666 op->set_data_offset(out_file_size);
667 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
668 static_cast<ssize_t>(buf.size()));
669 out_file_size += buf.size();
670 }
671 return true;
672}
673
674bool DeltaDiffGenerator::GenerateDeltaUpdateFile(const string& old_root,
675 const string& old_image,
676 const string& new_root,
677 const string& new_image,
678 const string& output_path) {
679 struct stat old_image_stbuf;
680 TEST_AND_RETURN_FALSE_ERRNO(stat(old_image.c_str(), &old_image_stbuf) == 0);
681 struct stat new_image_stbuf;
682 TEST_AND_RETURN_FALSE_ERRNO(stat(new_image.c_str(), &new_image_stbuf) == 0);
683 LOG_IF(WARNING, new_image_stbuf.st_size != old_image_stbuf.st_size)
684 << "Old and new images are different sizes.";
685 LOG_IF(FATAL, new_image_stbuf.st_size % kBlockSize)
686 << "New image not a multiple of block size " << kBlockSize;
687 LOG_IF(FATAL, old_image_stbuf.st_size % kBlockSize)
688 << "Old image not a multiple of block size " << kBlockSize;
689
690 vector<Block> blocks(min(old_image_stbuf.st_size / kBlockSize,
691 new_image_stbuf.st_size / kBlockSize));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700692 LOG(INFO) << "invalid: " << Vertex::kInvalidIndex;
693 LOG(INFO) << "len: " << blocks.size();
694 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
695 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
696 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
697 }
698 Graph graph;
699 CheckGraph(graph);
700
701 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
702 string temp_file_path;
703 off_t data_file_size = 0;
704
705 LOG(INFO) << "Reading files...";
706
707 DeltaArchiveManifest_InstallOperation final_op;
708 {
709 int fd;
710 TEST_AND_RETURN_FALSE(
711 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
712 TEST_AND_RETURN_FALSE(fd >= 0);
713 ScopedFdCloser fd_closer(&fd);
714
715 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
716 &blocks,
717 old_root,
718 new_root,
719 fd,
720 &data_file_size));
721 CheckGraph(graph);
722
723 // TODO(adlr): read all the rest of the blocks in
724 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
725 fd,
726 &data_file_size,
727 new_image,
728 &final_op));
729 }
730 CheckGraph(graph);
731
732 LOG(INFO) << "Creating edges...";
733 CreateEdges(&graph, blocks);
734 CheckGraph(graph);
735
736 CycleBreaker cycle_breaker;
737 LOG(INFO) << "Finding cycles...";
738 set<Edge> cut_edges;
739 cycle_breaker.BreakCycles(graph, &cut_edges);
740 CheckGraph(graph);
741
742 // Calculate number of scratch blocks needed
743
744 LOG(INFO) << "Cutting cycles...";
745 TEST_AND_RETURN_FALSE(CutEdges(&graph, blocks, cut_edges));
746 CheckGraph(graph);
747
748 vector<Vertex::Index> final_order;
749 LOG(INFO) << "Ordering...";
750 TopologicalSort(graph, &final_order);
751 CheckGraph(graph);
752
753 // Convert to protobuf Manifest object
754 DeltaArchiveManifest manifest;
755 CheckGraph(graph);
756 InstallOperationsToManifest(graph, final_order, &manifest);
757 {
758 // Write final operation
759 DeltaArchiveManifest_InstallOperation* op =
760 manifest.add_install_operations();
761 *op = final_op;
762 CHECK(op->has_type());
763 LOG(INFO) << "final op length: " << op->data_length();
764 }
765 CheckGraph(graph);
766 manifest.set_block_size(kBlockSize);
767 // TODO(adlr): set checksums
768
769 // Reorder the data blobs with the newly ordered manifest
770 string ordered_blobs_path;
771 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
772 "/tmp/CrAU_temp_data.ordered.XXXXXX",
773 &ordered_blobs_path,
774 false));
775 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
776 temp_file_path,
777 ordered_blobs_path));
778
779 // Check that install op blobs are in order and that all blocks are written.
780 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700781 vector<uint32_t> written_count(blocks.size(), 0);
782 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700783 for (int i = 0; i < manifest.install_operations_size(); i++) {
784 const DeltaArchiveManifest_InstallOperation& op =
785 manifest.install_operations(i);
786 for (int j = 0; j < op.dst_extents_size(); j++) {
787 const Extent& extent = op.dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700788 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700789 block < (extent.start_block() + extent.num_blocks()); block++) {
790 written_count[block]++;
791 }
792 }
793 if (op.has_data_offset()) {
794 if (op.data_offset() != next_blob_offset) {
795 LOG(FATAL) << "bad blob offset! " << op.data_offset() << " != "
796 << next_blob_offset;
797 }
798 next_blob_offset += op.data_length();
799 }
800 }
801 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700802 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700803 if (written_count[i] == 0) {
804 LOG(FATAL) << "block " << i << " not written!";
805 }
806 }
807 }
808
809 // Serialize protobuf
810 string serialized_manifest;
811
812 CheckGraph(graph);
813 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
814 CheckGraph(graph);
815
816 LOG(INFO) << "Writing final delta file header...";
817 DirectFileWriter writer;
818 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
819 O_WRONLY | O_CREAT | O_TRUNC,
820 0644) == 0);
821 ScopedFileWriterCloser writer_closer(&writer);
822
823 // Write header
824 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700825 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700826
827 // Write version number
828 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
829
830 // Write protobuf length
831 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
832 serialized_manifest.size()));
833
834 // Write protobuf
835 LOG(INFO) << "Writing final delta file protobuf... "
836 << serialized_manifest.size();
837 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
838 serialized_manifest.size()) ==
839 static_cast<ssize_t>(serialized_manifest.size()));
840
841 // Append the data blobs
842 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700843 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700844 ScopedFdCloser blobs_fd_closer(&blobs_fd);
845 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
846 for (;;) {
847 char buf[kBlockSize];
848 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
849 if (0 == rc) {
850 // EOF
851 break;
852 }
853 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
854 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
855 }
856
857 LOG(INFO) << "All done. Successfully created delta file.";
858 return true;
859}
860
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700861const char* const kBsdiffPath = "/usr/bin/bsdiff";
862const char* const kBspatchPath = "/usr/bin/bspatch";
863const char* const kDeltaMagic = "CrAU";
864
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700865}; // namespace chromeos_update_engine