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