]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: support "barrier" operation to avoid reforking
[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         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                 # limit each repo to 1GB or so
61                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
62         };
63         bless $self, $class
64 }
65
66 # returns undef on duplicate or spam
67 # mimics Import::add and wraps it for v2
68 sub add {
69         my ($self, $mime, $check_cb) = @_;
70
71         # spam check:
72         if ($check_cb) {
73                 $mime = $check_cb->($mime) or return;
74         }
75
76         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
77         # as does SQLite 3.4.1+ (released in 2007-07-20), and
78         # Xapian 1.3.2+ (released 2015-03-15).
79         # For the most part, we can spawn git-fast-import without
80         # leaking FDs to it...
81         $self->idx_init;
82
83         my $mid0;
84         my $num = num_for($self, $mime, \$mid0);
85         defined $num or return; # duplicate
86         defined $mid0 or die "BUG: $mid0 undefined\n";
87         my $im = $self->importer;
88         my $cmt = $im->add($mime);
89         $cmt = $im->get_mark($cmt);
90         my ($oid, $len, $msgref) = @{$im->{last_object}};
91
92         my $nparts = $self->{partitions};
93         my $part = $num % $nparts;
94         my $idx = $self->idx_part($part);
95         $idx->index_raw($len, $msgref, $num, $oid, $mid0);
96         my $n = $self->{transact_bytes} += $len;
97         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
98                 $self->checkpoint;
99         }
100
101         $mime;
102 }
103
104 sub num_for {
105         my ($self, $mime, $mid0) = @_;
106         my $mids = mids($mime->header_obj);
107         if (@$mids) {
108                 my $mid = $mids->[0];
109                 my $num = $self->{skel}->{mm}->mid_insert($mid);
110                 if (defined $num) { # common case
111                         $$mid0 = $mid;
112                         return $num;
113                 };
114
115                 # crap, Message-ID is already known, hope somebody just resent:
116                 $self->barrier;
117                 foreach my $m (@$mids) {
118                         # read-only lookup now safe to do after above barrier
119                         my $existing = $self->lookup_content($mime, $m);
120                         if ($existing) {
121                                 warn "<$m> resent\n";
122                                 return; # easy, don't store duplicates
123                         }
124                 }
125
126                 # very unlikely:
127                 warn "<$mid> reused for mismatched content\n";
128                 $self->idx_init;
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 = $dig->clone->hexdigest . '@localhost';
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 = $dig->clone->hexdigest . '@localhost';
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 = $dig->clone->hexdigest . '@localhost';
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         # first time initialization, first we create the skeleton pipe:
189         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
190
191         # need to create all parts before initializing msgmap FD
192         my $max = $self->{partitions} - 1;
193         my $idx = $self->{idx_parts} = [];
194         for my $i (0..$max) {
195                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
196         }
197
198         # Now that all subprocesses are up, we can open the FD for SQLite:
199         $skel->_msgmap_init->{dbh}->begin_work;
200 }
201
202 sub remove {
203         my ($self, $mime, $msg) = @_;
204         my $existing = $self->lookup_content($mime) or return;
205
206         # don't touch ghosts or already junked messages
207         return unless $existing->type eq 'mail';
208
209         # always write removals to the current (latest) git repo since
210         # we process chronologically
211         my $im = $self->importer;
212         my ($cmt, undef) = $im->remove($mime, $msg);
213         $cmt = $im->get_mark($cmt);
214         $self->unindex_msg($existing, $cmt);
215 }
216
217 sub done {
218         my ($self) = @_;
219         my $im = delete $self->{im};
220         $im->done if $im; # PublicInbox::Import::done
221         $self->searchidx_checkpoint(0);
222 }
223
224 sub checkpoint {
225         my ($self) = @_;
226         my $im = $self->{im};
227         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
228         $self->searchidx_checkpoint(1);
229 }
230
231 # issue a write barrier to ensure all data is visible to other processes
232 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
233 sub barrier {
234         my ($self) = @_;
235
236         # For safety, we ensure git checkpoint is complete before because
237         # the data in git is still more important than what is in Xapian.
238         # Performance may be gained by delaying ->progress call but we
239         # lose safety
240         if (my $im = $self->{im}) {
241                 $im->checkpoint;
242                 $im->progress('checkpoint');
243         }
244         my $skel = $self->{skel};
245         my $parts = $self->{idx_parts};
246         if ($parts && $skel) {
247                 my $dbh = $skel->{mm}->{dbh};
248                 $dbh->commit; # SQLite data is second in importance
249
250                 # Now deal with Xapian
251                 $skel->barrier_init(scalar(@$parts));
252                 # each partition needs to issue a barrier command to skel:
253                 $_->barrier foreach @$parts;
254
255                 $skel->barrier_wait; # wait for each Xapian partition
256
257                 $dbh->begin_work;
258         }
259         $self->{transact_bytes} = 0;
260 }
261
262 sub searchidx_checkpoint {
263         my ($self, $more) = @_;
264
265         # order matters, we can only close {skel} after all partitions
266         # are done because the partitions also write to {skel}
267         if (my $parts = $self->{idx_parts}) {
268                 foreach my $idx (@$parts) {
269                         $idx->remote_commit; # propagates commit to skel
270                         $idx->remote_close unless $more;
271                 }
272                 delete $self->{idx_parts} unless $more;
273         }
274
275         if (my $skel = $self->{skel}) {
276                 my $dbh = $skel->{mm}->{dbh};
277                 $dbh->commit;
278                 if ($more) {
279                         $dbh->begin_work;
280                 } else {
281                         $skel->remote_close;
282                         delete $self->{skel};
283                 }
284         }
285         $self->{transact_bytes} = 0;
286 }
287
288 sub git_init {
289         my ($self, $new) = @_;
290         my $pfx = "$self->{-inbox}->{mainrepo}/git";
291         my $git_dir = "$pfx/$new.git";
292         die "$git_dir exists\n" if -e $git_dir;
293         my @cmd = (qw(git init --bare -q), $git_dir);
294         PublicInbox::Import::run_die(\@cmd);
295
296         my $all = "$self->{-inbox}->{mainrepo}/all.git";
297         unless (-d $all) {
298                 @cmd = (qw(git init --bare -q), $all);
299                 PublicInbox::Import::run_die(\@cmd);
300                 @cmd = (qw/git config/, "--file=$all/config",
301                                 'repack.writeBitmaps', 'true');
302                 PublicInbox::Import::run_die(\@cmd);
303         }
304
305         @cmd = (qw/git config/, "--file=$git_dir/config",
306                         'include.path', '../../all.git/config');
307         PublicInbox::Import::run_die(\@cmd);
308
309         my $alt = "$all/objects/info/alternates";
310         my $new_obj_dir = "../../git/$new.git/objects";
311         my %alts;
312         if (-e $alt) {
313                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
314                 %alts = map { chomp; $_ => 1 } (<$fh>);
315         }
316         return $git_dir if $alts{$new_obj_dir};
317         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
318         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
319         close $fh or die "close $alt: $!\n";
320         $git_dir
321 }
322
323 sub importer {
324         my ($self) = @_;
325         my $im = $self->{im};
326         if ($im) {
327                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
328                         return $im;
329                 } else {
330                         $self->{im} = undef;
331                         $im->done;
332                         $self->searchidx_checkpoint(1);
333                         $im = undef;
334                         my $git_dir = $self->git_init(++$self->{max_git});
335                         my $git = PublicInbox::Git->new($git_dir);
336                         return $self->import_init($git, 0);
337                 }
338         }
339         my $latest;
340         my $max = -1;
341         my $new = 0;
342         my $pfx = "$self->{-inbox}->{mainrepo}/git";
343         if (-d $pfx) {
344                 foreach my $git_dir (glob("$pfx/*.git")) {
345                         $git_dir =~ m!/(\d+)\.git\z! or next;
346                         my $n = $1;
347                         if ($n > $max) {
348                                 $max = $n;
349                                 $latest = $git_dir;
350                         }
351                 }
352         }
353         if (defined $latest) {
354                 my $git = PublicInbox::Git->new($latest);
355                 my $packed_bytes = $git->packed_bytes;
356                 if ($packed_bytes >= $self->{rotate_bytes}) {
357                         $new = $max + 1;
358                 } else {
359                         $self->{max_git} = $max;
360                         return $self->import_init($git, $packed_bytes);
361                 }
362         }
363         $self->{max_git} = $new;
364         $latest = $self->git_init($new);
365         $self->import_init(PublicInbox::Git->new($latest), 0);
366 }
367
368 sub import_init {
369         my ($self, $git, $packed_bytes) = @_;
370         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
371         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
372         $im->{want_object_info} = 1;
373         $im->{ssoma_lock} = 0;
374         $im->{path_type} = 'v2';
375         $self->{im} = $im;
376 }
377
378 sub lookup_content {
379         my ($self, $mime, $mid) = @_;
380         my $ibx = $self->{-inbox};
381
382         my $srch = $ibx->search;
383         $srch->reopen;
384         my $cid = content_id($mime);
385         my $found;
386         $srch->each_smsg_by_mid($mid, sub {
387                 my ($smsg) = @_;
388                 $smsg->load_expand;
389                 my $msg = $ibx->msg_by_smsg($smsg);
390                 if (!defined($msg)) {
391                         warn "broken smsg for $mid\n";
392                         return 1; # continue
393                 }
394                 my $cur = PublicInbox::MIME->new($msg);
395                 if (content_id($cur) eq $cid) {
396                         $smsg->{mime} = $cur;
397                         $found = $smsg;
398                         return 0; # break out of loop
399                 }
400                 1; # continue
401         });
402         $found;
403 }
404
405 sub atfork_child {
406         my ($self) = @_;
407         if (my $parts = $self->{idx_parts}) {
408                 $_->atfork_child foreach @$parts;
409         }
410         if (my $im = $self->{im}) {
411                 $im->atfork_child;
412         }
413 }
414
415 1;