forked from coreos/update_engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelta_diff_generator.cc
1679 lines (1500 loc) · 62.9 KB
/
delta_diff_generator.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "update_engine/delta_diff_generator.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <base/logging.h>
#include <base/memory/scoped_ptr.h>
#include <base/string_util.h>
#include <base/stringprintf.h>
#include <bzlib.h>
#include "update_engine/bzip.h"
#include "update_engine/cycle_breaker.h"
#include "update_engine/extent_mapper.h"
#include "update_engine/extent_ranges.h"
#include "update_engine/file_writer.h"
#include "update_engine/filesystem_iterator.h"
#include "update_engine/full_update_generator.h"
#include "update_engine/graph_types.h"
#include "update_engine/graph_utils.h"
#include "update_engine/metadata.h"
#include "update_engine/omaha_hash_calculator.h"
#include "update_engine/payload_signer.h"
#include "update_engine/subprocess.h"
#include "update_engine/topological_sort.h"
#include "update_engine/update_metadata.pb.h"
#include "update_engine/utils.h"
using std::make_pair;
using std::map;
using std::max;
using std::min;
using std::pair;
using std::set;
using std::string;
using std::vector;
namespace chromeos_update_engine {
typedef DeltaDiffGenerator::Block Block;
typedef map<const DeltaArchiveManifest_InstallOperation*,
const string*> OperationNameMap;
namespace {
const size_t kBlockSize = 4096; // bytes
const string kNonexistentPath = "";
// TODO(adlr): switch from 1GiB to 2GiB when we no longer care about old
// clients:
const size_t kRootFSPartitionSize = 1 * 1024 * 1024 * 1024; // bytes
const uint64_t kVersionNumber = 1;
const uint64_t kFullUpdateChunkSize = 1024 * 1024; // bytes
static const char* kInstallOperationTypes[] = {
"REPLACE",
"REPLACE_BZ",
"MOVE",
"BSDIFF"
};
// Stores all Extents for a file into 'out'. Returns true on success.
bool GatherExtents(const string& path,
google::protobuf::RepeatedPtrField<Extent>* out) {
vector<Extent> extents;
TEST_AND_RETURN_FALSE(extent_mapper::ExtentsForFileFibmap(path, &extents));
DeltaDiffGenerator::StoreExtents(extents, out);
return true;
}
// For a given regular file which must exist at new_root + path, and
// may exist at old_root + path, creates a new InstallOperation and
// adds it to the graph. Also, populates the |blocks| array as
// necessary, if |blocks| is non-NULL. Also, writes the data
// necessary to send the file down to the client into data_fd, which
// has length *data_file_size. *data_file_size is updated
// appropriately. If |existing_vertex| is no kInvalidIndex, use that
// rather than allocating a new vertex. Returns true on success.
bool DeltaReadFile(Graph* graph,
Vertex::Index existing_vertex,
vector<Block>* blocks,
const string& old_root,
const string& new_root,
const string& path, // within new_root
int data_fd,
off_t* data_file_size) {
vector<char> data;
DeltaArchiveManifest_InstallOperation operation;
string old_path = (old_root == kNonexistentPath) ? kNonexistentPath :
old_root + path;
// If bsdiff breaks again, blacklist the problem file by using:
// bsdiff_allowed = (path != "/foo/bar")
//
// TODO(dgarrett): chromium-os:15274 connect this test to the command line.
bool bsdiff_allowed = true;
if (!bsdiff_allowed)
LOG(INFO) << "bsdiff blacklisting: " << path;
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ReadFileToDiff(old_path,
new_root + path,
bsdiff_allowed,
&data,
&operation,
true));
// Write the data
if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
operation.set_data_offset(*data_file_size);
operation.set_data_length(data.size());
}
TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
*data_file_size += data.size();
// Now, insert into graph and blocks vector
Vertex::Index vertex = existing_vertex;
if (vertex == Vertex::kInvalidIndex) {
graph->resize(graph->size() + 1);
vertex = graph->size() - 1;
}
(*graph)[vertex].op = operation;
CHECK((*graph)[vertex].op.has_type());
(*graph)[vertex].file_name = path;
if (blocks)
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
(*graph)[vertex].op,
*graph,
vertex,
blocks));
return true;
}
// For each regular file within new_root, creates a node in the graph,
// determines the best way to compress it (REPLACE, REPLACE_BZ, COPY, BSDIFF),
// and writes any necessary data to the end of data_fd.
bool DeltaReadFiles(Graph* graph,
vector<Block>* blocks,
const string& old_root,
const string& new_root,
int data_fd,
off_t* data_file_size) {
set<ino_t> visited_inodes;
set<ino_t> visited_src_inodes;
for (FilesystemIterator fs_iter(new_root,
utils::SetWithValue<string>("/lost+found"));
!fs_iter.IsEnd(); fs_iter.Increment()) {
// We never diff symlinks (here, we check that dst file is not a symlink).
if (!S_ISREG(fs_iter.GetStat().st_mode))
continue;
// Make sure we visit each inode only once.
if (utils::SetContainsKey(visited_inodes, fs_iter.GetStat().st_ino))
continue;
visited_inodes.insert(fs_iter.GetStat().st_ino);
if (fs_iter.GetStat().st_size == 0)
continue;
LOG(INFO) << "Encoding file " << fs_iter.GetPartialPath();
// We can't visit each dst image inode more than once, as that would
// duplicate work. Here, we avoid visiting each source image inode
// more than once. Technically, we could have multiple operations
// that read the same blocks from the source image for diffing, but
// we choose not to to avoid complexity. Eventually we will move away
// from using a graph/cycle detection/etc to generate diffs, and at that
// time, it will be easy (non-complex) to have many operations read
// from the same source blocks. At that time, this code can die. -adlr
bool should_diff_from_source = false;
string src_path = old_root + fs_iter.GetPartialPath();
struct stat src_stbuf;
// We never diff symlinks (here, we check that src file is not a symlink).
if (0 == lstat(src_path.c_str(), &src_stbuf) &&
S_ISREG(src_stbuf.st_mode)) {
should_diff_from_source = !utils::SetContainsKey(visited_src_inodes,
src_stbuf.st_ino);
visited_src_inodes.insert(src_stbuf.st_ino);
}
TEST_AND_RETURN_FALSE(DeltaReadFile(graph,
Vertex::kInvalidIndex,
blocks,
(should_diff_from_source ?
old_root :
kNonexistentPath),
new_root,
fs_iter.GetPartialPath(),
data_fd,
data_file_size));
}
return true;
}
// This class allocates non-existent temp blocks, starting from
// kTempBlockStart. Other code is responsible for converting these
// temp blocks into real blocks, as the client can't read or write to
// these blocks.
class DummyExtentAllocator {
public:
explicit DummyExtentAllocator()
: next_block_(kTempBlockStart) {}
vector<Extent> Allocate(const uint64_t block_count) {
vector<Extent> ret(1);
ret[0].set_start_block(next_block_);
ret[0].set_num_blocks(block_count);
next_block_ += block_count;
return ret;
}
private:
uint64_t next_block_;
};
// Reads blocks from image_path that are not yet marked as being written
// in the blocks array. These blocks that remain are non-file-data blocks.
// In the future we might consider intelligent diffing between this data
// and data in the previous image, but for now we just bzip2 compress it
// and include it in the update.
// Creates a new node in the graph to write these blocks and writes the
// appropriate blob to blobs_fd. Reads and updates blobs_length;
bool ReadUnwrittenBlocks(const vector<Block>& blocks,
int blobs_fd,
off_t* blobs_length,
const string& image_path,
Vertex* vertex) {
vertex->file_name = "<rootfs-non-file-data>";
DeltaArchiveManifest_InstallOperation* out_op = &vertex->op;
int image_fd = open(image_path.c_str(), O_RDONLY, 000);
TEST_AND_RETURN_FALSE_ERRNO(image_fd >= 0);
ScopedFdCloser image_fd_closer(&image_fd);
string temp_file_path;
TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/CrAU_temp_data.XXXXXX",
&temp_file_path,
NULL));
FILE* file = fopen(temp_file_path.c_str(), "w");
TEST_AND_RETURN_FALSE(file);
int err = BZ_OK;
BZFILE* bz_file = BZ2_bzWriteOpen(&err,
file,
9, // max compression
0, // verbosity
0); // default work factor
TEST_AND_RETURN_FALSE(err == BZ_OK);
vector<Extent> extents;
vector<Block>::size_type block_count = 0;
LOG(INFO) << "Appending left over blocks to extents";
for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
if (blocks[i].writer != Vertex::kInvalidIndex)
continue;
if (blocks[i].reader != Vertex::kInvalidIndex) {
graph_utils::AddReadBeforeDep(vertex, blocks[i].reader, i);
}
graph_utils::AppendBlockToExtents(&extents, i);
block_count++;
}
// Code will handle 'buf' at any size that's a multiple of kBlockSize,
// so we arbitrarily set it to 1024 * kBlockSize.
vector<char> buf(1024 * kBlockSize);
LOG(INFO) << "Reading left over blocks";
vector<Block>::size_type blocks_copied_count = 0;
// For each extent in extents, write the data into BZ2_bzWrite which
// sends it to an output file.
// We use the temporary buffer 'buf' to hold the data, which may be
// smaller than the extent, so in that case we have to loop to get
// the extent's data (that's the inner while loop).
for (vector<Extent>::const_iterator it = extents.begin();
it != extents.end(); ++it) {
vector<Block>::size_type blocks_read = 0;
float printed_progress = -1;
while (blocks_read < it->num_blocks()) {
const int copy_block_cnt =
min(buf.size() / kBlockSize,
static_cast<vector<char>::size_type>(
it->num_blocks() - blocks_read));
ssize_t rc = pread(image_fd,
&buf[0],
copy_block_cnt * kBlockSize,
(it->start_block() + blocks_read) * kBlockSize);
TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
TEST_AND_RETURN_FALSE(static_cast<size_t>(rc) ==
copy_block_cnt * kBlockSize);
BZ2_bzWrite(&err, bz_file, &buf[0], copy_block_cnt * kBlockSize);
TEST_AND_RETURN_FALSE(err == BZ_OK);
blocks_read += copy_block_cnt;
blocks_copied_count += copy_block_cnt;
float current_progress =
static_cast<float>(blocks_copied_count) / block_count;
if (printed_progress + 0.1 < current_progress ||
blocks_copied_count == block_count) {
LOG(INFO) << "progress: " << current_progress;
printed_progress = current_progress;
}
}
}
BZ2_bzWriteClose(&err, bz_file, 0, NULL, NULL);
TEST_AND_RETURN_FALSE(err == BZ_OK);
bz_file = NULL;
TEST_AND_RETURN_FALSE_ERRNO(0 == fclose(file));
file = NULL;
vector<char> compressed_data;
LOG(INFO) << "Reading compressed data off disk";
TEST_AND_RETURN_FALSE(utils::ReadFile(temp_file_path, &compressed_data));
TEST_AND_RETURN_FALSE(unlink(temp_file_path.c_str()) == 0);
// Add node to graph to write these blocks
out_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
out_op->set_data_offset(*blobs_length);
out_op->set_data_length(compressed_data.size());
LOG(INFO) << "Rootfs non-data blocks compressed take up "
<< compressed_data.size();
*blobs_length += compressed_data.size();
out_op->set_dst_length(kBlockSize * block_count);
DeltaDiffGenerator::StoreExtents(extents, out_op->mutable_dst_extents());
TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd,
&compressed_data[0],
compressed_data.size()));
LOG(INFO) << "done with extra blocks";
return true;
}
// Writes the uint64_t passed in in host-endian to the file as big-endian.
// Returns true on success.
bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
uint64_t value_be = htobe64(value);
TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
return true;
}
// Adds each operation from |graph| to |out_manifest| in the order specified by
// |order| while building |out_op_name_map| with operation to name
// mappings. Adds all |kernel_ops| to |out_manifest|. Filters out no-op
// operations.
void InstallOperationsToManifest(
const Graph& graph,
const vector<Vertex::Index>& order,
const vector<DeltaArchiveManifest_InstallOperation>& kernel_ops,
DeltaArchiveManifest* out_manifest,
OperationNameMap* out_op_name_map) {
for (vector<Vertex::Index>::const_iterator it = order.begin();
it != order.end(); ++it) {
const Vertex& vertex = graph[*it];
const DeltaArchiveManifest_InstallOperation& add_op = vertex.op;
if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
continue;
}
DeltaArchiveManifest_InstallOperation* op =
out_manifest->add_install_operations();
*op = add_op;
(*out_op_name_map)[op] = &vertex.file_name;
}
for (vector<DeltaArchiveManifest_InstallOperation>::const_iterator it =
kernel_ops.begin(); it != kernel_ops.end(); ++it) {
const DeltaArchiveManifest_InstallOperation& add_op = *it;
if (DeltaDiffGenerator::IsNoopOperation(add_op)) {
continue;
}
DeltaArchiveManifest_InstallOperation* op =
out_manifest->add_kernel_install_operations();
*op = add_op;
}
}
void CheckGraph(const Graph& graph) {
for (Graph::const_iterator it = graph.begin(); it != graph.end(); ++it) {
CHECK(it->op.has_type());
}
}
// Delta compresses a kernel partition |new_kernel_part| with knowledge of the
// old kernel partition |old_kernel_part|. If |old_kernel_part| is an empty
// string, generates a full update of the partition.
bool DeltaCompressKernelPartition(
const string& old_kernel_part,
const string& new_kernel_part,
vector<DeltaArchiveManifest_InstallOperation>* ops,
int blobs_fd,
off_t* blobs_length) {
LOG(INFO) << "Delta compressing kernel partition...";
LOG_IF(INFO, old_kernel_part.empty()) << "Generating full kernel update...";
// Add a new install operation
ops->resize(1);
DeltaArchiveManifest_InstallOperation* op = &(*ops)[0];
vector<char> data;
TEST_AND_RETURN_FALSE(
DeltaDiffGenerator::ReadFileToDiff(old_kernel_part,
new_kernel_part,
true, // bsdiff_allowed
&data,
op,
false));
// Write the data
if (op->type() != DeltaArchiveManifest_InstallOperation_Type_MOVE) {
op->set_data_offset(*blobs_length);
op->set_data_length(data.size());
}
TEST_AND_RETURN_FALSE(utils::WriteAll(blobs_fd, &data[0], data.size()));
*blobs_length += data.size();
LOG(INFO) << "Done delta compressing kernel partition: "
<< kInstallOperationTypes[op->type()];
return true;
}
struct DeltaObject {
DeltaObject(const string& in_name, const int in_type, const off_t in_size)
: name(in_name),
type(in_type),
size(in_size) {}
bool operator <(const DeltaObject& object) const {
return (size != object.size) ? (size < object.size) : (name < object.name);
}
string name;
int type;
off_t size;
};
void ReportPayloadUsage(const DeltaArchiveManifest& manifest,
const int64_t manifest_metadata_size,
const OperationNameMap& op_name_map) {
vector<DeltaObject> objects;
off_t total_size = 0;
// Rootfs install operations.
for (int i = 0; i < manifest.install_operations_size(); ++i) {
const DeltaArchiveManifest_InstallOperation& op =
manifest.install_operations(i);
objects.push_back(DeltaObject(*op_name_map.find(&op)->second,
op.type(),
op.data_length()));
total_size += op.data_length();
}
// Kernel install operations.
for (int i = 0; i < manifest.kernel_install_operations_size(); ++i) {
const DeltaArchiveManifest_InstallOperation& op =
manifest.kernel_install_operations(i);
objects.push_back(DeltaObject(StringPrintf("<kernel-operation-%d>", i),
op.type(),
op.data_length()));
total_size += op.data_length();
}
objects.push_back(DeltaObject("<manifest-metadata>",
-1,
manifest_metadata_size));
total_size += manifest_metadata_size;
std::sort(objects.begin(), objects.end());
static const char kFormatString[] = "%6.2f%% %10llu %-10s %s\n";
for (vector<DeltaObject>::const_iterator it = objects.begin();
it != objects.end(); ++it) {
const DeltaObject& object = *it;
fprintf(stderr, kFormatString,
object.size * 100.0 / total_size,
object.size,
object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
object.name.c_str());
}
fprintf(stderr, kFormatString, 100.0, total_size, "", "<total>");
}
} // namespace {}
bool DeltaDiffGenerator::ReadFileToDiff(
const string& old_filename,
const string& new_filename,
bool bsdiff_allowed,
vector<char>* out_data,
DeltaArchiveManifest_InstallOperation* out_op,
bool gather_extents) {
// Read new data in
vector<char> new_data;
TEST_AND_RETURN_FALSE(utils::ReadFile(new_filename, &new_data));
TEST_AND_RETURN_FALSE(!new_data.empty());
vector<char> new_data_bz;
TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
CHECK(!new_data_bz.empty());
vector<char> data; // Data blob that will be written to delta file.
DeltaArchiveManifest_InstallOperation operation;
size_t current_best_size = 0;
if (new_data.size() <= new_data_bz.size()) {
operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
current_best_size = new_data.size();
data = new_data;
} else {
operation.set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
current_best_size = new_data_bz.size();
data = new_data_bz;
}
// Do we have an original file to consider?
struct stat old_stbuf;
bool original = !old_filename.empty();
if (original && 0 != stat(old_filename.c_str(), &old_stbuf)) {
// If stat-ing the old file fails, it should be because it doesn't exist.
TEST_AND_RETURN_FALSE(errno == ENOTDIR || errno == ENOENT);
original = false;
}
if (original) {
// Read old data
vector<char> old_data;
TEST_AND_RETURN_FALSE(utils::ReadFile(old_filename, &old_data));
if (old_data == new_data) {
// No change in data.
operation.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
current_best_size = 0;
data.clear();
} else if (bsdiff_allowed) {
// If the source file is considered bsdiff safe (no bsdiff bugs
// triggered), see if BSDIFF encoding is smaller.
vector<char> bsdiff_delta;
TEST_AND_RETURN_FALSE(
BsdiffFiles(old_filename, new_filename, &bsdiff_delta));
CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
if (bsdiff_delta.size() < current_best_size) {
operation.set_type(DeltaArchiveManifest_InstallOperation_Type_BSDIFF);
current_best_size = bsdiff_delta.size();
data = bsdiff_delta;
}
}
}
// Set parameters of the operations
CHECK_EQ(data.size(), current_best_size);
if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
operation.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
if (gather_extents) {
TEST_AND_RETURN_FALSE(
GatherExtents(old_filename, operation.mutable_src_extents()));
} else {
Extent* src_extent = operation.add_src_extents();
src_extent->set_start_block(0);
src_extent->set_num_blocks(
(old_stbuf.st_size + kBlockSize - 1) / kBlockSize);
}
operation.set_src_length(old_stbuf.st_size);
}
if (gather_extents) {
TEST_AND_RETURN_FALSE(
GatherExtents(new_filename, operation.mutable_dst_extents()));
} else {
Extent* dst_extent = operation.add_dst_extents();
dst_extent->set_start_block(0);
dst_extent->set_num_blocks((new_data.size() + kBlockSize - 1) / kBlockSize);
}
operation.set_dst_length(new_data.size());
out_data->swap(data);
*out_op = operation;
return true;
}
bool DeltaDiffGenerator::InitializePartitionInfo(bool is_kernel,
const string& partition,
PartitionInfo* info) {
int64_t size = 0;
if (is_kernel) {
size = utils::FileSize(partition);
} else {
int block_count = 0, block_size = 0;
TEST_AND_RETURN_FALSE(utils::GetFilesystemSize(partition,
&block_count,
&block_size));
size = static_cast<int64_t>(block_count) * block_size;
}
TEST_AND_RETURN_FALSE(size > 0);
info->set_size(size);
OmahaHashCalculator hasher;
TEST_AND_RETURN_FALSE(hasher.UpdateFile(partition, size) == size);
TEST_AND_RETURN_FALSE(hasher.Finalize());
const vector<char>& hash = hasher.raw_hash();
info->set_hash(hash.data(), hash.size());
LOG(INFO) << partition << ": size=" << size << " hash=" << hasher.hash();
return true;
}
bool InitializePartitionInfos(const string& old_kernel,
const string& new_kernel,
const string& old_rootfs,
const string& new_rootfs,
DeltaArchiveManifest* manifest) {
if (!old_kernel.empty()) {
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
true,
old_kernel,
manifest->mutable_old_kernel_info()));
}
if (!new_kernel.empty()) {
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
true,
new_kernel,
manifest->mutable_new_kernel_info()));
}
if (!old_rootfs.empty()) {
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
false,
old_rootfs,
manifest->mutable_old_rootfs_info()));
}
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::InitializePartitionInfo(
false,
new_rootfs,
manifest->mutable_new_rootfs_info()));
return true;
}
namespace {
// Takes a collection (vector or RepeatedPtrField) of Extent and
// returns a vector of the blocks referenced, in order.
template<typename T>
vector<uint64_t> ExpandExtents(const T& extents) {
vector<uint64_t> ret;
for (size_t i = 0, e = static_cast<size_t>(extents.size()); i != e; ++i) {
const Extent extent = graph_utils::GetElement(extents, i);
if (extent.start_block() == kSparseHole) {
ret.resize(ret.size() + extent.num_blocks(), kSparseHole);
} else {
for (uint64_t block = extent.start_block();
block < (extent.start_block() + extent.num_blocks()); block++) {
ret.push_back(block);
}
}
}
return ret;
}
// Takes a vector of blocks and returns an equivalent vector of Extent
// objects.
vector<Extent> CompressExtents(const vector<uint64_t>& blocks) {
vector<Extent> new_extents;
for (vector<uint64_t>::const_iterator it = blocks.begin(), e = blocks.end();
it != e; ++it) {
graph_utils::AppendBlockToExtents(&new_extents, *it);
}
return new_extents;
}
} // namespace {}
void DeltaDiffGenerator::SubstituteBlocks(
Vertex* vertex,
const vector<Extent>& remove_extents,
const vector<Extent>& replace_extents) {
// First, expand out the blocks that op reads from
vector<uint64_t> read_blocks = ExpandExtents(vertex->op.src_extents());
{
// Expand remove_extents and replace_extents
vector<uint64_t> remove_extents_expanded =
ExpandExtents(remove_extents);
vector<uint64_t> replace_extents_expanded =
ExpandExtents(replace_extents);
CHECK_EQ(remove_extents_expanded.size(), replace_extents_expanded.size());
map<uint64_t, uint64_t> conversion;
for (vector<uint64_t>::size_type i = 0;
i < replace_extents_expanded.size(); i++) {
conversion[remove_extents_expanded[i]] = replace_extents_expanded[i];
}
utils::ApplyMap(&read_blocks, conversion);
for (Vertex::EdgeMap::iterator it = vertex->out_edges.begin(),
e = vertex->out_edges.end(); it != e; ++it) {
vector<uint64_t> write_before_deps_expanded =
ExpandExtents(it->second.write_extents);
utils::ApplyMap(&write_before_deps_expanded, conversion);
it->second.write_extents = CompressExtents(write_before_deps_expanded);
}
}
// Convert read_blocks back to extents
vertex->op.clear_src_extents();
vector<Extent> new_extents = CompressExtents(read_blocks);
DeltaDiffGenerator::StoreExtents(new_extents,
vertex->op.mutable_src_extents());
}
bool DeltaDiffGenerator::CutEdges(Graph* graph,
const set<Edge>& edges,
vector<CutEdgeVertexes>* out_cuts) {
DummyExtentAllocator scratch_allocator;
vector<CutEdgeVertexes> cuts;
cuts.reserve(edges.size());
uint64_t scratch_blocks_used = 0;
for (set<Edge>::const_iterator it = edges.begin();
it != edges.end(); ++it) {
cuts.resize(cuts.size() + 1);
vector<Extent> old_extents =
(*graph)[it->first].out_edges[it->second].extents;
// Choose some scratch space
scratch_blocks_used += graph_utils::EdgeWeight(*graph, *it);
cuts.back().tmp_extents =
scratch_allocator.Allocate(graph_utils::EdgeWeight(*graph, *it));
// create vertex to copy original->scratch
cuts.back().new_vertex = graph->size();
graph->resize(graph->size() + 1);
cuts.back().old_src = it->first;
cuts.back().old_dst = it->second;
EdgeProperties& cut_edge_properties =
(*graph)[it->first].out_edges.find(it->second)->second;
// This should never happen, as we should only be cutting edges between
// real file nodes, and write-before relationships are created from
// a real file node to a temp copy node:
CHECK(cut_edge_properties.write_extents.empty())
<< "Can't cut edge that has write-before relationship.";
// make node depend on the copy operation
(*graph)[it->first].out_edges.insert(make_pair(graph->size() - 1,
cut_edge_properties));
// Set src/dst extents and other proto variables for copy operation
graph->back().op.set_type(DeltaArchiveManifest_InstallOperation_Type_MOVE);
DeltaDiffGenerator::StoreExtents(
cut_edge_properties.extents,
graph->back().op.mutable_src_extents());
DeltaDiffGenerator::StoreExtents(cuts.back().tmp_extents,
graph->back().op.mutable_dst_extents());
graph->back().op.set_src_length(
graph_utils::EdgeWeight(*graph, *it) * kBlockSize);
graph->back().op.set_dst_length(graph->back().op.src_length());
// make the dest node read from the scratch space
DeltaDiffGenerator::SubstituteBlocks(
&((*graph)[it->second]),
(*graph)[it->first].out_edges[it->second].extents,
cuts.back().tmp_extents);
// delete the old edge
CHECK_EQ(static_cast<Graph::size_type>(1),
(*graph)[it->first].out_edges.erase(it->second));
// Add an edge from dst to copy operation
EdgeProperties write_before_edge_properties;
write_before_edge_properties.write_extents = cuts.back().tmp_extents;
(*graph)[it->second].out_edges.insert(
make_pair(graph->size() - 1, write_before_edge_properties));
}
out_cuts->swap(cuts);
return true;
}
// Stores all Extents in 'extents' into 'out'.
void DeltaDiffGenerator::StoreExtents(
const vector<Extent>& extents,
google::protobuf::RepeatedPtrField<Extent>* out) {
for (vector<Extent>::const_iterator it = extents.begin();
it != extents.end(); ++it) {
Extent* new_extent = out->Add();
*new_extent = *it;
}
}
// Creates all the edges for the graph. Writers of a block point to
// readers of the same block. This is because for an edge A->B, B
// must complete before A executes.
void DeltaDiffGenerator::CreateEdges(Graph* graph,
const vector<Block>& blocks) {
for (vector<Block>::size_type i = 0; i < blocks.size(); i++) {
// Blocks with both a reader and writer get an edge
if (blocks[i].reader == Vertex::kInvalidIndex ||
blocks[i].writer == Vertex::kInvalidIndex)
continue;
// Don't have a node depend on itself
if (blocks[i].reader == blocks[i].writer)
continue;
// See if there's already an edge we can add onto
Vertex::EdgeMap::iterator edge_it =
(*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
if (edge_it == (*graph)[blocks[i].writer].out_edges.end()) {
// No existing edge. Create one
(*graph)[blocks[i].writer].out_edges.insert(
make_pair(blocks[i].reader, EdgeProperties()));
edge_it = (*graph)[blocks[i].writer].out_edges.find(blocks[i].reader);
CHECK(edge_it != (*graph)[blocks[i].writer].out_edges.end());
}
graph_utils::AppendBlockToExtents(&edge_it->second.extents, i);
}
}
namespace {
class SortCutsByTopoOrderLess {
public:
SortCutsByTopoOrderLess(vector<vector<Vertex::Index>::size_type>& table)
: table_(table) {}
bool operator()(const CutEdgeVertexes& a, const CutEdgeVertexes& b) {
return table_[a.old_dst] < table_[b.old_dst];
}
private:
vector<vector<Vertex::Index>::size_type>& table_;
};
} // namespace {}
void DeltaDiffGenerator::GenerateReverseTopoOrderMap(
vector<Vertex::Index>& op_indexes,
vector<vector<Vertex::Index>::size_type>* reverse_op_indexes) {
vector<vector<Vertex::Index>::size_type> table(op_indexes.size());
for (vector<Vertex::Index>::size_type i = 0, e = op_indexes.size();
i != e; ++i) {
Vertex::Index node = op_indexes[i];
if (table.size() < (node + 1)) {
table.resize(node + 1);
}
table[node] = i;
}
reverse_op_indexes->swap(table);
}
void DeltaDiffGenerator::SortCutsByTopoOrder(vector<Vertex::Index>& op_indexes,
vector<CutEdgeVertexes>* cuts) {
// first, make a reverse lookup table.
vector<vector<Vertex::Index>::size_type> table;
GenerateReverseTopoOrderMap(op_indexes, &table);
SortCutsByTopoOrderLess less(table);
sort(cuts->begin(), cuts->end(), less);
}
void DeltaDiffGenerator::MoveFullOpsToBack(Graph* graph,
vector<Vertex::Index>* op_indexes) {
vector<Vertex::Index> ret;
vector<Vertex::Index> full_ops;
ret.reserve(op_indexes->size());
for (vector<Vertex::Index>::size_type i = 0, e = op_indexes->size(); i != e;
++i) {
DeltaArchiveManifest_InstallOperation_Type type =
(*graph)[(*op_indexes)[i]].op.type();
if (type == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
type == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
full_ops.push_back((*op_indexes)[i]);
} else {
ret.push_back((*op_indexes)[i]);
}
}
LOG(INFO) << "Stats: " << full_ops.size() << " full ops out of "
<< (full_ops.size() + ret.size()) << " total ops.";
ret.insert(ret.end(), full_ops.begin(), full_ops.end());
op_indexes->swap(ret);
}
namespace {
template<typename T>
bool TempBlocksExistInExtents(const T& extents) {
for (int i = 0, e = extents.size(); i < e; ++i) {
Extent extent = graph_utils::GetElement(extents, i);
uint64_t start = extent.start_block();
uint64_t num = extent.num_blocks();
if (start == kSparseHole)
continue;
if (start >= kTempBlockStart ||
(start + num) >= kTempBlockStart) {
LOG(ERROR) << "temp block!";
LOG(ERROR) << "start: " << start << ", num: " << num;
LOG(ERROR) << "kTempBlockStart: " << kTempBlockStart;
LOG(ERROR) << "returning true";
return true;
}
// check for wrap-around, which would be a bug:
CHECK(start <= (start + num));
}
return false;
}
// Convertes the cuts, which must all have the same |old_dst| member,
// to full. It does this by converting the |old_dst| to REPLACE or
// REPLACE_BZ, dropping all incoming edges to |old_dst|, and marking
// all temp nodes invalid.
bool ConvertCutsToFull(
Graph* graph,
const string& new_root,
int data_fd,
off_t* data_file_size,
vector<Vertex::Index>* op_indexes,
vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
const vector<CutEdgeVertexes>& cuts) {
CHECK(!cuts.empty());
set<Vertex::Index> deleted_nodes;
for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
e = cuts.end(); it != e; ++it) {
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::ConvertCutToFullOp(
graph,
*it,
new_root,
data_fd,
data_file_size));
deleted_nodes.insert(it->new_vertex);
}
deleted_nodes.insert(cuts[0].old_dst);
vector<Vertex::Index> new_op_indexes;
new_op_indexes.reserve(op_indexes->size());
for (vector<Vertex::Index>::iterator it = op_indexes->begin(),
e = op_indexes->end(); it != e; ++it) {
if (utils::SetContainsKey(deleted_nodes, *it))
continue;
new_op_indexes.push_back(*it);
}
new_op_indexes.push_back(cuts[0].old_dst);
op_indexes->swap(new_op_indexes);
DeltaDiffGenerator::GenerateReverseTopoOrderMap(*op_indexes,
reverse_op_indexes);
return true;
}
// Tries to assign temp blocks for a collection of cuts, all of which share
// the same old_dst member. If temp blocks can't be found, old_dst will be
// converted to a REPLACE or REPLACE_BZ operation. Returns true on success,
// which can happen even if blocks are converted to full. Returns false
// on exceptional error cases.
bool AssignBlockForAdjoiningCuts(
Graph* graph,
const string& new_root,
int data_fd,
off_t* data_file_size,
vector<Vertex::Index>* op_indexes,
vector<vector<Vertex::Index>::size_type>* reverse_op_indexes,
const vector<CutEdgeVertexes>& cuts) {
CHECK(!cuts.empty());
const Vertex::Index old_dst = cuts[0].old_dst;
// Calculate # of blocks needed
uint64_t blocks_needed = 0;
map<const CutEdgeVertexes*, uint64_t> cuts_blocks_needed;
for (vector<CutEdgeVertexes>::const_iterator it = cuts.begin(),
e = cuts.end(); it != e; ++it) {
uint64_t cut_blocks_needed = 0;
for (vector<Extent>::const_iterator jt = it->tmp_extents.begin(),
je = it->tmp_extents.end(); jt != je; ++jt) {
cut_blocks_needed += jt->num_blocks();
}
blocks_needed += cut_blocks_needed;
cuts_blocks_needed[&*it] = cut_blocks_needed;
}
// Find enough blocks
ExtentRanges scratch_ranges;
// Each block that's supplying temp blocks and the corresponding blocks:
typedef vector<pair<Vertex::Index, ExtentRanges> > SupplierVector;
SupplierVector block_suppliers;
uint64_t scratch_blocks_found = 0;
for (vector<Vertex::Index>::size_type i = (*reverse_op_indexes)[old_dst] + 1,
e = op_indexes->size(); i < e; ++i) {
Vertex::Index test_node = (*op_indexes)[i];
if (!(*graph)[test_node].valid)
continue;
// See if this node has sufficient blocks
ExtentRanges ranges;
ranges.AddRepeatedExtents((*graph)[test_node].op.dst_extents());
ranges.SubtractExtent(ExtentForRange(
kTempBlockStart, kSparseHole - kTempBlockStart));
ranges.SubtractRepeatedExtents((*graph)[test_node].op.src_extents());
// For now, for simplicity, subtract out all blocks in read-before
// dependencies.
for (Vertex::EdgeMap::const_iterator edge_i =
(*graph)[test_node].out_edges.begin(),
edge_e = (*graph)[test_node].out_edges.end();
edge_i != edge_e; ++edge_i) {
ranges.SubtractExtents(edge_i->second.extents);
}
if (ranges.blocks() == 0)
continue;