blob: 75379cd496b4e20a146e7d196a44be7a22bf5b22 [file] [log] [blame]
Doug Zongker424296a2014-09-02 08:53:09 -07001# Copyright (C) 2014 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Doug Zongkerfc44a512014-08-26 13:10:25 -070015from __future__ import print_function
16
17from collections import deque, OrderedDict
18from hashlib import sha1
Doug Zongker62338182014-09-08 08:29:55 -070019import heapq
Doug Zongkerfc44a512014-08-26 13:10:25 -070020import itertools
21import multiprocessing
22import os
Doug Zongkerfc44a512014-08-26 13:10:25 -070023import re
24import subprocess
Doug Zongkerfc44a512014-08-26 13:10:25 -070025import threading
26import tempfile
27
Dan Albert8b72aef2015-03-23 19:13:21 -070028from rangelib import RangeSet
29
Doug Zongkerfc44a512014-08-26 13:10:25 -070030
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070031__all__ = ["EmptyImage", "DataImage", "BlockImageDiff"]
32
Dan Albert8b72aef2015-03-23 19:13:21 -070033
Doug Zongkerfc44a512014-08-26 13:10:25 -070034def compute_patch(src, tgt, imgdiff=False):
35 srcfd, srcfile = tempfile.mkstemp(prefix="src-")
36 tgtfd, tgtfile = tempfile.mkstemp(prefix="tgt-")
37 patchfd, patchfile = tempfile.mkstemp(prefix="patch-")
38 os.close(patchfd)
39
40 try:
41 with os.fdopen(srcfd, "wb") as f_src:
42 for p in src:
43 f_src.write(p)
44
45 with os.fdopen(tgtfd, "wb") as f_tgt:
46 for p in tgt:
47 f_tgt.write(p)
48 try:
49 os.unlink(patchfile)
50 except OSError:
51 pass
52 if imgdiff:
53 p = subprocess.call(["imgdiff", "-z", srcfile, tgtfile, patchfile],
54 stdout=open("/dev/null", "a"),
55 stderr=subprocess.STDOUT)
56 else:
57 p = subprocess.call(["bsdiff", srcfile, tgtfile, patchfile])
58
59 if p:
60 raise ValueError("diff failed: " + str(p))
61
62 with open(patchfile, "rb") as f:
63 return f.read()
64 finally:
65 try:
66 os.unlink(srcfile)
67 os.unlink(tgtfile)
68 os.unlink(patchfile)
69 except OSError:
70 pass
71
Dan Albert8b72aef2015-03-23 19:13:21 -070072
73class Image(object):
74 def ReadRangeSet(self, ranges):
75 raise NotImplementedError
76
77 def TotalSha1(self):
78 raise NotImplementedError
79
80
81class EmptyImage(Image):
Doug Zongkerfc44a512014-08-26 13:10:25 -070082 """A zero-length image."""
83 blocksize = 4096
84 care_map = RangeSet()
85 total_blocks = 0
86 file_map = {}
87 def ReadRangeSet(self, ranges):
88 return ()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070089 def TotalSha1(self):
90 return sha1().hexdigest()
91
92
Dan Albert8b72aef2015-03-23 19:13:21 -070093class DataImage(Image):
Doug Zongkerab7ca1d2014-08-26 10:40:28 -070094 """An image wrapped around a single string of data."""
95
96 def __init__(self, data, trim=False, pad=False):
97 self.data = data
98 self.blocksize = 4096
99
100 assert not (trim and pad)
101
102 partial = len(self.data) % self.blocksize
103 if partial > 0:
104 if trim:
105 self.data = self.data[:-partial]
106 elif pad:
107 self.data += '\0' * (self.blocksize - partial)
108 else:
109 raise ValueError(("data for DataImage must be multiple of %d bytes "
110 "unless trim or pad is specified") %
111 (self.blocksize,))
112
113 assert len(self.data) % self.blocksize == 0
114
115 self.total_blocks = len(self.data) / self.blocksize
116 self.care_map = RangeSet(data=(0, self.total_blocks))
117
118 zero_blocks = []
119 nonzero_blocks = []
120 reference = '\0' * self.blocksize
121
122 for i in range(self.total_blocks):
123 d = self.data[i*self.blocksize : (i+1)*self.blocksize]
124 if d == reference:
125 zero_blocks.append(i)
126 zero_blocks.append(i+1)
127 else:
128 nonzero_blocks.append(i)
129 nonzero_blocks.append(i+1)
130
131 self.file_map = {"__ZERO": RangeSet(zero_blocks),
132 "__NONZERO": RangeSet(nonzero_blocks)}
133
134 def ReadRangeSet(self, ranges):
135 return [self.data[s*self.blocksize:e*self.blocksize] for (s, e) in ranges]
136
137 def TotalSha1(self):
Dan Albert8b72aef2015-03-23 19:13:21 -0700138 return sha1(self.data).hexdigest()
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700139
Doug Zongkerfc44a512014-08-26 13:10:25 -0700140
141class Transfer(object):
142 def __init__(self, tgt_name, src_name, tgt_ranges, src_ranges, style, by_id):
143 self.tgt_name = tgt_name
144 self.src_name = src_name
145 self.tgt_ranges = tgt_ranges
146 self.src_ranges = src_ranges
147 self.style = style
148 self.intact = (getattr(tgt_ranges, "monotonic", False) and
149 getattr(src_ranges, "monotonic", False))
Tao Baob8c87172015-03-19 19:42:12 -0700150
151 # We use OrderedDict rather than dict so that the output is repeatable;
152 # otherwise it would depend on the hash values of the Transfer objects.
153 self.goes_before = OrderedDict()
154 self.goes_after = OrderedDict()
Doug Zongkerfc44a512014-08-26 13:10:25 -0700155
Doug Zongker62338182014-09-08 08:29:55 -0700156 self.stash_before = []
157 self.use_stash = []
158
Doug Zongkerfc44a512014-08-26 13:10:25 -0700159 self.id = len(by_id)
160 by_id.append(self)
161
Doug Zongker62338182014-09-08 08:29:55 -0700162 def NetStashChange(self):
163 return (sum(sr.size() for (_, sr) in self.stash_before) -
164 sum(sr.size() for (_, sr) in self.use_stash))
165
Doug Zongkerfc44a512014-08-26 13:10:25 -0700166 def __str__(self):
167 return (str(self.id) + ": <" + str(self.src_ranges) + " " + self.style +
168 " to " + str(self.tgt_ranges) + ">")
169
170
171# BlockImageDiff works on two image objects. An image object is
172# anything that provides the following attributes:
173#
174# blocksize: the size in bytes of a block, currently must be 4096.
175#
176# total_blocks: the total size of the partition/image, in blocks.
177#
178# care_map: a RangeSet containing which blocks (in the range [0,
179# total_blocks) we actually care about; i.e. which blocks contain
180# data.
181#
182# file_map: a dict that partitions the blocks contained in care_map
183# into smaller domains that are useful for doing diffs on.
184# (Typically a domain is a file, and the key in file_map is the
185# pathname.)
186#
187# ReadRangeSet(): a function that takes a RangeSet and returns the
188# data contained in the image blocks of that RangeSet. The data
189# is returned as a list or tuple of strings; concatenating the
190# elements together should produce the requested data.
191# Implementations are free to break up the data into list/tuple
192# elements in any way that is convenient.
193#
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700194# TotalSha1(): a function that returns (as a hex string) the SHA-1
195# hash of all the data in the image (ie, all the blocks in the
196# care_map)
197#
Doug Zongkerfc44a512014-08-26 13:10:25 -0700198# When creating a BlockImageDiff, the src image may be None, in which
199# case the list of transfers produced will never read from the
200# original image.
201
202class BlockImageDiff(object):
Sami Tolvanendd67a292014-12-09 16:40:34 +0000203 def __init__(self, tgt, src=None, threads=None, version=3):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700204 if threads is None:
205 threads = multiprocessing.cpu_count() // 2
Dan Albert8b72aef2015-03-23 19:13:21 -0700206 if threads == 0:
207 threads = 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700208 self.threads = threads
Doug Zongker62338182014-09-08 08:29:55 -0700209 self.version = version
Dan Albert8b72aef2015-03-23 19:13:21 -0700210 self.transfers = []
211 self.src_basenames = {}
212 self.src_numpatterns = {}
Doug Zongker62338182014-09-08 08:29:55 -0700213
Sami Tolvanendd67a292014-12-09 16:40:34 +0000214 assert version in (1, 2, 3)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700215
216 self.tgt = tgt
217 if src is None:
218 src = EmptyImage()
219 self.src = src
220
221 # The updater code that installs the patch always uses 4k blocks.
222 assert tgt.blocksize == 4096
223 assert src.blocksize == 4096
224
225 # The range sets in each filemap should comprise a partition of
226 # the care map.
227 self.AssertPartition(src.care_map, src.file_map.values())
228 self.AssertPartition(tgt.care_map, tgt.file_map.values())
229
230 def Compute(self, prefix):
231 # When looking for a source file to use as the diff input for a
232 # target file, we try:
233 # 1) an exact path match if available, otherwise
234 # 2) a exact basename match if available, otherwise
235 # 3) a basename match after all runs of digits are replaced by
236 # "#" if available, otherwise
237 # 4) we have no source for this target.
238 self.AbbreviateSourceNames()
239 self.FindTransfers()
240
241 # Find the ordering dependencies among transfers (this is O(n^2)
242 # in the number of transfers).
243 self.GenerateDigraph()
244 # Find a sequence of transfers that satisfies as many ordering
245 # dependencies as possible (heuristically).
246 self.FindVertexSequence()
247 # Fix up the ordering dependencies that the sequence didn't
248 # satisfy.
Doug Zongker62338182014-09-08 08:29:55 -0700249 if self.version == 1:
250 self.RemoveBackwardEdges()
251 else:
252 self.ReverseBackwardEdges()
253 self.ImproveVertexSequence()
254
Doug Zongkerfc44a512014-08-26 13:10:25 -0700255 # Double-check our work.
256 self.AssertSequenceGood()
257
258 self.ComputePatches(prefix)
259 self.WriteTransfers(prefix)
260
Dan Albert8b72aef2015-03-23 19:13:21 -0700261 def HashBlocks(self, source, ranges): # pylint: disable=no-self-use
Sami Tolvanendd67a292014-12-09 16:40:34 +0000262 data = source.ReadRangeSet(ranges)
263 ctx = sha1()
264
265 for p in data:
266 ctx.update(p)
267
268 return ctx.hexdigest()
269
Doug Zongkerfc44a512014-08-26 13:10:25 -0700270 def WriteTransfers(self, prefix):
271 out = []
272
Doug Zongkerfc44a512014-08-26 13:10:25 -0700273 total = 0
274 performs_read = False
275
Doug Zongker62338182014-09-08 08:29:55 -0700276 stashes = {}
277 stashed_blocks = 0
278 max_stashed_blocks = 0
279
280 free_stash_ids = []
281 next_stash_id = 0
282
Doug Zongkerfc44a512014-08-26 13:10:25 -0700283 for xf in self.transfers:
284
Doug Zongker62338182014-09-08 08:29:55 -0700285 if self.version < 2:
286 assert not xf.stash_before
287 assert not xf.use_stash
288
289 for s, sr in xf.stash_before:
290 assert s not in stashes
291 if free_stash_ids:
292 sid = heapq.heappop(free_stash_ids)
293 else:
294 sid = next_stash_id
295 next_stash_id += 1
296 stashes[s] = sid
297 stashed_blocks += sr.size()
Sami Tolvanendd67a292014-12-09 16:40:34 +0000298 if self.version == 2:
299 out.append("stash %d %s\n" % (sid, sr.to_string_raw()))
300 else:
301 sh = self.HashBlocks(self.src, sr)
302 if sh in stashes:
303 stashes[sh] += 1
304 else:
305 stashes[sh] = 1
306 out.append("stash %s %s\n" % (sh, sr.to_string_raw()))
Doug Zongker62338182014-09-08 08:29:55 -0700307
308 if stashed_blocks > max_stashed_blocks:
309 max_stashed_blocks = stashed_blocks
310
Jesse Zhao7b985f62015-03-02 16:53:08 -0800311 free_string = []
312
Doug Zongker62338182014-09-08 08:29:55 -0700313 if self.version == 1:
Dan Albert8b72aef2015-03-23 19:13:21 -0700314 src_str = xf.src_ranges.to_string_raw()
Sami Tolvanendd67a292014-12-09 16:40:34 +0000315 elif self.version >= 2:
Doug Zongker62338182014-09-08 08:29:55 -0700316
317 # <# blocks> <src ranges>
318 # OR
319 # <# blocks> <src ranges> <src locs> <stash refs...>
320 # OR
321 # <# blocks> - <stash refs...>
322
323 size = xf.src_ranges.size()
Dan Albert8b72aef2015-03-23 19:13:21 -0700324 src_str = [str(size)]
Doug Zongker62338182014-09-08 08:29:55 -0700325
326 unstashed_src_ranges = xf.src_ranges
327 mapped_stashes = []
328 for s, sr in xf.use_stash:
329 sid = stashes.pop(s)
330 stashed_blocks -= sr.size()
331 unstashed_src_ranges = unstashed_src_ranges.subtract(sr)
Sami Tolvanendd67a292014-12-09 16:40:34 +0000332 sh = self.HashBlocks(self.src, sr)
Doug Zongker62338182014-09-08 08:29:55 -0700333 sr = xf.src_ranges.map_within(sr)
334 mapped_stashes.append(sr)
Sami Tolvanendd67a292014-12-09 16:40:34 +0000335 if self.version == 2:
Dan Albert8b72aef2015-03-23 19:13:21 -0700336 src_str.append("%d:%s" % (sid, sr.to_string_raw()))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000337 else:
338 assert sh in stashes
Dan Albert8b72aef2015-03-23 19:13:21 -0700339 src_str.append("%s:%s" % (sh, sr.to_string_raw()))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000340 stashes[sh] -= 1
341 if stashes[sh] == 0:
342 free_string.append("free %s\n" % (sh))
343 stashes.pop(sh)
Doug Zongker62338182014-09-08 08:29:55 -0700344 heapq.heappush(free_stash_ids, sid)
345
346 if unstashed_src_ranges:
Dan Albert8b72aef2015-03-23 19:13:21 -0700347 src_str.insert(1, unstashed_src_ranges.to_string_raw())
Doug Zongker62338182014-09-08 08:29:55 -0700348 if xf.use_stash:
349 mapped_unstashed = xf.src_ranges.map_within(unstashed_src_ranges)
Dan Albert8b72aef2015-03-23 19:13:21 -0700350 src_str.insert(2, mapped_unstashed.to_string_raw())
Doug Zongker62338182014-09-08 08:29:55 -0700351 mapped_stashes.append(mapped_unstashed)
352 self.AssertPartition(RangeSet(data=(0, size)), mapped_stashes)
353 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700354 src_str.insert(1, "-")
Doug Zongker62338182014-09-08 08:29:55 -0700355 self.AssertPartition(RangeSet(data=(0, size)), mapped_stashes)
356
Dan Albert8b72aef2015-03-23 19:13:21 -0700357 src_str = " ".join(src_str)
Doug Zongker62338182014-09-08 08:29:55 -0700358
Sami Tolvanendd67a292014-12-09 16:40:34 +0000359 # all versions:
Doug Zongker62338182014-09-08 08:29:55 -0700360 # zero <rangeset>
361 # new <rangeset>
362 # erase <rangeset>
363 #
364 # version 1:
365 # bsdiff patchstart patchlen <src rangeset> <tgt rangeset>
366 # imgdiff patchstart patchlen <src rangeset> <tgt rangeset>
367 # move <src rangeset> <tgt rangeset>
368 #
369 # version 2:
Dan Albert8b72aef2015-03-23 19:13:21 -0700370 # bsdiff patchstart patchlen <tgt rangeset> <src_str>
371 # imgdiff patchstart patchlen <tgt rangeset> <src_str>
372 # move <tgt rangeset> <src_str>
Sami Tolvanendd67a292014-12-09 16:40:34 +0000373 #
374 # version 3:
Dan Albert8b72aef2015-03-23 19:13:21 -0700375 # bsdiff patchstart patchlen srchash tgthash <tgt rangeset> <src_str>
376 # imgdiff patchstart patchlen srchash tgthash <tgt rangeset> <src_str>
377 # move hash <tgt rangeset> <src_str>
Doug Zongkerfc44a512014-08-26 13:10:25 -0700378
379 tgt_size = xf.tgt_ranges.size()
380
381 if xf.style == "new":
382 assert xf.tgt_ranges
383 out.append("%s %s\n" % (xf.style, xf.tgt_ranges.to_string_raw()))
384 total += tgt_size
385 elif xf.style == "move":
386 performs_read = True
387 assert xf.tgt_ranges
388 assert xf.src_ranges.size() == tgt_size
389 if xf.src_ranges != xf.tgt_ranges:
Doug Zongker62338182014-09-08 08:29:55 -0700390 if self.version == 1:
391 out.append("%s %s %s\n" % (
392 xf.style,
393 xf.src_ranges.to_string_raw(), xf.tgt_ranges.to_string_raw()))
394 elif self.version == 2:
395 out.append("%s %s %s\n" % (
396 xf.style,
Dan Albert8b72aef2015-03-23 19:13:21 -0700397 xf.tgt_ranges.to_string_raw(), src_str))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000398 elif self.version >= 3:
399 out.append("%s %s %s %s\n" % (
400 xf.style,
401 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700402 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700403 total += tgt_size
404 elif xf.style in ("bsdiff", "imgdiff"):
405 performs_read = True
406 assert xf.tgt_ranges
407 assert xf.src_ranges
Doug Zongker62338182014-09-08 08:29:55 -0700408 if self.version == 1:
409 out.append("%s %d %d %s %s\n" % (
410 xf.style, xf.patch_start, xf.patch_len,
411 xf.src_ranges.to_string_raw(), xf.tgt_ranges.to_string_raw()))
412 elif self.version == 2:
413 out.append("%s %d %d %s %s\n" % (
414 xf.style, xf.patch_start, xf.patch_len,
Dan Albert8b72aef2015-03-23 19:13:21 -0700415 xf.tgt_ranges.to_string_raw(), src_str))
Sami Tolvanendd67a292014-12-09 16:40:34 +0000416 elif self.version >= 3:
417 out.append("%s %d %d %s %s %s %s\n" % (
418 xf.style,
419 xf.patch_start, xf.patch_len,
420 self.HashBlocks(self.src, xf.src_ranges),
421 self.HashBlocks(self.tgt, xf.tgt_ranges),
Dan Albert8b72aef2015-03-23 19:13:21 -0700422 xf.tgt_ranges.to_string_raw(), src_str))
Doug Zongkerfc44a512014-08-26 13:10:25 -0700423 total += tgt_size
424 elif xf.style == "zero":
425 assert xf.tgt_ranges
426 to_zero = xf.tgt_ranges.subtract(xf.src_ranges)
427 if to_zero:
428 out.append("%s %s\n" % (xf.style, to_zero.to_string_raw()))
429 total += to_zero.size()
430 else:
Dan Albert8b72aef2015-03-23 19:13:21 -0700431 raise ValueError("unknown transfer style '%s'\n" % xf.style)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700432
Sami Tolvanendd67a292014-12-09 16:40:34 +0000433 if free_string:
434 out.append("".join(free_string))
435
Doug Zongker62338182014-09-08 08:29:55 -0700436
437 # sanity check: abort if we're going to need more than 512 MB if
438 # stash space
439 assert max_stashed_blocks * self.tgt.blocksize < (512 << 20)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700440
441 all_tgt = RangeSet(data=(0, self.tgt.total_blocks))
442 if performs_read:
443 # if some of the original data is used, then at the end we'll
444 # erase all the blocks on the partition that don't contain data
445 # in the new image.
446 new_dontcare = all_tgt.subtract(self.tgt.care_map)
447 if new_dontcare:
448 out.append("erase %s\n" % (new_dontcare.to_string_raw(),))
449 else:
450 # if nothing is read (ie, this is a full OTA), then we can start
451 # by erasing the entire partition.
Doug Zongkere985f6f2014-09-09 12:38:47 -0700452 out.insert(0, "erase %s\n" % (all_tgt.to_string_raw(),))
453
454 out.insert(0, "%d\n" % (self.version,)) # format version number
455 out.insert(1, str(total) + "\n")
456 if self.version >= 2:
457 # version 2 only: after the total block count, we give the number
458 # of stash slots needed, and the maximum size needed (in blocks)
459 out.insert(2, str(next_stash_id) + "\n")
460 out.insert(3, str(max_stashed_blocks) + "\n")
Doug Zongkerfc44a512014-08-26 13:10:25 -0700461
462 with open(prefix + ".transfer.list", "wb") as f:
463 for i in out:
464 f.write(i)
465
Doug Zongker62338182014-09-08 08:29:55 -0700466 if self.version >= 2:
467 print("max stashed blocks: %d (%d bytes)\n" % (
468 max_stashed_blocks, max_stashed_blocks * self.tgt.blocksize))
469
Doug Zongkerfc44a512014-08-26 13:10:25 -0700470 def ComputePatches(self, prefix):
471 print("Reticulating splines...")
472 diff_q = []
473 patch_num = 0
474 with open(prefix + ".new.dat", "wb") as new_f:
475 for xf in self.transfers:
476 if xf.style == "zero":
477 pass
478 elif xf.style == "new":
479 for piece in self.tgt.ReadRangeSet(xf.tgt_ranges):
480 new_f.write(piece)
481 elif xf.style == "diff":
482 src = self.src.ReadRangeSet(xf.src_ranges)
483 tgt = self.tgt.ReadRangeSet(xf.tgt_ranges)
484
485 # We can't compare src and tgt directly because they may have
486 # the same content but be broken up into blocks differently, eg:
487 #
488 # ["he", "llo"] vs ["h", "ello"]
489 #
490 # We want those to compare equal, ideally without having to
491 # actually concatenate the strings (these may be tens of
492 # megabytes).
493
494 src_sha1 = sha1()
495 for p in src:
496 src_sha1.update(p)
497 tgt_sha1 = sha1()
498 tgt_size = 0
499 for p in tgt:
500 tgt_sha1.update(p)
501 tgt_size += len(p)
502
503 if src_sha1.digest() == tgt_sha1.digest():
504 # These are identical; we don't need to generate a patch,
505 # just issue copy commands on the device.
506 xf.style = "move"
507 else:
508 # For files in zip format (eg, APKs, JARs, etc.) we would
509 # like to use imgdiff -z if possible (because it usually
510 # produces significantly smaller patches than bsdiff).
511 # This is permissible if:
512 #
513 # - the source and target files are monotonic (ie, the
514 # data is stored with blocks in increasing order), and
515 # - we haven't removed any blocks from the source set.
516 #
517 # If these conditions are satisfied then appending all the
518 # blocks in the set together in order will produce a valid
519 # zip file (plus possibly extra zeros in the last block),
520 # which is what imgdiff needs to operate. (imgdiff is
521 # fine with extra zeros at the end of the file.)
522 imgdiff = (xf.intact and
523 xf.tgt_name.split(".")[-1].lower()
524 in ("apk", "jar", "zip"))
525 xf.style = "imgdiff" if imgdiff else "bsdiff"
526 diff_q.append((tgt_size, src, tgt, xf, patch_num))
527 patch_num += 1
528
529 else:
530 assert False, "unknown style " + xf.style
531
532 if diff_q:
533 if self.threads > 1:
534 print("Computing patches (using %d threads)..." % (self.threads,))
535 else:
536 print("Computing patches...")
537 diff_q.sort()
538
539 patches = [None] * patch_num
540
Dan Albert8b72aef2015-03-23 19:13:21 -0700541 # TODO: Rewrite with multiprocessing.ThreadPool?
Doug Zongkerfc44a512014-08-26 13:10:25 -0700542 lock = threading.Lock()
543 def diff_worker():
544 while True:
545 with lock:
Dan Albert8b72aef2015-03-23 19:13:21 -0700546 if not diff_q:
547 return
Doug Zongkerfc44a512014-08-26 13:10:25 -0700548 tgt_size, src, tgt, xf, patchnum = diff_q.pop()
549 patch = compute_patch(src, tgt, imgdiff=(xf.style == "imgdiff"))
550 size = len(patch)
551 with lock:
552 patches[patchnum] = (patch, xf)
553 print("%10d %10d (%6.2f%%) %7s %s" % (
554 size, tgt_size, size * 100.0 / tgt_size, xf.style,
555 xf.tgt_name if xf.tgt_name == xf.src_name else (
556 xf.tgt_name + " (from " + xf.src_name + ")")))
557
558 threads = [threading.Thread(target=diff_worker)
Dan Albert8b72aef2015-03-23 19:13:21 -0700559 for _ in range(self.threads)]
Doug Zongkerfc44a512014-08-26 13:10:25 -0700560 for th in threads:
561 th.start()
562 while threads:
563 threads.pop().join()
564 else:
565 patches = []
566
567 p = 0
568 with open(prefix + ".patch.dat", "wb") as patch_f:
569 for patch, xf in patches:
570 xf.patch_start = p
571 xf.patch_len = len(patch)
572 patch_f.write(patch)
573 p += len(patch)
574
575 def AssertSequenceGood(self):
576 # Simulate the sequences of transfers we will output, and check that:
577 # - we never read a block after writing it, and
578 # - we write every block we care about exactly once.
579
580 # Start with no blocks having been touched yet.
581 touched = RangeSet()
582
583 # Imagine processing the transfers in order.
584 for xf in self.transfers:
585 # Check that the input blocks for this transfer haven't yet been touched.
Doug Zongker62338182014-09-08 08:29:55 -0700586
587 x = xf.src_ranges
588 if self.version >= 2:
589 for _, sr in xf.use_stash:
590 x = x.subtract(sr)
591
592 assert not touched.overlaps(x)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700593 # Check that the output blocks for this transfer haven't yet been touched.
594 assert not touched.overlaps(xf.tgt_ranges)
595 # Touch all the blocks written by this transfer.
596 touched = touched.union(xf.tgt_ranges)
597
598 # Check that we've written every target block.
599 assert touched == self.tgt.care_map
600
Doug Zongker62338182014-09-08 08:29:55 -0700601 def ImproveVertexSequence(self):
602 print("Improving vertex order...")
603
604 # At this point our digraph is acyclic; we reversed any edges that
605 # were backwards in the heuristically-generated sequence. The
606 # previously-generated order is still acceptable, but we hope to
607 # find a better order that needs less memory for stashed data.
608 # Now we do a topological sort to generate a new vertex order,
609 # using a greedy algorithm to choose which vertex goes next
610 # whenever we have a choice.
611
612 # Make a copy of the edge set; this copy will get destroyed by the
613 # algorithm.
614 for xf in self.transfers:
615 xf.incoming = xf.goes_after.copy()
616 xf.outgoing = xf.goes_before.copy()
617
618 L = [] # the new vertex order
619
620 # S is the set of sources in the remaining graph; we always choose
621 # the one that leaves the least amount of stashed data after it's
622 # executed.
623 S = [(u.NetStashChange(), u.order, u) for u in self.transfers
624 if not u.incoming]
625 heapq.heapify(S)
626
627 while S:
628 _, _, xf = heapq.heappop(S)
629 L.append(xf)
630 for u in xf.outgoing:
631 del u.incoming[xf]
632 if not u.incoming:
633 heapq.heappush(S, (u.NetStashChange(), u.order, u))
634
635 # if this fails then our graph had a cycle.
636 assert len(L) == len(self.transfers)
637
638 self.transfers = L
639 for i, xf in enumerate(L):
640 xf.order = i
641
Doug Zongkerfc44a512014-08-26 13:10:25 -0700642 def RemoveBackwardEdges(self):
643 print("Removing backward edges...")
644 in_order = 0
645 out_of_order = 0
646 lost_source = 0
647
648 for xf in self.transfers:
Doug Zongkerfc44a512014-08-26 13:10:25 -0700649 lost = 0
650 size = xf.src_ranges.size()
651 for u in xf.goes_before:
652 # xf should go before u
653 if xf.order < u.order:
654 # it does, hurray!
Doug Zongker62338182014-09-08 08:29:55 -0700655 in_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700656 else:
657 # it doesn't, boo. trim the blocks that u writes from xf's
658 # source, so that xf can go after u.
Doug Zongker62338182014-09-08 08:29:55 -0700659 out_of_order += 1
Doug Zongkerfc44a512014-08-26 13:10:25 -0700660 assert xf.src_ranges.overlaps(u.tgt_ranges)
661 xf.src_ranges = xf.src_ranges.subtract(u.tgt_ranges)
662 xf.intact = False
663
664 if xf.style == "diff" and not xf.src_ranges:
665 # nothing left to diff from; treat as new data
666 xf.style = "new"
667
668 lost = size - xf.src_ranges.size()
669 lost_source += lost
Doug Zongkerfc44a512014-08-26 13:10:25 -0700670
671 print((" %d/%d dependencies (%.2f%%) were violated; "
672 "%d source blocks removed.") %
673 (out_of_order, in_order + out_of_order,
674 (out_of_order * 100.0 / (in_order + out_of_order))
675 if (in_order + out_of_order) else 0.0,
676 lost_source))
677
Doug Zongker62338182014-09-08 08:29:55 -0700678 def ReverseBackwardEdges(self):
679 print("Reversing backward edges...")
680 in_order = 0
681 out_of_order = 0
682 stashes = 0
683 stash_size = 0
684
685 for xf in self.transfers:
Doug Zongker62338182014-09-08 08:29:55 -0700686 for u in xf.goes_before.copy():
687 # xf should go before u
688 if xf.order < u.order:
689 # it does, hurray!
690 in_order += 1
691 else:
692 # it doesn't, boo. modify u to stash the blocks that it
693 # writes that xf wants to read, and then require u to go
694 # before xf.
695 out_of_order += 1
696
697 overlap = xf.src_ranges.intersect(u.tgt_ranges)
698 assert overlap
699
700 u.stash_before.append((stashes, overlap))
701 xf.use_stash.append((stashes, overlap))
702 stashes += 1
703 stash_size += overlap.size()
704
705 # reverse the edge direction; now xf must go after u
706 del xf.goes_before[u]
707 del u.goes_after[xf]
708 xf.goes_after[u] = None # value doesn't matter
709 u.goes_before[xf] = None
710
711 print((" %d/%d dependencies (%.2f%%) were violated; "
712 "%d source blocks stashed.") %
713 (out_of_order, in_order + out_of_order,
714 (out_of_order * 100.0 / (in_order + out_of_order))
715 if (in_order + out_of_order) else 0.0,
716 stash_size))
717
Doug Zongkerfc44a512014-08-26 13:10:25 -0700718 def FindVertexSequence(self):
719 print("Finding vertex sequence...")
720
721 # This is based on "A Fast & Effective Heuristic for the Feedback
722 # Arc Set Problem" by P. Eades, X. Lin, and W.F. Smyth. Think of
723 # it as starting with the digraph G and moving all the vertices to
724 # be on a horizontal line in some order, trying to minimize the
725 # number of edges that end up pointing to the left. Left-pointing
726 # edges will get removed to turn the digraph into a DAG. In this
727 # case each edge has a weight which is the number of source blocks
728 # we'll lose if that edge is removed; we try to minimize the total
729 # weight rather than just the number of edges.
730
731 # Make a copy of the edge set; this copy will get destroyed by the
732 # algorithm.
733 for xf in self.transfers:
734 xf.incoming = xf.goes_after.copy()
735 xf.outgoing = xf.goes_before.copy()
736
737 # We use an OrderedDict instead of just a set so that the output
738 # is repeatable; otherwise it would depend on the hash values of
739 # the transfer objects.
740 G = OrderedDict()
741 for xf in self.transfers:
742 G[xf] = None
743 s1 = deque() # the left side of the sequence, built from left to right
744 s2 = deque() # the right side of the sequence, built from right to left
745
746 while G:
747
748 # Put all sinks at the end of the sequence.
749 while True:
750 sinks = [u for u in G if not u.outgoing]
Dan Albert8b72aef2015-03-23 19:13:21 -0700751 if not sinks:
752 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700753 for u in sinks:
754 s2.appendleft(u)
755 del G[u]
756 for iu in u.incoming:
757 del iu.outgoing[u]
758
759 # Put all the sources at the beginning of the sequence.
760 while True:
761 sources = [u for u in G if not u.incoming]
Dan Albert8b72aef2015-03-23 19:13:21 -0700762 if not sources:
763 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700764 for u in sources:
765 s1.append(u)
766 del G[u]
767 for iu in u.outgoing:
768 del iu.incoming[u]
769
Dan Albert8b72aef2015-03-23 19:13:21 -0700770 if not G:
771 break
Doug Zongkerfc44a512014-08-26 13:10:25 -0700772
773 # Find the "best" vertex to put next. "Best" is the one that
774 # maximizes the net difference in source blocks saved we get by
775 # pretending it's a source rather than a sink.
776
777 max_d = None
778 best_u = None
779 for u in G:
780 d = sum(u.outgoing.values()) - sum(u.incoming.values())
781 if best_u is None or d > max_d:
782 max_d = d
783 best_u = u
784
785 u = best_u
786 s1.append(u)
787 del G[u]
788 for iu in u.outgoing:
789 del iu.incoming[u]
790 for iu in u.incoming:
791 del iu.outgoing[u]
792
793 # Now record the sequence in the 'order' field of each transfer,
794 # and by rearranging self.transfers to be in the chosen sequence.
795
796 new_transfers = []
797 for x in itertools.chain(s1, s2):
798 x.order = len(new_transfers)
799 new_transfers.append(x)
800 del x.incoming
801 del x.outgoing
802
803 self.transfers = new_transfers
804
805 def GenerateDigraph(self):
806 print("Generating digraph...")
807 for a in self.transfers:
808 for b in self.transfers:
Dan Albert8b72aef2015-03-23 19:13:21 -0700809 if a is b:
810 continue
Doug Zongkerfc44a512014-08-26 13:10:25 -0700811
812 # If the blocks written by A are read by B, then B needs to go before A.
813 i = a.tgt_ranges.intersect(b.src_ranges)
814 if i:
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700815 if b.src_name == "__ZERO":
816 # the cost of removing source blocks for the __ZERO domain
817 # is (nearly) zero.
818 size = 0
819 else:
820 size = i.size()
Doug Zongkerfc44a512014-08-26 13:10:25 -0700821 b.goes_before[a] = size
822 a.goes_after[b] = size
823
824 def FindTransfers(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700825 empty = RangeSet()
826 for tgt_fn, tgt_ranges in self.tgt.file_map.items():
827 if tgt_fn == "__ZERO":
828 # the special "__ZERO" domain is all the blocks not contained
829 # in any file and that are filled with zeros. We have a
830 # special transfer style for zero blocks.
831 src_ranges = self.src.file_map.get("__ZERO", empty)
Doug Zongkerab7ca1d2014-08-26 10:40:28 -0700832 Transfer(tgt_fn, "__ZERO", tgt_ranges, src_ranges,
833 "zero", self.transfers)
Doug Zongkerfc44a512014-08-26 13:10:25 -0700834 continue
835
836 elif tgt_fn in self.src.file_map:
837 # Look for an exact pathname match in the source.
838 Transfer(tgt_fn, tgt_fn, tgt_ranges, self.src.file_map[tgt_fn],
839 "diff", self.transfers)
840 continue
841
842 b = os.path.basename(tgt_fn)
843 if b in self.src_basenames:
844 # Look for an exact basename match in the source.
845 src_fn = self.src_basenames[b]
846 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
847 "diff", self.transfers)
848 continue
849
850 b = re.sub("[0-9]+", "#", b)
851 if b in self.src_numpatterns:
852 # Look for a 'number pattern' match (a basename match after
853 # all runs of digits are replaced by "#"). (This is useful
854 # for .so files that contain version numbers in the filename
855 # that get bumped.)
856 src_fn = self.src_numpatterns[b]
857 Transfer(tgt_fn, src_fn, tgt_ranges, self.src.file_map[src_fn],
858 "diff", self.transfers)
859 continue
860
861 Transfer(tgt_fn, None, tgt_ranges, empty, "new", self.transfers)
862
863 def AbbreviateSourceNames(self):
Doug Zongkerfc44a512014-08-26 13:10:25 -0700864 for k in self.src.file_map.keys():
865 b = os.path.basename(k)
866 self.src_basenames[b] = k
867 b = re.sub("[0-9]+", "#", b)
868 self.src_numpatterns[b] = k
869
870 @staticmethod
871 def AssertPartition(total, seq):
872 """Assert that all the RangeSets in 'seq' form a partition of the
873 'total' RangeSet (ie, they are nonintersecting and their union
874 equals 'total')."""
875 so_far = RangeSet()
876 for i in seq:
877 assert not so_far.overlaps(i)
878 so_far = so_far.union(i)
879 assert so_far == total