blob: 9a5219df20de9dad746ee07f2546b9928343e4b1 [file] [log] [blame]
Darin Petkovc0b7a532010-09-29 15:18:14 -07001// Copyright (c) 2010 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>
21#include <base/string_util.h>
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070022#include <bzlib.h>
Darin Petkov880335c2010-10-01 15:52:53 -070023
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070024#include "update_engine/bzip.h"
25#include "update_engine/cycle_breaker.h"
26#include "update_engine/extent_mapper.h"
Andrew de los Reyesef017552010-10-06 17:57:52 -070027#include "update_engine/extent_ranges.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070028#include "update_engine/file_writer.h"
29#include "update_engine/filesystem_iterator.h"
30#include "update_engine/graph_types.h"
31#include "update_engine/graph_utils.h"
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -070032#include "update_engine/payload_signer.h"
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070033#include "update_engine/subprocess.h"
34#include "update_engine/topological_sort.h"
35#include "update_engine/update_metadata.pb.h"
36#include "update_engine/utils.h"
37
38using std::make_pair;
Andrew de los Reyesef017552010-10-06 17:57:52 -070039using std::map;
Andrew de los Reyes3270f742010-07-15 22:28:14 -070040using std::max;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070041using std::min;
42using std::set;
43using std::string;
44using std::vector;
45
46namespace chromeos_update_engine {
47
48typedef DeltaDiffGenerator::Block Block;
49
50namespace {
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070051const size_t kBlockSize = 4096; // bytes
Darin Petkovc0b7a532010-09-29 15:18:14 -070052const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // 1 GiB
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070053const uint64_t kVersionNumber = 1;
Andrew de los Reyes27f7d372010-10-07 11:26:07 -070054const uint64_t kFullUpdateChunkSize = 128 * 1024; // bytes
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070055
56// Stores all Extents for a file into 'out'. Returns true on success.
57bool GatherExtents(const string& path,
58 google::protobuf::RepeatedPtrField<Extent>* out) {
59 vector<Extent> extents;
60 TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
61 DeltaDiffGenerator::StoreExtents(extents, out);
62 return true;
63}
64
65// Runs the bsdiff tool on two files and returns the resulting delta in
66// 'out'. Returns true on success.
67bool BsdiffFiles(const string& old_file,
68 const string& new_file,
69 vector<char>* out) {
70 const string kPatchFile = "/tmp/delta.patchXXXXXX";
71 string patch_file_path;
72
73 TEST_AND_RETURN_FALSE(
74 utils::MakeTempFile(kPatchFile, &patch_file_path, NULL));
75
76 vector<string> cmd;
77 cmd.push_back(kBsdiffPath);
78 cmd.push_back(old_file);
79 cmd.push_back(new_file);
80 cmd.push_back(patch_file_path);
81
82 int rc = 1;
83 vector<char> patch_file;
84 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &rc));
85 TEST_AND_RETURN_FALSE(rc == 0);
86 TEST_AND_RETURN_FALSE(utils::ReadFile(patch_file_path, out));
87 unlink(patch_file_path.c_str());
88 return true;
89}
90
91// The blocks vector contains a reader and writer for each block on the
92// filesystem that's being in-place updated. We populate the reader/writer
93// fields of blocks by calling this function.
94// For each block in 'operation' that is read or written, find that block
95// in 'blocks' and set the reader/writer field to the vertex passed.
96// 'graph' is not strictly necessary, but useful for printing out
97// error messages.
98bool AddInstallOpToBlocksVector(
99 const DeltaArchiveManifest_InstallOperation& operation,
100 vector<Block>* blocks,
101 const Graph& graph,
102 Vertex::Index vertex) {
103 LOG(INFO) << "AddInstallOpToBlocksVector(" << vertex << "), "
104 << graph[vertex].file_name;
105 // See if this is already present.
106 TEST_AND_RETURN_FALSE(operation.dst_extents_size() > 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700107
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700108 enum BlockField { READER = 0, WRITER, BLOCK_FIELD_COUNT };
109 for (int field = READER; field < BLOCK_FIELD_COUNT; field++) {
110 const int extents_size =
111 (field == READER) ? operation.src_extents_size() :
112 operation.dst_extents_size();
113 const char* past_participle = (field == READER) ? "read" : "written";
114 const google::protobuf::RepeatedPtrField<Extent>& extents =
115 (field == READER) ? operation.src_extents() : operation.dst_extents();
116 Vertex::Index Block::*access_type =
117 (field == READER) ? &Block::reader : &Block::writer;
118
119 for (int i = 0; i < extents_size; i++) {
120 const Extent& extent = extents.Get(i);
121 if (extent.start_block() == kSparseHole) {
122 // Hole in sparse file. skip
123 continue;
124 }
125 for (uint64_t block = extent.start_block();
126 block < (extent.start_block() + extent.num_blocks()); block++) {
127 LOG(INFO) << "ext: " << i << " block: " << block;
128 if ((*blocks)[block].*access_type != Vertex::kInvalidIndex) {
129 LOG(FATAL) << "Block " << block << " is already "
130 << past_participle << " by "
131 << (*blocks)[block].*access_type << "("
132 << graph[(*blocks)[block].*access_type].file_name
133 << ") and also " << vertex << "("
134 << graph[vertex].file_name << ")";
135 }
136 (*blocks)[block].*access_type = vertex;
137 }
138 }
139 }
140 return true;
141}
142
Andrew de los Reyesef017552010-10-06 17:57:52 -0700143// For a given regular file which must exist at new_root + path, and
144// may exist at old_root + path, creates a new InstallOperation and
145// adds it to the graph. Also, populates the |blocks| array as
146// necessary, if |blocks| is non-NULL. Also, writes the data
147// necessary to send the file down to the client into data_fd, which
148// has length *data_file_size. *data_file_size is updated
149// appropriately. If |existing_vertex| is no kInvalidIndex, use that
150// rather than allocating a new vertex. Returns true on success.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700151bool DeltaReadFile(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700152 Vertex::Index existing_vertex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700153 vector<Block>* blocks,
154 const string& old_root,
155 const string& new_root,
156 const string& path, // within new_root
157 int data_fd,
158 off_t* data_file_size) {
159 vector<char> data;
160 DeltaArchiveManifest_InstallOperation operation;
161
162 TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_root + path,
163 new_root + path,
164 &data,
165 &operation));
166
167 // Write the data
168 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
169 operation.set_data_offset(*data_file_size);
170 operation.set_data_length(data.size());
171 }
172
173 TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
174 *data_file_size += data.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700175
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700176 // Now, insert into graph and blocks vector
Andrew de los Reyesef017552010-10-06 17:57:52 -0700177 Vertex::Index vertex = existing_vertex;
178 if (vertex == Vertex::kInvalidIndex) {
179 graph->resize(graph->size() + 1);
180 vertex = graph->size() - 1;
181 }
182 (*graph)[vertex].op = operation;
183 CHECK((*graph)[vertex].op.has_type());
184 (*graph)[vertex].file_name = path;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700185
Andrew de los Reyesef017552010-10-06 17:57:52 -0700186 if (blocks)
187 TEST_AND_RETURN_FALSE(AddInstallOpToBlocksVector((*graph)[vertex].op,
188 blocks,
189 *graph,
190 vertex));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700191 return true;
192}
193
194// For each regular file within new_root, creates a node in the graph,
195// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
196// and writes any necessary data to the end of data_fd.
197bool DeltaReadFiles(Graph* graph,
198 vector<Block>* blocks,
199 const string& old_root,
200 const string& new_root,
201 int data_fd,
202 off_t* data_file_size) {
203 set<ino_t> visited_inodes;
204 for (FilesystemIterator fs_iter(new_root,
205 utils::SetWithValue<string>("/lost+found"));
206 !fs_iter.IsEnd(); fs_iter.Increment()) {
207 if (!S_ISREG(fs_iter.GetStat().st_mode))
208 continue;
209
210 // Make sure we visit each inode only once.
211 if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
212 continue;
213 visited_inodes.insert(fs_iter.GetStat().st_ino);
214 if (fs_iter.GetStat().st_size == 0)
215 continue;
216
217 LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700218
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700219 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700220 Vertex::kInvalidIndex,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700221 blocks,
222 old_root,
223 new_root,
224 fs_iter.GetPartialPath(),
225 data_fd,
226 data_file_size));
227 }
228 return true;
229}
230
Andrew de los Reyesef017552010-10-06 17:57:52 -0700231// This class allocates non-existent temp blocks, starting from
232// kTempBlockStart. Other code is responsible for converting these
233// temp blocks into real blocks, as the client can't read or write to
234// these blocks.
235class DummyExtentAllocator {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700236 public:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700237 explicit DummyExtentAllocator()
238 : next_block_(kTempBlockStart) {}
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700239 vector<Extent> Allocate(const uint64_t block_count) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700240 vector<Extent> ret(1);
241 ret[0].set_start_block(next_block_);
242 ret[0].set_num_blocks(block_count);
243 next_block_ += block_count;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700244 return ret;
245 }
246 private:
Andrew de los Reyesef017552010-10-06 17:57:52 -0700247 uint64_t next_block_;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700248};
249
250// Reads blocks from image_path that are not yet marked as being written
251// in the blocks array. These blocks that remain are non-file-data blocks.
252// In the future we might consider intelligent diffing between this data
253// and data in the previous image, but for now we just bzip2 compress it
254// and include it in the update.
255// Creates a new node in the graph to write these blocks and writes the
256// appropriate blob to blobs_fd. Reads and updates blobs_length;
257bool ReadUnwrittenBlocks(const vector<Block>& blocks,
258 int blobs_fd,
259 off_t* blobs_length,
260 const string& image_path,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700261 Vertex* vertex) {
262 DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700263 int image_fd = open(image_path.c_str(), O_RDONLY, 000);
264 TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
265 ScopedFdCloser image_fd_closer(&image_fd);
266
267 string temp_file_path;
268 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
269 &temp_file_path,
270 NULL));
271
272 FILE* file = fopen(temp_file_path.c_str(), "w");
273 TEST_AND_RETURN_FALSE(file);
274 int err = BZ_OK;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700275
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700276 BZFILE* bz_file = BZ2_bzWriteOpen(&err,
277 file,
278 9, // max compression
279 0, // verbosity
280 0); // default work factor
281 TEST_AND_RETURN_FALSE(err == BZ_OK);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700282
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700283 vector<Extent> extents;
284 vector<Block>::size_type block_count = 0;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700285
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700286 LOG(INFO) << "Appending left over blocks to extents";
287 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
288 if (blocks[i].writer != Vertex::kInvalidIndex)
289 continue;
Andrew de los Reyesef017552010-10-06 17:57:52 -0700290 if (blocks[i].reader != Vertex::kInvalidIndex) {
291 graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
292 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700293 graph_utils::AppendBlockToExtents(&extents, i);
294 block_count++;
295 }
296
297 // Code will handle 'buf' at any size that's a multiple of kBlockSize,
298 // so we arbitrarily set it to 1024 * kBlockSize.
299 vector<char> buf(1024 * kBlockSize);
300
301 LOG(INFO) << "Reading left over blocks";
302 vector<Block>::size_type blocks_copied_count = 0;
303
304 // For each extent in extents, write the data into BZ2_bzWrite which
305 // sends it to an output file.
306 // We use the temporary buffer 'buf' to hold the data, which may be
307 // smaller than the extent, so in that case we have to loop to get
308 // the extent's data (that's the inner while loop).
309 for (vector<Extent>::const_iterator it = extents.begin();
310 it != extents.end(); ++it) {
311 vector<Block>::size_type blocks_read = 0;
312 while (blocks_read < it->num_blocks()) {
313 const int copy_block_cnt =
314 min(buf.size() / kBlockSize,
315 static_cast<vector<char>::size_type>(
316 it->num_blocks() - blocks_read));
317 ssize_t rc = pread(image_fd,
318 &buf[0],
319 copy_block_cnt * kBlockSize,
320 (it->start_block() + blocks_read) * kBlockSize);
321 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
322 TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
323 copy_block_cnt * kBlockSize);
324 BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
325 TEST_AND_RETURN_FALSE(err == BZ_OK);
326 blocks_read += copy_block_cnt;
327 blocks_copied_count += copy_block_cnt;
328 LOG(INFO) << "progress: " << ((float)blocks_copied_count)/block_count;
329 }
330 }
331 BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
332 TEST_AND_RETURN_FALSE(err == BZ_OK);
333 bz_file = NULL;
334 TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
335 file = NULL;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700336
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700337 vector<char> compressed_data;
338 LOG(INFO) << "Reading compressed data off disk";
339 TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
340 TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700341
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700342 // Add node to graph to write these blocks
343 out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
344 out_op->set_data_offset(*blobs_length);
345 out_op->set_data_length(compressed_data.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700346 LOG(INFO) << "Rootfs non-data blocks compressed take up "
347 << compressed_data.size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700348 *blobs_length += compressed_data.size();
349 out_op->set_dst_length(kBlockSize * block_count);
350 DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700351
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700352 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
353 &compressed_data[0],
354 compressed_data.size()));
355 LOG(INFO) << "done with extra blocks";
356 return true;
357}
358
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700359// Writes the uint64_t passed in in host-endian to the file as big-endian.
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700360// Returns true on success.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700361bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
362 uint64_t value_be = htobe64(value);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700363 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)) ==
364 sizeof(value_be));
365 return true;
366}
367
368// Adds each operation from the graph to the manifest in the order
369// specified by 'order'.
370void InstallOperationsToManifest(
371 const Graph& graph,
372 const vector<Vertex::Index>& order,
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700373 const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700374 DeltaArchiveManifest* out_manifest) {
375 for (vector<Vertex::Index>::const_iterator it = order.begin();
376 it != order.end(); ++it) {
377 DeltaArchiveManifest_InstallOperation* op =
378 out_manifest->add_install_operations();
379 *op = graph[*it].op;
380 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700381 for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
382 kernel_ops.begin(); it != kernel_ops.end(); ++it) {
383 DeltaArchiveManifest_InstallOperation* op =
384 out_manifest->add_kernel_install_operations();
385 *op = *it;
386 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700387}
388
389void CheckGraph(const Graph& graph) {
390 for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
391 CHECK(it->op.has_type());
392 }
393}
394
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700395// Delta compresses a kernel partition new_kernel_part with knowledge of
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700396// the old kernel partition old_kernel_part.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700397bool DeltaCompressKernelPartition(
398 const string& old_kernel_part,
399 const string& new_kernel_part,
400 vector<DeltaArchiveManifest_InstallOperation>* ops,
401 int blobs_fd,
402 off_t* blobs_length) {
403 // For now, just bsdiff the kernel partition as a whole.
404 // TODO(adlr): Use knowledge of how the kernel partition is laid out
405 // to more efficiently compress it.
406
407 LOG(INFO) << "Delta compressing kernel partition...";
408
409 // Add a new install operation
410 ops->resize(1);
411 DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700412 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700413 op->set_data_offset(*blobs_length);
414
415 // Do the actual compression
416 vector<char> data;
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700417 TEST_AND_RETURN_FALSE(utils::ReadFile(new_kernel_part, &data));
418 TEST_AND_RETURN_FALSE(!data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700419
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700420 vector<char> data_bz;
421 TEST_AND_RETURN_FALSE(BzipCompress(data, &data_bz));
422 CHECK(!data_bz.empty());
423
424 TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data_bz[0], data_bz.size()));
425 *blobs_length += data_bz.size();
426
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700427 off_t new_part_size = utils::FileSize(new_kernel_part);
428 TEST_AND_RETURN_FALSE(new_part_size >= 0);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700429
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700430 op->set_data_length(data_bz.size());
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700431
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700432 op->set_dst_length(new_part_size);
433
Andrew de los Reyes877ca8d2010-09-07 14:42:49 -0700434 // There's a single dest extent
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700435 Extent* dst_extent = op->add_dst_extents();
436 dst_extent->set_start_block(0);
437 dst_extent->set_num_blocks((new_part_size + kBlockSize - 1) / kBlockSize);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700438
Andrew de los Reyes36f37362010-09-03 09:20:04 -0700439 LOG(INFO) << "Done compressing kernel partition.";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700440 return true;
441}
442
Darin Petkov880335c2010-10-01 15:52:53 -0700443struct DeltaObject {
444 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
445 : name(in_name),
446 type(in_type),
447 size(in_size) {}
448 bool operator <(const DeltaObject& object) const {
449 return size < object.size;
450 }
451 string name;
452 int type;
453 off_t size;
454};
455
456static const char* kInstallOperationTypes[] = {
457 "REPLACE",
458 "REPLACE_BZ",
459 "MOVE",
460 "BSDIFF"
461};
462
463void ReportPayloadUsage(const Graph& graph,
464 const DeltaArchiveManifest& manifest) {
465 vector<DeltaObject> objects;
466 off_t total_size = 0;
467
468 // Graph nodes with information about file names.
469 for (Vertex::Index node = 0; node < graph.size(); node++) {
470 objects.push_back(DeltaObject(graph[node].file_name,
471 graph[node].op.type(),
472 graph[node].op.data_length()));
473 total_size += graph[node].op.data_length();
474 }
475
476 // Final rootfs operation writing non-file-data.
477 const DeltaArchiveManifest_InstallOperation& final_op =
478 manifest.install_operations(manifest.install_operations_size() - 1);
479 objects.push_back(DeltaObject("<rootfs-final-operation>",
480 final_op.type(),
481 final_op.data_length()));
482 total_size += final_op.data_length();
483
484 // Kernel install operations.
485 for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
486 const DeltaArchiveManifest_InstallOperation& op =
487 manifest.kernel_install_operations(i);
488 objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
489 op.type(),
490 op.data_length()));
491 total_size += op.data_length();
492 }
493
494 std::sort(objects.begin(), objects.end());
495
496 static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
497 for (vector<DeltaObject>::const_iterator it = objects.begin();
498 it != objects.end(); ++it) {
499 const DeltaObject& object = *it;
500 fprintf(stderr, kFormatString,
501 object.size * 100.0 / total_size,
502 object.size,
503 kInstallOperationTypes[object.type],
504 object.name.c_str());
505 }
506 fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
507}
508
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700509} // namespace {}
510
511bool DeltaDiffGenerator::ReadFileToDiff(
512 const string& old_filename,
513 const string& new_filename,
514 vector<char>* out_data,
515 DeltaArchiveManifest_InstallOperation* out_op) {
516 // Read new data in
517 vector<char> new_data;
518 TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700519
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700520 TEST_AND_RETURN_FALSE(!new_data.empty());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700521
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700522 vector<char> new_data_bz;
523 TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
524 CHECK(!new_data_bz.empty());
525
526 vector<char> data; // Data blob that will be written to delta file.
527
528 DeltaArchiveManifest_InstallOperation operation;
529 size_t current_best_size = 0;
530 if (new_data.size() <= new_data_bz.size()) {
531 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
532 current_best_size = new_data.size();
533 data = new_data;
534 } else {
535 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
536 current_best_size = new_data_bz.size();
537 data = new_data_bz;
538 }
539
540 // Do we have an original file to consider?
541 struct stat old_stbuf;
542 if (0 != stat(old_filename.c_str(), &old_stbuf)) {
543 // If stat-ing the old file fails, it should be because it doesn't exist.
544 TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
545 } else {
546 // Read old data
547 vector<char> old_data;
548 TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
549 if (old_data == new_data) {
550 // No change in data.
551 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
552 current_best_size = 0;
553 data.clear();
554 } else {
555 // Try bsdiff of old to new data
556 vector<char> bsdiff_delta;
557 TEST_AND_RETURN_FALSE(
558 BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
559 CHECK_GT(bsdiff_delta.size(), 0);
560 if (bsdiff_delta.size() < current_best_size) {
561 operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
562 current_best_size = bsdiff_delta.size();
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700563
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700564 data = bsdiff_delta;
565 }
566 }
567 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700568
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700569 // Set parameters of the operations
570 CHECK_EQ(data.size(), current_best_size);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700571
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700572 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
573 operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
574 TEST_AND_RETURN_FALSE(
575 GatherExtents(old_filename, operation.mutable_src_extents()));
576 operation.set_src_length(old_stbuf.st_size);
577 }
578
579 TEST_AND_RETURN_FALSE(
580 GatherExtents(new_filename, operation.mutable_dst_extents()));
581 operation.set_dst_length(new_data.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700582
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700583 out_data->swap(data);
584 *out_op = operation;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700585
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 return true;
587}
588
Andrew de los Reyesef017552010-10-06 17:57:52 -0700589namespace {
590
591// Takes a collection (vector or RepeatedPtrField) of Extent and
592// returns a vector of the blocks referenced, in order.
593template<typename T>
594vector<uint64_t> ExpandExtents(const T& extents) {
595 vector<uint64_t> ret;
596 for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
597 const Extent extent = graph_utils::GetElement(extents, i);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700598 if (extent.start_block() == kSparseHole) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700599 ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700600 } else {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700601 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700602 block < (extent.start_block() + extent.num_blocks()); block++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700603 ret.push_back(block);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700604 }
605 }
606 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700607 return ret;
608}
609
610// Takes a vector of blocks and returns an equivalent vector of Extent
611// objects.
612vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
613 vector<Extent> new_extents;
614 for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
615 it != e; ++it) {
616 graph_utils::AppendBlockToExtents(&new_extents, *it);
617 }
618 return new_extents;
619}
620
621} // namespace {}
622
623void DeltaDiffGenerator::SubstituteBlocks(
624 Vertex* vertex,
625 const vector<Extent>& remove_extents,
626 const vector<Extent>& replace_extents) {
627 // First, expand out the blocks that op reads from
628 vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700629 {
630 // Expand remove_extents and replace_extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700631 vector<uint64_t> remove_extents_expanded =
632 ExpandExtents(remove_extents);
633 vector<uint64_t> replace_extents_expanded =
634 ExpandExtents(replace_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700635 CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700636 map<uint64_t, uint64_t> conversion;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700637 for (vector<uint64_t>::size_type i = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700638 i < replace_extents_expanded.size(); i++) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700639 conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
640 }
641 utils::ApplyMap(&read_blocks, conversion);
642 for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
643 e = vertex->out_edges.end(); it != e; ++it) {
644 vector<uint64_t> write_before_deps_expanded =
645 ExpandExtents(it->second.write_extents);
646 utils::ApplyMap(&write_before_deps_expanded, conversion);
647 it->second.write_extents = CompressExtents(write_before_deps_expanded);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700648 }
649 }
650 // Convert read_blocks back to extents
Andrew de los Reyesef017552010-10-06 17:57:52 -0700651 vertex->op.clear_src_extents();
652 vector<Extent> new_extents = CompressExtents(read_blocks);
653 DeltaDiffGenerator::StoreExtents(new_extents,
654 vertex->op.mutable_src_extents());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700655}
656
657bool DeltaDiffGenerator::CutEdges(Graph* graph,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700658 const set<Edge>& edges,
659 vector<CutEdgeVertexes>* out_cuts) {
660 DummyExtentAllocator scratch_allocator;
661 vector<CutEdgeVertexes> cuts;
662 cuts.reserve(edges.size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700663
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700664 uint64_t scratch_blocks_used = 0;
665 for (set<Edge>::const_iterator it = edges.begin();
666 it != edges.end(); ++it) {
Andrew de los Reyesef017552010-10-06 17:57:52 -0700667 cuts.resize(cuts.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700668 vector<Extent> old_extents =
669 (*graph)[it->first].out_edges[it->second].extents;
670 // Choose some scratch space
671 scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
672 LOG(INFO) << "using " << graph_utils::EdgeWeight(*graph, *it)
673 << " scratch blocks ("
674 << scratch_blocks_used << ")";
Andrew de los Reyesef017552010-10-06 17:57:52 -0700675 cuts.back().tmp_extents =
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700676 scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
677 // create vertex to copy original->scratch
Andrew de los Reyesef017552010-10-06 17:57:52 -0700678 cuts.back().new_vertex = graph->size();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700679 graph->resize(graph->size() + 1);
Andrew de los Reyesef017552010-10-06 17:57:52 -0700680 cuts.back().old_src = it->first;
681 cuts.back().old_dst = it->second;
682
683 EdgeProperties& cut_edge_properties =
684 (*graph)[it->first].out_edges.find(it->second)->second;
685
686 // This should never happen, as we should only be cutting edges between
687 // real file nodes, and write-before relationships are created from
688 // a real file node to a temp copy node:
689 CHECK(cut_edge_properties.write_extents.empty())
690 << "Can't cut edge that has write-before relationship.";
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -0700691
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700692 // make node depend on the copy operation
693 (*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700694 cut_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700695
696 // Set src/dst extents and other proto variables for copy operation
697 graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
698 DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700699 cut_edge_properties.extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700700 graph->back().op.mutable_src_extents());
Andrew de los Reyesef017552010-10-06 17:57:52 -0700701 DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700702 graph->back().op.mutable_dst_extents());
703 graph->back().op.set_src_length(
704 graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
705 graph->back().op.set_dst_length(graph->back().op.src_length());
706
707 // make the dest node read from the scratch space
708 DeltaDiffGenerator::SubstituteBlocks(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700709 &((*graph)[it->second]),
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700710 (*graph)[it->first].out_edges[it->second].extents,
Andrew de los Reyesef017552010-10-06 17:57:52 -0700711 cuts.back().tmp_extents);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700712
713 // delete the old edge
714 CHECK_EQ(1, (*graph)[it->first].out_edges.erase(it->second));
Chris Masone790e62e2010-08-12 10:41:18 -0700715
Andrew de los Reyesd12784c2010-07-26 13:55:14 -0700716 // Add an edge from dst to copy operation
Andrew de los Reyesef017552010-10-06 17:57:52 -0700717 EdgeProperties write_before_edge_properties;
718 write_before_edge_properties.write_extents = cuts.back().tmp_extents;
719 (*graph)[it->second].out_edges.insert(
720 make_pair(graph->size() - 1, write_before_edge_properties));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700721 }
Andrew de los Reyesef017552010-10-06 17:57:52 -0700722 out_cuts->swap(cuts);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700723 return true;
724}
725
726// Stores all Extents in 'extents' into 'out'.
727void DeltaDiffGenerator::StoreExtents(
Andrew de los Reyesef017552010-10-06 17:57:52 -0700728 const vector<Extent>& extents,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700729 google::protobuf::RepeatedPtrField<Extent>* out) {
730 for (vector<Extent>::const_iterator it = extents.begin();
731 it != extents.end(); ++it) {
732 Extent* new_extent = out->Add();
733 *new_extent = *it;
734 }
735}
736
737// Creates all the edges for the graph. Writers of a block point to
738// readers of the same block. This is because for an edge A->B, B
739// must complete before A executes.
740void DeltaDiffGenerator::CreateEdges(Graph* graph,
741 const vector<Block>& blocks) {
742 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
743 // Blocks with both a reader and writer get an edge
744 if (blocks[i].reader == Vertex::kInvalidIndex ||
745 blocks[i].writer == Vertex::kInvalidIndex)
746 continue;
747 // Don't have a node depend on itself
748 if (blocks[i].reader == blocks[i].writer)
749 continue;
750 // See if there's already an edge we can add onto
751 Vertex::EdgeMap::iterator edge_it =
752 (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
753 if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
754 // No existing edge. Create one
755 (*graph)[blocks[i].writer].out_edges.insert(
756 make_pair(blocks[i].reader, EdgeProperties()));
757 edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
Chris Masone790e62e2010-08-12 10:41:18 -0700758 CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700759 }
760 graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
761 }
762}
763
Andrew de los Reyesef017552010-10-06 17:57:52 -0700764namespace {
765
766class SortCutsByTopoOrderLess {
767 public:
768 SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
769 : table_(table) {}
770 bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
771 return table_[a.old_dst] < table_[b.old_dst];
772 }
773 private:
774 vector<vector<Vertex::Index>::size_type>& table_;
775};
776
777} // namespace {}
778
779void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
780 vector<Vertex::Index>& op_indexes,
781 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
782 vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
783 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
784 i != e; ++i) {
785 Vertex::Index node = op_indexes[i];
786 if (table.size() < (node + 1)) {
787 table.resize(node + 1);
788 }
789 table[node] = i;
790 }
791 reverse_op_indexes->swap(table);
792}
793
794void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
795 vector<CutEdgeVertexes>* cuts) {
796 // first, make a reverse lookup table.
797 vector<vector<Vertex::Index>::size_type> table;
798 GenerateReverseTopoOrderMap(op_indexes, &table);
799 SortCutsByTopoOrderLess less(table);
800 sort(cuts->begin(), cuts->end(), less);
801}
802
803void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
804 vector<Vertex::Index>* op_indexes) {
805 vector<Vertex::Index> ret;
806 vector<Vertex::Index> full_ops;
807 ret.reserve(op_indexes->size());
808 for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
809 ++i) {
810 DeltaArchiveManifest_InstallOperation_Type type =
811 (*graph)[(*op_indexes)[i]].op.type();
812 if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
813 type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
814 full_ops.push_back((*op_indexes)[i]);
815 } else {
816 ret.push_back((*op_indexes)[i]);
817 }
818 }
819 LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
820 << (full_ops.size() + ret.size()) << " total ops.";
821 ret.insert(ret.end(), full_ops.begin(), full_ops.end());
822 op_indexes->swap(ret);
823}
824
825namespace {
826
827template<typename T>
828bool TempBlocksExistInExtents(const T& extents) {
829 for (int i = 0, e = extents.size(); i < e; ++i) {
830 Extent extent = graph_utils::GetElement(extents, i);
831 uint64_t start = extent.start_block();
832 uint64_t num = extent.num_blocks();
833 if (start == kSparseHole)
834 continue;
835 if (start >= kTempBlockStart ||
836 (start + num) >= kTempBlockStart) {
837 LOG(ERROR) << "temp block!";
838 LOG(ERROR) << "start: " << start << ", num: " << num;
839 LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
840 LOG(ERROR) << "returning true";
841 return true;
842 }
843 // check for wrap-around, which would be a bug:
844 CHECK(start <= (start + num));
845 }
846 return false;
847}
848
849} // namespace {}
850
851bool DeltaDiffGenerator::AssignTempBlocks(
852 Graph* graph,
853 const string& new_root,
854 int data_fd,
855 off_t* data_file_size,
856 vector<Vertex::Index>* op_indexes,
857 vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
858 vector<CutEdgeVertexes>& cuts) {
859 CHECK(!cuts.empty());
860 for (vector<CutEdgeVertexes>::size_type i = cuts.size() - 1, e = 0;
861 true ; --i) {
862 LOG(INFO) << "Fixing temp blocks in cut " << i
863 << ": old dst: " << cuts[i].old_dst << " new vertex: "
864 << cuts[i].new_vertex;
865 const uint64_t blocks_needed =
866 graph_utils::BlocksInExtents(cuts[i].tmp_extents);
867 LOG(INFO) << "Scanning for usable blocks (" << blocks_needed << " needed)";
868 // For now, just look for a single op w/ sufficient blocks, not
869 // considering blocks from outgoing read-before deps.
870 Vertex::Index node = cuts[i].old_dst;
871 DeltaArchiveManifest_InstallOperation_Type node_type =
872 (*graph)[node].op.type();
873 if (node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
874 node_type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
875 LOG(INFO) << "This was already converted to full, so skipping.";
876 // Delete the temp node and pointer to it from old src
877 if (!(*graph)[cuts[i].old_src].out_edges.erase(cuts[i].new_vertex)) {
878 LOG(INFO) << "Odd. node " << cuts[i].old_src << " didn't point to "
879 << cuts[i].new_vertex;
880 }
881 (*graph)[cuts[i].new_vertex].valid = false;
882 vector<Vertex::Index>::size_type new_topo_idx =
883 (*reverse_op_indexes)[cuts[i].new_vertex];
884 op_indexes->erase(op_indexes->begin() + new_topo_idx);
885 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
886 continue;
887 }
888 bool found_node = false;
889 for (vector<Vertex::Index>::size_type j = (*reverse_op_indexes)[node] + 1,
890 je = op_indexes->size(); j < je; ++j) {
891 Vertex::Index test_node = (*op_indexes)[j];
892 // See if this node has sufficient blocks
893 ExtentRanges ranges;
894 ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
895 ranges.SubtractExtent(ExtentForRange(
896 kTempBlockStart, kSparseHole - kTempBlockStart));
897 ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
898 // For now, for simplicity, subtract out all blocks in read-before
899 // dependencies.
900 for (Vertex::EdgeMap::const_iterator edge_i =
901 (*graph)[test_node].out_edges.begin(),
902 edge_e = (*graph)[test_node].out_edges.end();
903 edge_i != edge_e; ++edge_i) {
904 ranges.SubtractExtents(edge_i->second.extents);
905 }
906
907 uint64_t blocks_found = ranges.blocks();
908 if (blocks_found < blocks_needed) {
909 if (blocks_found > 0)
910 LOG(INFO) << "insufficient blocks found in topo node " << j
911 << " (node " << (*op_indexes)[j] << "). Found only "
912 << blocks_found;
913 continue;
914 }
915 found_node = true;
916 LOG(INFO) << "Found sufficient blocks in topo node " << j
917 << " (node " << (*op_indexes)[j] << ")";
918 // Sub in the blocks, and make the node supplying the blocks
919 // depend on old_dst.
920 vector<Extent> real_extents =
921 ranges.GetExtentsForBlockCount(blocks_needed);
922
923 // Fix the old dest node w/ the real blocks
924 SubstituteBlocks(&(*graph)[node],
925 cuts[i].tmp_extents,
926 real_extents);
927
928 // Fix the new node w/ the real blocks. Since the new node is just a
929 // copy operation, we can replace all the dest extents w/ the real
930 // blocks.
931 DeltaArchiveManifest_InstallOperation *op =
932 &(*graph)[cuts[i].new_vertex].op;
933 op->clear_dst_extents();
934 StoreExtents(real_extents, op->mutable_dst_extents());
935
936 // Add an edge from the real-block supplier to the old dest block.
937 graph_utils::AddReadBeforeDepExtents(&(*graph)[test_node],
938 node,
939 real_extents);
940 break;
941 }
942 if (!found_node) {
943 // convert to full op
944 LOG(WARNING) << "Failed to find enough temp blocks for cut " << i
945 << " with old dest (graph node " << node
946 << "). Converting to a full op, at the expense of a "
947 << "good compression ratio.";
948 TEST_AND_RETURN_FALSE(ConvertCutToFullOp(graph,
949 cuts[i],
950 new_root,
951 data_fd,
952 data_file_size));
953 // move the full op to the back
954 vector<Vertex::Index> new_op_indexes;
955 for (vector<Vertex::Index>::const_iterator iter_i = op_indexes->begin(),
956 iter_e = op_indexes->end(); iter_i != iter_e; ++iter_i) {
957 if ((*iter_i == cuts[i].old_dst) || (*iter_i == cuts[i].new_vertex))
958 continue;
959 new_op_indexes.push_back(*iter_i);
960 }
961 new_op_indexes.push_back(cuts[i].old_dst);
962 op_indexes->swap(new_op_indexes);
963
964 GenerateReverseTopoOrderMap(*op_indexes, reverse_op_indexes);
965 }
966 if (i == e) {
967 // break out of for() loop
968 break;
969 }
970 }
971 return true;
972}
973
974bool DeltaDiffGenerator::NoTempBlocksRemain(const Graph& graph) {
975 size_t idx = 0;
976 for (Graph::const_iterator it = graph.begin(), e = graph.end(); it != e;
977 ++it, ++idx) {
978 if (!it->valid)
979 continue;
980 const DeltaArchiveManifest_InstallOperation& op = it->op;
981 if (TempBlocksExistInExtents(op.dst_extents()) ||
982 TempBlocksExistInExtents(op.src_extents())) {
983 LOG(INFO) << "bad extents in node " << idx;
984 LOG(INFO) << "so yeah";
985 return false;
986 }
987
988 // Check out-edges:
989 for (Vertex::EdgeMap::const_iterator jt = it->out_edges.begin(),
990 je = it->out_edges.end(); jt != je; ++jt) {
991 if (TempBlocksExistInExtents(jt->second.extents) ||
992 TempBlocksExistInExtents(jt->second.write_extents)) {
993 LOG(INFO) << "bad out edge in node " << idx;
994 LOG(INFO) << "so yeah";
995 return false;
996 }
997 }
998 }
999 return true;
1000}
1001
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001002bool DeltaDiffGenerator::ReorderDataBlobs(
1003 DeltaArchiveManifest* manifest,
1004 const std::string& data_blobs_path,
1005 const std::string& new_data_blobs_path) {
1006 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
1007 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
1008 ScopedFdCloser in_fd_closer(&in_fd);
Chris Masone790e62e2010-08-12 10:41:18 -07001009
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001010 DirectFileWriter writer;
1011 TEST_AND_RETURN_FALSE(
1012 writer.Open(new_data_blobs_path.c_str(),
1013 O_WRONLY | O_TRUNC | O_CREAT,
1014 0644) == 0);
1015 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001016 uint64_t out_file_size = 0;
Chris Masone790e62e2010-08-12 10:41:18 -07001017
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001018 for (int i = 0; i < (manifest->install_operations_size() +
1019 manifest->kernel_install_operations_size()); i++) {
1020 DeltaArchiveManifest_InstallOperation* op = NULL;
1021 if (i < manifest->install_operations_size()) {
1022 op = manifest->mutable_install_operations(i);
1023 } else {
1024 op = manifest->mutable_kernel_install_operations(
1025 i - manifest->install_operations_size());
1026 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001027 if (!op->has_data_offset())
1028 continue;
1029 CHECK(op->has_data_length());
1030 vector<char> buf(op->data_length());
1031 ssize_t rc = pread(in_fd, &buf[0], buf.size(), op->data_offset());
1032 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
1033
1034 op->set_data_offset(out_file_size);
1035 TEST_AND_RETURN_FALSE(writer.Write(&buf[0], buf.size()) ==
1036 static_cast<ssize_t>(buf.size()));
1037 out_file_size += buf.size();
1038 }
1039 return true;
1040}
1041
Andrew de los Reyesef017552010-10-06 17:57:52 -07001042bool DeltaDiffGenerator::ConvertCutToFullOp(Graph* graph,
1043 const CutEdgeVertexes& cut,
1044 const string& new_root,
1045 int data_fd,
1046 off_t* data_file_size) {
1047 // Drop all incoming edges, keep all outgoing edges
1048
1049 // Keep all outgoing edges
1050 Vertex::EdgeMap out_edges = (*graph)[cut.old_dst].out_edges;
1051 graph_utils::DropWriteBeforeDeps(&out_edges);
1052
1053 TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
1054 cut.old_dst,
1055 NULL,
1056 "/-!@:&*nonexistent_path",
1057 new_root,
1058 (*graph)[cut.old_dst].file_name,
1059 data_fd,
1060 data_file_size));
1061
1062 (*graph)[cut.old_dst].out_edges = out_edges;
1063
1064 // Right now we don't have doubly-linked edges, so we have to scan
1065 // the whole graph.
1066 graph_utils::DropIncomingEdgesTo(graph, cut.old_dst);
1067
1068 // Delete temp node
1069 (*graph)[cut.old_src].out_edges.erase(cut.new_vertex);
1070 CHECK((*graph)[cut.old_dst].out_edges.find(cut.new_vertex) ==
1071 (*graph)[cut.old_dst].out_edges.end());
1072 (*graph)[cut.new_vertex].valid = false;
1073 return true;
1074}
1075
1076bool DeltaDiffGenerator::ConvertGraphToDag(Graph* graph,
1077 const string& new_root,
1078 int fd,
1079 off_t* data_file_size,
1080 vector<Vertex::Index>* final_order) {
1081 CycleBreaker cycle_breaker;
1082 LOG(INFO) << "Finding cycles...";
1083 set<Edge> cut_edges;
1084 cycle_breaker.BreakCycles(*graph, &cut_edges);
1085 LOG(INFO) << "done finding cycles";
1086 CheckGraph(*graph);
1087
1088 // Calculate number of scratch blocks needed
1089
1090 LOG(INFO) << "Cutting cycles...";
1091 vector<CutEdgeVertexes> cuts;
1092 TEST_AND_RETURN_FALSE(CutEdges(graph, cut_edges, &cuts));
1093 LOG(INFO) << "done cutting cycles";
1094 LOG(INFO) << "There are " << cuts.size() << " cuts.";
1095 CheckGraph(*graph);
1096
1097 LOG(INFO) << "Creating initial topological order...";
1098 TopologicalSort(*graph, final_order);
1099 LOG(INFO) << "done with initial topo order";
1100 CheckGraph(*graph);
1101
1102 LOG(INFO) << "Moving full ops to the back";
1103 MoveFullOpsToBack(graph, final_order);
1104 LOG(INFO) << "done moving full ops to back";
1105
1106 vector<vector<Vertex::Index>::size_type> inverse_final_order;
1107 GenerateReverseTopoOrderMap(*final_order, &inverse_final_order);
1108
1109 if (!cuts.empty())
1110 TEST_AND_RETURN_FALSE(AssignTempBlocks(graph,
1111 new_root,
1112 fd,
1113 data_file_size,
1114 final_order,
1115 &inverse_final_order,
1116 cuts));
1117 LOG(INFO) << "Making sure all temp blocks have been allocated";
1118 graph_utils::DumpGraph(*graph);
1119 CHECK(NoTempBlocksRemain(*graph));
1120 LOG(INFO) << "done making sure all temp blocks are allocated";
1121 return true;
1122}
1123
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001124bool DeltaDiffGenerator::ReadFullUpdateFromDisk(
1125 Graph* graph,
1126 const std::string& new_kernel_part,
1127 const std::string& new_image,
1128 int fd,
1129 off_t* data_file_size,
1130 off_t chunk_size,
1131 vector<DeltaArchiveManifest_InstallOperation>* kernel_ops,
1132 std::vector<Vertex::Index>* final_order) {
1133 TEST_AND_RETURN_FALSE(chunk_size > 0);
1134 TEST_AND_RETURN_FALSE((chunk_size % kBlockSize) == 0);
1135
1136 // Get the sizes early in the function, so we can fail fast if the user
1137 // passed us bad paths.
1138 const off_t image_size = utils::FileSize(new_image);
1139 TEST_AND_RETURN_FALSE(image_size >= 0);
1140 const off_t kernel_size = utils::FileSize(new_kernel_part);
1141 TEST_AND_RETURN_FALSE(kernel_size >= 0);
1142
1143 off_t part_sizes[] = { image_size, kernel_size };
1144 string paths[] = { new_image, new_kernel_part };
1145
1146 for (int partition = 0; partition < 2; ++partition) {
1147 const string& path = paths[partition];
1148 LOG(INFO) << "compressing " << path;
1149
1150 int in_fd = open(path.c_str(), O_RDONLY, 0);
1151 TEST_AND_RETURN_FALSE(in_fd >= 0);
1152 ScopedFdCloser in_fd_closer(&in_fd);
1153
1154 for (off_t bytes_left = part_sizes[partition], counter = 0, offset = 0;
1155 bytes_left > 0;
1156 bytes_left -= chunk_size, ++counter, offset += chunk_size) {
1157 LOG(INFO) << "offset = " << offset;
1158 DeltaArchiveManifest_InstallOperation* op = NULL;
1159 if (partition == 0) {
1160 graph->resize(graph->size() + 1);
1161 graph->back().file_name = path + StringPrintf("-%" PRIi64, counter);
1162 op = &graph->back().op;
1163 final_order->push_back(graph->size() - 1);
1164 } else {
1165 kernel_ops->resize(kernel_ops->size() + 1);
1166 op = &kernel_ops->back();
1167 }
1168 LOG(INFO) << "have an op";
1169
1170 vector<char> buf(min(bytes_left, chunk_size));
1171 LOG(INFO) << "buf size: " << buf.size();
1172 ssize_t bytes_read = -1;
1173
1174 TEST_AND_RETURN_FALSE(utils::PReadAll(
1175 in_fd, &buf[0], buf.size(), offset, &bytes_read));
1176 TEST_AND_RETURN_FALSE(bytes_read == static_cast<ssize_t>(buf.size()));
1177
1178 vector<char> buf_compressed;
1179
1180 TEST_AND_RETURN_FALSE(BzipCompress(buf, &buf_compressed));
1181 const bool compress = buf_compressed.size() < buf.size();
1182 const vector<char>& use_buf = compress ? buf_compressed : buf;
1183 if (compress) {
1184 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
1185 } else {
1186 op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1187 }
1188 op->set_data_offset(*data_file_size);
1189 *data_file_size += use_buf.size();
1190 op->set_data_length(use_buf.size());
1191 Extent* dst_extent = op->add_dst_extents();
1192 dst_extent->set_start_block(offset / kBlockSize);
1193 dst_extent->set_num_blocks(chunk_size / kBlockSize);
1194 }
1195 }
1196
1197 return true;
1198}
1199
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001200bool DeltaDiffGenerator::GenerateDeltaUpdateFile(
1201 const string& old_root,
1202 const string& old_image,
1203 const string& new_root,
1204 const string& new_image,
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001205 const string& old_kernel_part,
1206 const string& new_kernel_part,
1207 const string& output_path,
1208 const string& private_key_path) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001209 struct stat old_image_stbuf;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001210 struct stat new_image_stbuf;
1211 TEST_AND_RETURN_FALSE_ERRNO(stat(new_image.c_str(), &new_image_stbuf) == 0);
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001212 if (!old_image.empty()) {
1213 TEST_AND_RETURN_FALSE_ERRNO(stat(old_image.c_str(), &old_image_stbuf) == 0);
1214 LOG_IF(WARNING, new_image_stbuf.st_size != old_image_stbuf.st_size)
1215 << "Old and new images are different sizes.";
1216 LOG_IF(FATAL, old_image_stbuf.st_size % kBlockSize)
1217 << "Old image not a multiple of block size " << kBlockSize;
1218 // Sanity check kernel partition arg
1219 TEST_AND_RETURN_FALSE(utils::FileSize(old_kernel_part) >= 0);
1220 } else {
1221 old_image_stbuf.st_size = 0;
1222 }
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001223 LOG_IF(FATAL, new_image_stbuf.st_size % kBlockSize)
1224 << "New image not a multiple of block size " << kBlockSize;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001225
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001226 // Sanity check kernel partition arg
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001227 TEST_AND_RETURN_FALSE(utils::FileSize(new_kernel_part) >= 0);
1228
Andrew de los Reyes3270f742010-07-15 22:28:14 -07001229 vector<Block> blocks(max(old_image_stbuf.st_size / kBlockSize,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001230 new_image_stbuf.st_size / kBlockSize));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001231 LOG(INFO) << "invalid: " << Vertex::kInvalidIndex;
1232 LOG(INFO) << "len: " << blocks.size();
1233 for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
1234 CHECK(blocks[i].reader == Vertex::kInvalidIndex);
1235 CHECK(blocks[i].writer == Vertex::kInvalidIndex);
1236 }
1237 Graph graph;
1238 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001239
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001240 const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
1241 string temp_file_path;
1242 off_t data_file_size = 0;
1243
1244 LOG(INFO) << "Reading files...";
1245
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001246 vector<DeltaArchiveManifest_InstallOperation> kernel_ops;
1247
Andrew de los Reyesef017552010-10-06 17:57:52 -07001248 vector<Vertex::Index> final_order;
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001249 if (!old_image.empty()) {
1250 // Delta update
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001251 int fd;
1252 TEST_AND_RETURN_FALSE(
1253 utils::MakeTempFile(kTempFileTemplate, &temp_file_path, &fd));
1254 TEST_AND_RETURN_FALSE(fd >= 0);
1255 ScopedFdCloser fd_closer(&fd);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001256
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001257 TEST_AND_RETURN_FALSE(DeltaReadFiles(&graph,
1258 &blocks,
1259 old_root,
1260 new_root,
1261 fd,
1262 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001263 LOG(INFO) << "done reading normal files";
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001264 CheckGraph(graph);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001265
Andrew de los Reyesef017552010-10-06 17:57:52 -07001266 graph.resize(graph.size() + 1);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001267 TEST_AND_RETURN_FALSE(ReadUnwrittenBlocks(blocks,
1268 fd,
1269 &data_file_size,
1270 new_image,
Andrew de los Reyesef017552010-10-06 17:57:52 -07001271 &graph.back()));
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001272
1273 // Read kernel partition
1274 TEST_AND_RETURN_FALSE(DeltaCompressKernelPartition(old_kernel_part,
1275 new_kernel_part,
1276 &kernel_ops,
1277 fd,
1278 &data_file_size));
Andrew de los Reyesef017552010-10-06 17:57:52 -07001279
1280 LOG(INFO) << "done reading kernel";
1281 CheckGraph(graph);
1282
1283 LOG(INFO) << "Creating edges...";
1284 CreateEdges(&graph, blocks);
1285 LOG(INFO) << "Done creating edges";
1286 CheckGraph(graph);
1287
1288 TEST_AND_RETURN_FALSE(ConvertGraphToDag(&graph,
1289 new_root,
1290 fd,
1291 &data_file_size,
1292 &final_order));
Andrew de los Reyes27f7d372010-10-07 11:26:07 -07001293 } else {
1294 // Full update
1295 int fd = 0;
1296 TEST_AND_RETURN_FALSE(ReadFullUpdateFromDisk(&graph,
1297 new_kernel_part,
1298 new_image,
1299 fd,
1300 &data_file_size,
1301 kFullUpdateChunkSize,
1302 &kernel_ops,
1303 &final_order));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001304 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001305
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001306 // Convert to protobuf Manifest object
1307 DeltaArchiveManifest manifest;
1308 CheckGraph(graph);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001309 InstallOperationsToManifest(graph, final_order, kernel_ops, &manifest);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001310
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001311 CheckGraph(graph);
1312 manifest.set_block_size(kBlockSize);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001313
1314 // Reorder the data blobs with the newly ordered manifest
1315 string ordered_blobs_path;
1316 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
1317 "/tmp/CrAU_temp_data.ordered.XXXXXX",
1318 &ordered_blobs_path,
1319 false));
1320 TEST_AND_RETURN_FALSE(ReorderDataBlobs(&manifest,
1321 temp_file_path,
1322 ordered_blobs_path));
1323
1324 // Check that install op blobs are in order and that all blocks are written.
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001325 uint64_t next_blob_offset = 0;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001326 {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001327 vector<uint32_t> written_count(blocks.size(), 0);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001328 for (int i = 0; i < (manifest.install_operations_size() +
1329 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001330 DeltaArchiveManifest_InstallOperation* op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001331 i < manifest.install_operations_size() ?
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001332 manifest.mutable_install_operations(i) :
1333 manifest.mutable_kernel_install_operations(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001334 i - manifest.install_operations_size());
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001335 for (int j = 0; j < op->dst_extents_size(); j++) {
1336 const Extent& extent = op->dst_extents(j);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001337 for (uint64_t block = extent.start_block();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001338 block < (extent.start_block() + extent.num_blocks()); block++) {
Darin Petkovc0b7a532010-09-29 15:18:14 -07001339 if (block < blocks.size())
1340 written_count[block]++;
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001341 }
1342 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001343 if (op->has_data_offset()) {
1344 if (op->data_offset() != next_blob_offset) {
1345 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001346 << next_blob_offset;
1347 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001348 next_blob_offset += op->data_length();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001349 }
1350 }
1351 // check all blocks written to
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001352 for (vector<uint32_t>::size_type i = 0; i < written_count.size(); i++) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001353 if (written_count[i] == 0) {
1354 LOG(FATAL) << "block " << i << " not written!";
1355 }
1356 }
1357 }
1358
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001359 // Signatures appear at the end of the blobs. Note the offset in the
1360 // manifest
1361 if (!private_key_path.empty()) {
1362 LOG(INFO) << "Making room for signature in file";
1363 manifest.set_signatures_offset(next_blob_offset);
1364 LOG(INFO) << "set? " << manifest.has_signatures_offset();
1365 // Add a dummy op at the end to appease older clients
1366 DeltaArchiveManifest_InstallOperation* dummy_op =
1367 manifest.add_kernel_install_operations();
1368 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
1369 dummy_op->set_data_offset(next_blob_offset);
1370 manifest.set_signatures_offset(next_blob_offset);
1371 uint64_t signature_blob_length = 0;
1372 TEST_AND_RETURN_FALSE(
1373 PayloadSigner::SignatureBlobLength(private_key_path,
1374 &signature_blob_length));
1375 dummy_op->set_data_length(signature_blob_length);
1376 manifest.set_signatures_size(signature_blob_length);
1377 Extent* dummy_extent = dummy_op->add_dst_extents();
1378 // Tell the dummy op to write this data to a big sparse hole
1379 dummy_extent->set_start_block(kSparseHole);
1380 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
1381 kBlockSize);
1382 }
1383
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001384 // Serialize protobuf
1385 string serialized_manifest;
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001386
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001387 CheckGraph(graph);
1388 TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
1389 CheckGraph(graph);
1390
1391 LOG(INFO) << "Writing final delta file header...";
1392 DirectFileWriter writer;
1393 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(output_path.c_str(),
1394 O_WRONLY | O_CREAT | O_TRUNC,
1395 0644) == 0);
1396 ScopedFileWriterCloser writer_closer(&writer);
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001397
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001398 // Write header
1399 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)) ==
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07001400 static_cast<ssize_t>(strlen(kDeltaMagic)));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001401
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001402 // Write version number
1403 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kVersionNumber));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001404
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001405 // Write protobuf length
1406 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
1407 serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001408
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001409 // Write protobuf
1410 LOG(INFO) << "Writing final delta file protobuf... "
1411 << serialized_manifest.size();
1412 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
1413 serialized_manifest.size()) ==
1414 static_cast<ssize_t>(serialized_manifest.size()));
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001415
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001416 // Append the data blobs
1417 LOG(INFO) << "Writing final delta file data blobs...";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001418 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001419 ScopedFdCloser blobs_fd_closer(&blobs_fd);
1420 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
1421 for (;;) {
1422 char buf[kBlockSize];
1423 ssize_t rc = read(blobs_fd, buf, sizeof(buf));
1424 if (0 == rc) {
1425 // EOF
1426 break;
1427 }
1428 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
1429 TEST_AND_RETURN_FALSE(writer.Write(buf, rc) == rc);
1430 }
Andrew de los Reyes932bc4c2010-08-23 18:14:09 -07001431
1432 // Write signature blob.
1433 if (!private_key_path.empty()) {
1434 LOG(INFO) << "Signing the update...";
1435 vector<char> signature_blob;
1436 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(output_path,
1437 private_key_path,
1438 &signature_blob));
1439 TEST_AND_RETURN_FALSE(writer.Write(&signature_blob[0],
1440 signature_blob.size()) ==
1441 static_cast<ssize_t>(signature_blob.size()));
1442 }
1443
Darin Petkov880335c2010-10-01 15:52:53 -07001444 ReportPayloadUsage(graph, manifest);
1445
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001446 LOG(INFO) << "All done. Successfully created delta file.";
1447 return true;
1448}
1449
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001450const char* const kBsdiffPath = "/usr/bin/bsdiff";
1451const char* const kBspatchPath = "/usr/bin/bspatch";
1452const char* const kDeltaMagic = "CrAU";
1453
Andrew de los Reyesb10320d2010-03-31 16:44:44 -07001454}; // namespace chromeos_update_engine