-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot
executable file
·1490 lines (1278 loc) · 44.5 KB
/
snapshot
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
#!/usr/bin/ruby
# Copyright (c) 2009, 2010 Peter Palfrader
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'optparse'
require 'yaml'
require 'dbi'
require 'logger'
require 'digest/sha1'
require 'digest/md5'
require 'fileutils'
require 'time'
def barf(str)
if $logger.nil?
STDERR.puts(str)
STDERR.puts("(Also, while trying to print this we realized there $logger is not defined!)")
exit 1
end
$logger.error(str)
exit 1
end
def randstring()
value = ''
8.times{value << (65 + rand(25)).chr}
value
end
class StorageBackend
def store(source, digest)
throw "Not implemented"
end
def open(digest)
throw "Not implemented"
end
end
class FileBackend < StorageBackend
def initialize(farmpath, db)
@farmpath = farmpath
@db = db
end
def add_to_journal(hash)
@db.insert_row('farm_journal', { 'hash' => hash } )
end
def _get_path(digest, mkdir=false)
target = @farmpath
h = digest
2.times do
target = target + '/' + h[0..1]
h = h[2..-1]
Dir.mkdir(target) if mkdir and not File.directory?(target)
end
target = target + '/' + digest
end
def exists?(digest)
target = _get_path(digest)
return File.exists?(target)
end
def store(source, digest)
unless exists?(digest)
target = _get_path(digest, true)
dir = File.dirname(target)
fn = File.basename(target)
tmptarget = dir+"/.tmp."+randstring()+"."+(Process.pid.to_s)+"."+fn
FileUtils.cp(source, tmptarget)
begin
File.link(tmptarget, target)
add_to_journal(digest)
rescue Errno::EEXIST
# it may have jumped into existence, that's no problem.
end
File.unlink(tmptarget)
end
end
def open(digest)
target = _get_path(digest)
return File.new(target)
end
def get_path_to(digest)
return _get_path(digest)
end
end
class SnapshotDB
def initialize(conf, logger)
s = []
s << "database=#{conf['database']}"
s << "host=#{conf['host']}" if conf['host']
s << "port=#{conf['port']}" if conf['port']
@dbh = DBI.connect("dbi:Pg:#{s.join(';')}", conf['user'], conf['password'], 'AutoCommit'=>false)
@logger = logger
end
def get_primarykey_name(table);
# XXX
return table+'_id';
end
def begin()
@dbh.do("BEGIN")
end
def commit()
@dbh.do("COMMIT")
end
def dbdo(query, *args)
begin
@dbh.do(query, *args)
rescue DBI::ProgrammingError
@logger.warn("DB Error: #{$!}")
@logger.warn("Query: #{query}")
@logger.warn("Arguments: #{args.join(', ')}")
raise
end
end
def execute(query, *args)
begin
@dbh.execute(query, *args)
rescue DBI::ProgrammingError
@logger.warn("DB Error: #{$!}")
@logger.warn("Query: #{query}")
@logger.warn("Arguments: #{args.join(', ')}")
raise
end
end
def insert(table, values, returning=nil)
cols = values.keys().join(',')
vals = values.values()
qmarks = (['?'] * values.length).join(',')
query = "INSERT INTO #{table} (#{cols}) VALUES (#{qmarks})"
if returning.nil?
dbdo(query, *vals)
return nil
else
returning = [returning] unless returning.kind_of?(Array)
query += " RETURNING #{returning.join(',')}"
return query_row(query, *vals)
end
end
def insert_row(table, values)
pk_name = get_primarykey_name(table)
if values.has_key?(pk_name)
insert(table, values)
else
results = insert(table, values, [pk_name])
values[pk_name] = results[pk_name]
end
values
end
def update(table, set, where, returning=nil)
setclause = set.each_key.collect { |k| "#{k}=?" }.join(",")
whereclause = where.each_key.collect { |k| where[k].nil? ? "#{k} IS NULL" : "#{k}=?" }.join(" AND ")
query = "UPDATE #{table} SET #{setclause} WHERE #{whereclause}"
params = set.values + where.values.compact
unless returning
return dbdo(query, *params)
else
returning = [returning] unless returning.kind_of?(Array)
query += " RETURNING #{returning.join(',')}"
return query_row(query, *params)
end
end
def update_one(table, set, where)
r = update(table, set, where)
raise "Did not update exactly one row in update_one" unless r==1
return r
end
def query(query, *params)
sth = execute(query, *params)
while row = sth.fetch_hash
yield row
end
sth.finish
end
def query_row(query, *params)
sth = execute(query, *params)
row = sth.fetch_hash
if row == nil
sth.finish
return nil
elsif sth.fetch_hash != nil
sth.finish
raise "More than one result when querying for #{query}."
else
sth.finish
return row
end
end
end
class FSNode
attr_reader :path
def initialize(type, path, parent)
@data = {}
@type = type
@path = _fixup_path(path)
@name = File.basename(@path)
@parent = parent
if @parent.nil?
raise "No parent but we are not /." unless @path == "/"
@parent = self
elsif not @parent.kind_of? FSNodeDirectory
raise "FSNode got a parent of wrong type (#{parent.class})."
end
end
def _fixup_path(path)
return '/' if path == '.'
return path[1..-1] if path[0..0] == '.'
raise "Unexpected path(#{path}) for fixup"
end
def to_s
"#{@type} #{@path}"
end
def new_db_node(db, mirrorrun_id)
node = { 'first' => mirrorrun_id,
'last' => mirrorrun_id
}
node['parent'] = @parent.directory_id(db)
db.insert_row('node', node)
return node['node_id']
end
def update_common(db, query, args)
if self.kind_of? FSNodeDirectory
query += ' RETURNING directory_id'
r = db.query_row(query, *args)
@directory_id = r['directory_id'] if r
return !r.nil?
else
r = db.dbdo(query, *args)
raise "Did not update exactly zero or one element." if r and r>1
return r == 1
end
end
def update_one_side(db, mirrorrun_id, lastnext, lastnext_id, table, whereclause, whereparams, isrootdir)
query = "UPDATE node SET #{lastnext}=?
FROM #{table}
WHERE node.node_id = #{table}.node_id " +
(isrootdir ? "" : "AND parent=? ") +
"AND #{lastnext}=?
AND #{whereclause}"
args = [mirrorrun_id] +
(isrootdir ? [] : [@parent.directory_id()]) +
[lastnext_id] +
whereparams
return update_common(db, query, args)
end
def update_boxed(db, table, whereclause, whereparams, isrootdir)
# if we have a mirrorrun in the past and one in the future
# then this element might already be covered by a node that starts
# in the past and ends in the future.
query = "DELETE FROM nodes_window USING #{table}
WHERE nodes_window.node_id = #{table}.node_id " +
(isrootdir ? "" : "AND parent=? ") +
"AND #{whereclause}"
args = (isrootdir ? [] : [@parent.directory_id()]) + whereparams
return update_common(db, query, args)
end
def insert(db, mirrorrun_id)
new_node_id = new_db_node(db, mirrorrun_id)
insert_elem(db, new_node_id)
end
def update_or_insert(db, mirrorrun_id, prev_run, next_run)
table, whereclause, whereparams = already_exists_args
isrootdir = @parent == self
[ ['last', prev_run], ['first', next_run] ].each do |lastnext, lastnext_id|
next if lastnext_id.nil?
r = update_one_side(db, mirrorrun_id, lastnext, lastnext_id, table, whereclause, whereparams, isrootdir)
return if r
end
r = update_boxed(db, table, whereclause, whereparams, isrootdir)
return if r
insert(db, mirrorrun_id)
end
end
class FSNodeDirectory < FSNode
def initialize(path, parent)
super('d', path, parent)
end
def directory_id(db=nil)
return @directory_id if @directory_id
raise "This should only be required for the / directory. This is #{@path}." unless @path == "/"
@directory_id = db.query_row("SELECT nextval(pg_get_serial_sequence('directory', 'directory_id')) AS newref")['newref']
$logger.debug("Making up directory_id for #{@path}. It's #{@directory_id}.")
return @directory_id
end
def already_exists_args()
return 'directory', "path=?", [@path]
end
def insert_elem(db, node_id)
dir = { 'path' => @path,
'node_id' => node_id
}
dir['directory_id'] = @directory_id if @directory_id
db.insert_row('directory', dir)
@directory_id = dir['directory_id']
end
end
class FSNodeSymlink < FSNode
def initialize(path, target, parent)
super('l', path, parent)
@target = target
end
def to_s
super + " #{@target}"
end
def already_exists_args()
return 'symlink', "name=? AND target=?", [@name, @target]
end
def insert_elem(db, node_id)
elem = { 'name' => @name,
'target' => @target,
'node_id' => node_id
}
db.insert('symlink', elem)
end
end
class FSNodeRegularBase < FSNode
def initialize(path, parent, size, digest)
super('-', path, parent)
@size = size
@digest = digest
end
def to_s
@digest.nil? ?
(super + " #{@size}") :
(super + " #{@size} #{@digest}")
end
def already_exists_args()
if @digest.nil?
return 'file', "name=? AND size=?", [@name, @size]
else
return 'file', "name=? AND size=? AND hash=?", [@name, @size, @digest]
end
end
def get_digest
return @digest if @digest
# this should only happen if a child class doesn't override it and also doesn't set @digest.
throw "get_digest() called in FSNodeRegularBase and we don't have an answer. That's not good."
end
def store_file
throw "store_file() called in FSNodeRegularBase - children should overwrite it."
end
def insert_elem(db, node_id)
elem = { 'name' => @name,
'size' => @size,
'hash' => get_digest,
'node_id' => node_id
}
db.insert('file', elem)
store_file
end
end
class FSNodeRegular < FSNodeRegularBase
def initialize(path, truepath, statinfo, parent, quick=nil)
# a word on the quick parameter:
# quick is either a boolean or a time object.
# if it's false (or nil) then all files are always hashed
# and their digest checked to see if the entry exists in the DB.
#
# same if quick is a timestamp and the file has ctime
# and mtime both older than quick.
#
# else the quick path is taken and we only use size
# (in addition to the filename, and path) to see if
# we already are in the DB. we only hash the file
# when we actually need to put that information in the DB,
# i.e. when the file is new.
@truepath = truepath
digest = nil
get_digest = true
most_recent_touched = [statinfo.mtime, statinfo.ctime].max
if quick
if quick.kind_of? Time
get_digest = false if most_recent_touched < quick
else
get_digest = false
end
end
if get_digest
digest = Digest::SHA1.file(@truepath).hexdigest
end
super(path, parent, statinfo.size, digest)
end
def get_digest
return @digest if @digest
@digest = Digest::SHA1.file(@truepath).hexdigest
@digest
end
def store_file
$storage.store(@truepath, get_digest)
end
end
class FSNodeRegularFromDump < FSNodeRegularBase
def initialize(path, parent, size, digest, trust_files_are_there)
super(path, parent, size, digest)
@trust_files_are_there = trust_files_are_there
end
def store_file
return if @trust_files_are_there
return if $storage.exists?(@digest)
$logger.warn("[dump import] missing file in storage: #{@digest} #{@path}.")
end
end
class FSReader
def initialize(path, quick=nil)
@root = path
@quick = quick
end
def each_node(path='.', parent=nil)
realpath = "#{@root}/#{path}"
dir = FSNodeDirectory.new(path, parent)
yield dir
Dir.foreach(realpath) do |filename|
next if %w{. ..}.include? filename
element = "#{path}/#{filename}"
trueelement = "#{@root}/#{element}"
statinfo = File.lstat(trueelement)
if statinfo.symlink?
yield FSNodeSymlink.new(element, File.readlink(trueelement), dir)
elsif statinfo.directory?
each_node(element, dir) { |e| yield e}
elsif statinfo.file?
yield FSNodeRegular.new(element, trueelement, statinfo, dir, @quick)
else
$logger.warn("Ignoring #{element} which has unknown file type.")
end
end
end
end
class DumpReader
def initialize(path, trust_files_are_there)
@fd = File.open( path )
@dir_cache = {}
@attrs = {}
@trust_files_are_there
while not (line = @fd.gets).nil?
line.chomp!
key,value = line.split(/: */, 2)
@attrs[key] = value
break if key == "Contents"
end
%w{Archive Date UUID ImportingHost Contents}.each do |k|
barf("Required key #{k} not found in dump") unless @attrs.has_key?(k)
end
end
def archive
@attrs['Archive']
end
def uuid
@attrs['UUID']
end
def date
@attrs['Date']
end
def importing_host
@attrs['ImportingHost']
end
def each_node(path='.', parent=nil)
line = @fd.gets
barf "Reached end of file without any contents?" unless line
line.chomp!
barf "Expected 'd /' as first entry" unless line == " d /"
dir = FSNodeDirectory.new(path, parent)
@dir_cache[dir.path] = dir
yield dir
@fd.each_line do |line|
line.chomp!
barf "Invalid input line '#{line}'." unless line[0..0] == ' '
line[0..0] = ''
type,path,rest = line.split(' ', 3)
barf "Expected path to start with /" unless path[0..0] == "/"
parentpath = File.dirname(path)
path = '.'+path
parent = @dir_cache[parentpath]
barf "Failed while trying to find parentdir #{parentpath} of entry '#{line}'" unless parent
case type
when 'd'
dir = FSNodeDirectory.new(path, parent)
@dir_cache[dir.path] = dir
yield dir
when '-'
size, digest = rest.split(' ',2)
throw "Invalid size #{size} in entry '#{line}'" if size =~ /[^0-9]/
throw "Invalid digest #{digest} in entry '#{line}'" if digest =~ /[^0-9a-f]/
throw "Invalid digest #{digest} in entry '#{line}'" if digest.length != 40
yield FSNodeRegularFromDump.new(path, parent, size, digest, @trust_files_are_there)
when 'l'
yield FSNodeSymlink.new(path, rest, parent)
else
barf "Unknown type #{type} in line '#{line}'"
end
end
end
end
class SnapshotImporter
def initialize(db, timetravel)
@db = db
@timetravel = timetravel
end
# if we insert a new mirrorrun in time between existing mirrorruns
# then it can happen that a specific file/dir/symlink existed in the
# past and exists in the future, but does not currently exist.
# in such cases we have to split existing nodes in the DB in two.
def _split_boxed_missing(mirrorrun_id, prev_run, next_run)
# This code path is probably slightly tested at best
# It will not get much practice
handled = 0
changed_parents = {}
[ ['directory', %w(path) ],
['symlink' , %w(name target)],
['file', %w(name size hash)]
].each do |type, items|
query = "SELECT #{type}.#{type}_id, "+(items.collect{|i| "#{type}.#{i}, "}.join(""))+
"node.node_id, node.parent, node.first, node.last
FROM nodes_window JOIN node ON nodes_window.node_id = node.node_id
JOIN #{type} ON node.node_id = #{type}.node_id"
query += " ORDER BY path" if type == "directory"
@db.query(query) do |row|
@db.update_one('node', {'last' => prev_run}, {'node_id' => row['node_id']})
# we would need to handle parent == self crap
throw "Cannot split the / node." if type == 'directory' and row['path'] == "/"
$logger.debug "[run ##{mirrorrun_id}] Splitting #{row.inspect}"
new_parent = (changed_parents[row['parent']] or row['parent'])
new_node = {'parent' => new_parent, 'first' => next_run, 'last' => row['last']}
@db.insert_row('node', new_node)
new_elem = {}
items.each { |k| new_elem[k] = row[k] }
new_elem['node_id'] = new_node['node_id']
@db.insert_row(type, new_elem)
changed_parents[ row['directory_id'] ] = new_elem['directory_id'] if type == "directory"
handled += 1
end
end
row = @db.query_row("SELECT count(*) AS count FROM nodes_window")
raise "Did not process correct amount of elements in nodes_window table." if row['count'].to_i != handled
end
def _get_archive_id(archive)
row = @db.query_row('SELECT archive_id FROM archive WHERE name=? FOR UPDATE', archive)
barf("Archive #{archive} does not exist") if row.nil?
return row['archive_id']
end
def _insert_mirrorrun(archive_id, date, uuid=nil, importing_host=nil)
date = date.nil? ? Time.new() : Time.parse(date)
uuid=`uuidgen`.chomp if uuid.nil?
importing_host=`hostname -f`.chomp if importing_host.nil?
mirrorrun_id = @db.insert_row('mirrorrun', {'archive_id'=>archive_id, 'run'=>date.to_s, 'mirrorrun_uuid'=>uuid, 'importing_host'=>importing_host})['mirrorrun_id']
return mirrorrun_id
end
def _get_prev_next(archive_id, mirrorrun_id)
row = @db.query_row("SELECT
(SELECT count(*) FROM mirrorrun WHERE archive_id=?
AND run=(SELECT run FROM mirrorrun WHERE mirrorrun_id=?)) AS count,
(SELECT mirrorrun_id FROM mirrorrun WHERE archive_id=?
AND run>(SELECT run FROM mirrorrun WHERE mirrorrun_id=?)
ORDER BY run
LIMIT 1) AS next,
(SELECT mirrorrun_id FROM mirrorrun WHERE archive_id=?
AND run<(SELECT run FROM mirrorrun WHERE mirrorrun_id=?)
ORDER BY run DESC
LIMIT 1) AS prev
", archive_id, mirrorrun_id, archive_id, mirrorrun_id, archive_id, mirrorrun_id);
barf("Cannot have two runs for the same archive at the exact same time.") if row['count'].to_i > 1
return row['prev'], row['next']
end
def _create_nodes_window(archive_id, mirrorrun_id)
@db.dbdo('CREATE TEMPORARY TABLE nodes_window AS
SELECT node_id, parent FROM node_with_ts
WHERE archive_id = ?
AND first_run < (SELECT run FROM mirrorrun WHERE mirrorrun_id=?)
AND last_run > (SELECT run FROM mirrorrun WHERE mirrorrun_id=?)',
archive_id, mirrorrun_id, mirrorrun_id)
@db.dbdo('CREATE INDEX nodes_window_idx_parent ON nodes_window(parent)')
@db.dbdo('ANALYZE nodes_window')
end
def _cleanup_nodes_window()
@db.dbdo("DROP TABLE nodes_window")
end
def _get_quick_cutoff_time(quick, prev_run)
quick_cutoff_time = nil
if quick and prev_run
row = @db.query_row("SELECT run FROM mirrorrun WHERE mirrorrun_id=?", prev_run)
quick_cutoff_time=Time.parse(row['run'].to_s)
end
return quick_cutoff_time
end
def _create_fs_reader(quick, prev_run, path)
quick_cutoff_time = _get_quick_cutoff_time(quick, prev_run)
fs = FSReader.new(path, quick_cutoff_time)
return fs
end
def import_from_filesystem(path, archive, date, quick)
@db.begin
archive_id = _get_archive_id(archive)
mirrorrun_id = _insert_mirrorrun(archive_id, date)
prev_run, next_run = _get_prev_next(archive_id, mirrorrun_id)
fs = _create_fs_reader(quick, prev_run, path)
barf("Quick imports are probably not safe when we have imports from the future already in the DB.") if next_run and quick
$logger.info("New mirrorrun #{mirrorrun_id} for #{archive}")
import(archive_id, mirrorrun_id, fs, prev_run, next_run)
@db.commit
$logger.info("[run ##{mirrorrun_id}] Mirrorrun #{mirrorrun_id} for #{archive} completed.")
end
def import_from_dump(path, quick)
@db.begin
fs = DumpReader.new(path, quick)
archive_id = _get_archive_id(fs.archive)
mirrorrun_id = _insert_mirrorrun(archive_id, fs.date, fs.uuid, fs.importing_host)
prev_run, next_run = _get_prev_next(archive_id, mirrorrun_id)
$logger.info("Import mirrorrun #{mirrorrun_id} for #{fs.archive}")
import(archive_id, mirrorrun_id, fs, prev_run, next_run)
@db.commit
$logger.info("[run ##{mirrorrun_id}] Mirrorrun #{mirrorrun_id} for #{fs.archive} completed (imported #{fs.uuid}).")
end
def import(archive_id, mirrorrun_id, fs, prev_run, next_run)
barf("Enable --timetravel if you want to import archives older than the newest in the DB.") if next_run and not @timetravel
_create_nodes_window(archive_id, mirrorrun_id)
fs.each_node do |fsnode|
fsnode.update_or_insert(@db, mirrorrun_id, prev_run, next_run)
$logger.debug("[run ##{mirrorrun_id}] Importing #{fsnode}")
end
_split_boxed_missing(mirrorrun_id, prev_run, next_run)
_cleanup_nodes_window()
end
end
class PackageIndexer
def initialize(db, quick, only_this_mirrorrun)
@db = db
@quick = quick
@only_this_mirrorrun = only_this_mirrorrun
@mirrorrun_id = nil
@mirrorrun_run = nil
@mirrorrun_archive_id = nil
end
def _get_archive_and_run_from_mirrorrun(mirrorrun_id)
row = @db.query_row("SELECT run, archive_id FROM mirrorrun WHERE mirrorrun_id=?", mirrorrun_id)
return row['archive_id'], row['run']
end
def get_file_digest(filename, mirrorrun_id=nil)
if mirrorrun_id
archive_id, run = _get_archive_and_run_from_mirrorrun(mirrorrun_id)
else
archive_id = @mirrorrun_archive_id
run = @mirrorrun_run
end
row = @db.query_row("SELECT get_file_from_path_at(?, ?, ?, ?) AS hash", archive_id, run, File.dirname(filename), File.basename(filename))
return row['hash']
end
def open_file(filename, mirrorrun_id=nil)
digest = get_file_digest(filename, mirrorrun_id)
return nil if digest.nil?
return $storage.open(digest)
end
def add_pkg(type, pkg, ver, srcpkg_id=nil)
case type
when "src"
cache = @sourcepkgs
throw "don't need a srcpkg_id" unless srcpkg_id.nil?
when "bin"
cache = @binarypkgs
throw "need a srcpkg_id" if srcpkg_id.nil?
else
throw "Invalid type #{type}"
end
return cache[pkg][ver] if cache[pkg] and cache[pkg][ver]
query = "SELECT #{type}pkg_id AS id FROM #{type}pkg WHERE name=? AND version=?"
args = [pkg, ver]
if srcpkg_id
query += " AND srcpkg_id=?"
args << srcpkg_id
end
r = @db.query_row(query, *args)
if r
id = r["id"]
else
p = {'name' => pkg, 'version' => ver }
p['srcpkg_id'] = srcpkg_id if srcpkg_id
@db.insert_row("#{type}pkg", p)
id = p["#{type}pkg_id"]
end
cache[pkg] = {} unless cache[pkg]
cache[pkg][ver] = id
return id
end
def add_srcpkg(pkg, ver)
add_pkg('src', pkg, ver)
end
def add_binpkg(pkg, ver, srcpkg_id)
add_pkg('bin', pkg, ver, srcpkg_id)
end
def hash_has_any_key(hash, keys)
keys.each{ |k| return true if hash.has_key? k }
return false
end
def hash_has_all_keys(hash, keys)
keys.each{ |k| return false unless hash.has_key? k }
return true
end
def insert_file_from_digest(type, pkg, digest, arch = nil)
query = "SELECT count(*) AS cnt FROM file_#{type}pkg_mapping WHERE #{type}pkg_id=? AND hash=?"
args = [pkg, digest]
if arch
query += " AND architecture=?"
args << arch
end
r = @db.query_row(query, *args)
r['cnt'] = r['cnt'].to_i
return if r['cnt'] == 1
throw "Unexpected count of #{r['cnt']}" unless r['cnt'] == 0
p = {"#{type}pkg_id" => pkg, 'hash' => digest}
p['architecture'] = arch if arch
@db.insert("file_#{type}pkg_mapping", p)
end
def insert_file_from_path(type, pkg, path, arch = nil)
case type
when "src"
throw "don't need an arch" unless arch.nil?
when "bin"
throw "need an arch" if arch.nil?
else
throw "Invalid type #{type}"
end
digest = get_file_digest(path)
unless digest
$logger.warn("[indexrun ##{@mirrorrun_id}] File #{path} is referenced in index but does not exist in mirrorrun)")
return false
end
insert_file_from_digest(type, pkg, digest, arch)
return true
end
def insert_src_file_from_path(srcpkg, path)
insert_file_from_path('src', srcpkg, path)
end
def insert_bin_file_from_path(binpkg, path, arch)
insert_file_from_path('bin', binpkg, path, arch)
end
def insert_src_file_from_digest(pkg, digest)
insert_file_from_digest('src', pkg, digest)
end
def insert_bin_file_from_digest(pkg, digest, arch)
insert_file_from_digest('bin', pkg, digest, arch)
end
# Insert binary and source packages listed in /indices/package-file.map.bz2
# if the mirror has such a file.
def index_mirrorrun_from_index()
index = open_file('/indices/package-file.map.bz2')
return unless index
@sourcepkgs = {}
@binarypkgs = {}
previously_seen = nil
if (@quick)
row = @db.query_row("SELECT mirrorrun_id as prev FROM mirrorrun
WHERE archive_id=?
AND run < ?
ORDER BY run DESC
LIMIT 1", @mirrorrun_archive_id, @mirrorrun_run)
unless row.nil?
prev_run_id = row['prev']
$logger.debug("[indexrun ##{@mirrorrun_id}] previous run was ##{prev_run_id}")
prev_index = open_file('/indices/package-file.map.bz2', prev_run_id)
unless prev_index.nil?
previously_seen = {}
prev_index = IO.popen(['bunzip2'], :in => prev_index)
prev_index.each_line(sep_string='') do |block|
previously_seen[Digest::SHA1.digest(block)] = 1
end
prev_index.close()
else
$logger.warn("[indexrun ##{@mirrorrun_id}] quick mode selected but no previous (##{prev_run_id}) package-file.map")
end
end
end
@db.dbdo('SAVEPOINT startofindexing')
begin
lineno = 0
index = IO.popen(['bunzip2'], :in => index)
index.each_line(sep_string='') do |block|
next if previously_seen and previously_seen.has_key? Digest::SHA1.digest(block)
e = {}
block.split("\n").each do |line|
key,value = line.split(/: */, 2)
e[key] = value
lineno += 1
end
lineno += 1
unless hash_has_all_keys(e, %w(Path))
$logger.warn("[indexrun ##{@mirrorrun_id}] Block has no path element before line #{lineno}")
next
end
e['Path'][0..0] = '' if e['Path'][0..0] = '.'
unless hash_has_all_keys(e, %w(Source Source-Version))
$logger.warn("[indexrun ##{@mirrorrun_id}] Block has incomplete source information before line #{lineno}")
next
end
srcpkg = add_srcpkg(e['Source'], e['Source-Version'])
if not hash_has_any_key(e, %w(Binary-Version Binary Architecture))
inserted = insert_src_file_from_path(srcpkg, e['Path'])
$logger.debug("[indexrun ##{@mirrorrun_id}] " + (inserted ? "Inserting" : "Skipping already existing") + " #{e['Path']} for source #{e['Source']} #{e['Source-Version']}")
else
unless hash_has_all_keys(e, %w(Binary-Version Binary Architecture))
$logger.warn("[indexrun ##{@mirrorrun_id}] Block has incomplete binary information before line #{lineno}")
next
end
binpkg = add_binpkg(e['Binary'], e['Binary-Version'], srcpkg)
inserted = insert_bin_file_from_path(binpkg, e['Path'], e['Architecture'])
$logger.debug("[indexrun ##{@mirrorrun_id}] " + (inserted ? "Inserting" : "Skipping already existing") + " #{e['Path']} for binary #{e['Binary']} #{e['Binary-Version']}")
end
end
index.close()
rescue Bzip2::EOZError => e
@db.dbdo('ROLLBACK TO startofindexing')
$logger.warn("[indexrun ##{@mirrorrun_id}] package-file.map is corrupt (Bzip2::EOZError): #{e.message}")
return
end
@db.dbdo('RELEASE SAVEPOINT startofindexing')
source = "index"
source += '(Q)' if @quick
return source
end
# index a given .deb or .udeb.
# package, version, source etc are all learned from dpkg --info.
def index_binary_package(path, name, digest)
e = {}
debversion = nil
fd = IO.popen('-') do |fd|
if not fd
cmd = ['dpkg', '--info', $storage.get_path_to(digest)]
exec(*cmd)
$logger.error("[indexrun ##{@mirrorrun_id}] Failed to exec #{cmd.join(" ")}")
exit(1)
end
# first line
line = fd.readline
line.chomp!
line[0..0] = '' if line[0..0] == ' '
case line
when "old debian package, version 0.932000.",
"old debian package, version 0.933000.",
"old debian package, version 0.936000.",
"old debian package, version 0.939000."
debversion = '0.93'
when "new debian package, version 2.0."
debversion = '2'
else