]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: ensure ->done is idempotent
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 package PublicInbox::V2Writable;
6 use strict;
7 use warnings;
8 use base qw(PublicInbox::Lock);
9 use PublicInbox::SearchIdxPart;
10 use PublicInbox::SearchIdxSkeleton;
11 use PublicInbox::MIME;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids);
15 use PublicInbox::ContentId qw(content_id content_digest);
16 use PublicInbox::Inbox;
17
18 # an estimate of the post-packed size to the raw uncompressed size
19 my $PACKING_FACTOR = 0.4;
20
21 # assume 2 cores if GNU nproc(1) is not available
22 sub nproc () {
23         int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
24 }
25
26 sub new {
27         my ($class, $v2ibx, $creat) = @_;
28         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
29         unless (-d $dir) {
30                 if ($creat) {
31                         require File::Path;
32                         File::Path::mkpath($dir);
33                 } else {
34                         die "$dir does not exist\n";
35                 }
36         }
37
38         my $nparts = 0;
39         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
40
41         # always load existing partitions in case core count changes:
42         if (-d $xpfx) {
43                 foreach my $part (<$xpfx/*>) {
44                         -d $part && $part =~ m!/\d+\z! or next;
45                         eval {
46                                 Search::Xapian::Database->new($part)->close;
47                                 $nparts++;
48                         };
49                 }
50         }
51         $nparts = nproc() if ($nparts == 0);
52
53         my $self = {
54                 -inbox => $v2ibx,
55                 im => undef, #  PublicInbox::Import
56                 xap_rw => undef, # PublicInbox::V2SearchIdx
57                 xap_ro => undef,
58                 partitions => $nparts,
59                 transact_bytes => 0,
60                 lock_path => "$dir/inbox.lock",
61                 # limit each repo to 1GB or so
62                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
63         };
64         bless $self, $class;
65 }
66
67 # returns undef on duplicate or spam
68 # mimics Import::add and wraps it for v2
69 sub add {
70         my ($self, $mime, $check_cb) = @_;
71
72         # spam check:
73         if ($check_cb) {
74                 $mime = $check_cb->($mime) or return;
75         }
76
77         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
78         # as does SQLite 3.4.1+ (released in 2007-07-20), and
79         # Xapian 1.3.2+ (released 2015-03-15).
80         # For the most part, we can spawn git-fast-import without
81         # leaking FDs to it...
82         $self->idx_init;
83
84         my $mid0;
85         my $num = num_for($self, $mime, \$mid0);
86         defined $num or return; # duplicate
87         defined $mid0 or die "BUG: $mid0 undefined\n";
88         my $im = $self->importer;
89         my $cmt = $im->add($mime);
90         $cmt = $im->get_mark($cmt);
91         my ($oid, $len, $msgref) = @{$im->{last_object}};
92
93         my $nparts = $self->{partitions};
94         my $part = $num % $nparts;
95         my $idx = $self->idx_part($part);
96         $idx->index_raw($len, $msgref, $num, $oid, $mid0);
97         my $n = $self->{transact_bytes} += $len;
98         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
99                 $self->checkpoint;
100         }
101
102         $mime;
103 }
104
105 sub num_for {
106         my ($self, $mime, $mid0) = @_;
107         my $mids = mids($mime->header_obj);
108         if (@$mids) {
109                 my $mid = $mids->[0];
110                 my $num = $self->{skel}->{mm}->mid_insert($mid);
111                 if (defined $num) { # common case
112                         $$mid0 = $mid;
113                         return $num;
114                 };
115
116                 # crap, Message-ID is already known, hope somebody just resent:
117                 $self->barrier;
118                 foreach my $m (@$mids) {
119                         # read-only lookup now safe to do after above barrier
120                         my $existing = $self->lookup_content($mime, $m);
121                         if ($existing) {
122                                 warn "<$m> resent\n";
123                                 return; # easy, don't store duplicates
124                         }
125                 }
126
127                 # very unlikely:
128                 warn "<$mid> reused for mismatched content\n";
129
130                 # try the rest of the mids
131                 foreach my $i (1..$#$mids) {
132                         my $m = $mids->[$i];
133                         $num = $self->{skel}->{mm}->mid_insert($m);
134                         if (defined $num) {
135                                 warn "alternative <$m> for <$mid> found\n";
136                                 $$mid0 = $m;
137                                 return $num;
138                         }
139                 }
140         }
141         # none of the existing Message-IDs are good, generate a new one:
142         num_for_harder($self, $mime, $mid0);
143 }
144
145 sub num_for_harder {
146         my ($self, $mime, $mid0) = @_;
147
148         my $hdr = $mime->header_obj;
149         my $dig = content_digest($mime);
150         $$mid0 = PublicInbox::Import::digest2mid($dig);
151         my $num = $self->{skel}->{mm}->mid_insert($$mid0);
152         unless (defined $num) {
153                 # it's hard to spoof the last Received: header
154                 my @recvd = $hdr->header_raw('Received');
155                 $dig->add("Received: $_") foreach (@recvd);
156                 $$mid0 = PublicInbox::Import::digest2mid($dig);
157                 $num = $self->{skel}->{mm}->mid_insert($$mid0);
158
159                 # fall back to a random Message-ID and give up determinism:
160                 until (defined($num)) {
161                         $dig->add(rand);
162                         $$mid0 = PublicInbox::Import::digest2mid($dig);
163                         warn "using random Message-ID <$$mid0> as fallback\n";
164                         $num = $self->{skel}->{mm}->mid_insert($$mid0);
165                 }
166         }
167         my @cur = $hdr->header_raw('Message-Id');
168         $hdr->header_set('Message-Id', "<$$mid0>", @cur);
169         $num;
170 }
171
172 sub idx_part {
173         my ($self, $part) = @_;
174         $self->{idx_parts}->[$part];
175 }
176
177 # idempotent
178 sub idx_init {
179         my ($self) = @_;
180         return if $self->{idx_parts};
181         my $ibx = $self->{-inbox};
182
183         # do not leak read-only FDs to child processes, we only have these
184         # FDs for duplicate detection so they should not be
185         # frequently activated.
186         delete $ibx->{$_} foreach (qw(git mm search));
187
188         $self->lock_acquire;
189
190         # first time initialization, first we create the skeleton pipe:
191         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
192
193         # need to create all parts before initializing msgmap FD
194         my $max = $self->{partitions} - 1;
195         my $idx = $self->{idx_parts} = [];
196         for my $i (0..$max) {
197                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
198         }
199
200         # Now that all subprocesses are up, we can open the FD for SQLite:
201         $skel->_msgmap_init->{dbh}->begin_work;
202 }
203
204 sub remove {
205         my ($self, $mime, $cmt_msg) = @_;
206         $self->barrier;
207         $self->idx_init;
208         my $im = $self->importer;
209         my $ibx = $self->{-inbox};
210         my $srch = $ibx->search;
211         my $cid = content_id($mime);
212         my $skel = $self->{skel};
213         my $parts = $self->{idx_parts};
214         my $mm = $skel->{mm};
215         my $removed;
216         my $mids = mids($mime->header_obj);
217         foreach my $mid (@$mids) {
218                 $srch->reopen->each_smsg_by_mid($mid, sub {
219                         my ($smsg) = @_;
220                         $smsg->load_expand;
221                         my $msg = $ibx->msg_by_smsg($smsg);
222                         if (!defined($msg)) {
223                                 warn "broken smsg for $mid\n";
224                                 return 1; # continue
225                         }
226                         my $orig = $$msg;
227                         my $cur = PublicInbox::MIME->new($msg);
228                         if (content_id($cur) eq $cid) {
229                                 $mm->num_delete($smsg->num);
230                                 # $removed should only be set once assuming
231                                 # no bugs in our deduplication code:
232                                 $removed = $smsg;
233                                 $removed->{mime} = $cur;
234                                 $im->remove(\$orig, $cmt_msg);
235                                 $orig = undef;
236                                 $removed->num; # memoize this for callers
237
238                                 my $oid = $smsg->{blob};
239                                 foreach my $idx (@$parts, $skel) {
240                                         $idx->remote_remove($oid, $mid);
241                                 }
242                         }
243                         1; # continue
244                 });
245                 $self->barrier;
246         }
247         $removed;
248 }
249
250 sub done {
251         my ($self) = @_;
252         my $locked = defined $self->{idx_parts};
253         my $im = delete $self->{im};
254         $im->done if $im; # PublicInbox::Import::done
255         $self->searchidx_checkpoint(0);
256         $self->lock_release if $locked;
257 }
258
259 sub checkpoint {
260         my ($self) = @_;
261         my $im = $self->{im};
262         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
263         $self->searchidx_checkpoint(1);
264 }
265
266 # issue a write barrier to ensure all data is visible to other processes
267 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
268 sub barrier {
269         my ($self) = @_;
270
271         if (my $im = $self->{im}) {
272                 $im->barrier;
273         }
274         my $skel = $self->{skel};
275         my $parts = $self->{idx_parts};
276         if ($parts && $skel) {
277                 my $dbh = $skel->{mm}->{dbh};
278                 $dbh->commit; # SQLite data is second in importance
279
280                 # Now deal with Xapian
281                 $skel->barrier_init(scalar(@$parts));
282                 # each partition needs to issue a barrier command to skel:
283                 $_->barrier foreach @$parts;
284
285                 $skel->barrier_wait; # wait for each Xapian partition
286
287                 $dbh->begin_work;
288         }
289         $self->{transact_bytes} = 0;
290 }
291
292 sub searchidx_checkpoint {
293         my ($self, $more) = @_;
294
295         # order matters, we can only close {skel} after all partitions
296         # are done because the partitions also write to {skel}
297         if (my $parts = $self->{idx_parts}) {
298                 foreach my $idx (@$parts) {
299                         $idx->remote_commit; # propagates commit to skel
300                         $idx->remote_close unless $more;
301                 }
302                 delete $self->{idx_parts} unless $more;
303         }
304
305         if (my $skel = $self->{skel}) {
306                 my $dbh = $skel->{mm}->{dbh};
307                 $dbh->commit;
308                 if ($more) {
309                         $dbh->begin_work;
310                 } else {
311                         $skel->remote_close;
312                         delete $self->{skel};
313                 }
314         }
315         $self->{transact_bytes} = 0;
316 }
317
318 sub git_init {
319         my ($self, $new) = @_;
320         my $pfx = "$self->{-inbox}->{mainrepo}/git";
321         my $git_dir = "$pfx/$new.git";
322         die "$git_dir exists\n" if -e $git_dir;
323         my @cmd = (qw(git init --bare -q), $git_dir);
324         PublicInbox::Import::run_die(\@cmd);
325
326         my $all = "$self->{-inbox}->{mainrepo}/all.git";
327         unless (-d $all) {
328                 @cmd = (qw(git init --bare -q), $all);
329                 PublicInbox::Import::run_die(\@cmd);
330                 @cmd = (qw/git config/, "--file=$all/config",
331                                 'repack.writeBitmaps', 'true');
332                 PublicInbox::Import::run_die(\@cmd);
333         }
334
335         @cmd = (qw/git config/, "--file=$git_dir/config",
336                         'include.path', '../../all.git/config');
337         PublicInbox::Import::run_die(\@cmd);
338
339         my $alt = "$all/objects/info/alternates";
340         my $new_obj_dir = "../../git/$new.git/objects";
341         my %alts;
342         if (-e $alt) {
343                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
344                 %alts = map { chomp; $_ => 1 } (<$fh>);
345         }
346         return $git_dir if $alts{$new_obj_dir};
347         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
348         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
349         close $fh or die "close $alt: $!\n";
350         $git_dir
351 }
352
353 sub importer {
354         my ($self) = @_;
355         my $im = $self->{im};
356         if ($im) {
357                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
358                         return $im;
359                 } else {
360                         $self->{im} = undef;
361                         $im->done;
362                         $self->searchidx_checkpoint(1);
363                         $im = undef;
364                         my $git_dir = $self->git_init(++$self->{max_git});
365                         my $git = PublicInbox::Git->new($git_dir);
366                         return $self->import_init($git, 0);
367                 }
368         }
369         my $latest;
370         my $max = -1;
371         my $new = 0;
372         my $pfx = "$self->{-inbox}->{mainrepo}/git";
373         if (-d $pfx) {
374                 foreach my $git_dir (glob("$pfx/*.git")) {
375                         $git_dir =~ m!/(\d+)\.git\z! or next;
376                         my $n = $1;
377                         if ($n > $max) {
378                                 $max = $n;
379                                 $latest = $git_dir;
380                         }
381                 }
382         }
383         if (defined $latest) {
384                 my $git = PublicInbox::Git->new($latest);
385                 my $packed_bytes = $git->packed_bytes;
386                 if ($packed_bytes >= $self->{rotate_bytes}) {
387                         $new = $max + 1;
388                 } else {
389                         $self->{max_git} = $max;
390                         return $self->import_init($git, $packed_bytes);
391                 }
392         }
393         $self->{max_git} = $new;
394         $latest = $self->git_init($new);
395         $self->import_init(PublicInbox::Git->new($latest), 0);
396 }
397
398 sub import_init {
399         my ($self, $git, $packed_bytes) = @_;
400         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
401         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
402         $im->{want_object_info} = 1;
403         $im->{lock_path} = undef;
404         $im->{path_type} = 'v2';
405         $self->{im} = $im;
406 }
407
408 sub lookup_content {
409         my ($self, $mime, $mid) = @_;
410         my $ibx = $self->{-inbox};
411
412         my $srch = $ibx->search->reopen;
413         my $cid = content_id($mime);
414         my $found;
415         $srch->each_smsg_by_mid($mid, sub {
416                 my ($smsg) = @_;
417                 $smsg->load_expand;
418                 my $msg = $ibx->msg_by_smsg($smsg);
419                 if (!defined($msg)) {
420                         warn "broken smsg for $mid\n";
421                         return 1; # continue
422                 }
423                 my $cur = PublicInbox::MIME->new($msg);
424                 if (content_id($cur) eq $cid) {
425                         $smsg->{mime} = $cur;
426                         $found = $smsg;
427                         return 0; # break out of loop
428                 }
429                 1; # continue
430         });
431         $found;
432 }
433
434 sub atfork_child {
435         my ($self) = @_;
436         if (my $parts = $self->{idx_parts}) {
437                 $_->atfork_child foreach @$parts;
438         }
439         if (my $im = $self->{im}) {
440                 $im->atfork_child;
441         }
442 }
443
444 1;