]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
import: force Message-ID generation for v1 here
[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
129                 # try the rest of the mids
130                 foreach my $i (1..$#$mids) {
131                         my $m = $mids->[$i];
132                         $num = $self->{skel}->{mm}->mid_insert($m);
133                         if (defined $num) {
134                                 warn "alternative <$m> for <$mid> found\n";
135                                 $$mid0 = $m;
136                                 return $num;
137                         }
138                 }
139         }
140         # none of the existing Message-IDs are good, generate a new one:
141         num_for_harder($self, $mime, $mid0);
142 }
143
144 sub num_for_harder {
145         my ($self, $mime, $mid0) = @_;
146
147         my $hdr = $mime->header_obj;
148         my $dig = content_digest($mime);
149         $$mid0 = PublicInbox::Import::digest2mid($dig);
150         my $num = $self->{skel}->{mm}->mid_insert($$mid0);
151         unless (defined $num) {
152                 # it's hard to spoof the last Received: header
153                 my @recvd = $hdr->header_raw('Received');
154                 $dig->add("Received: $_") foreach (@recvd);
155                 $$mid0 = PublicInbox::Import::digest2mid($dig);
156                 $num = $self->{skel}->{mm}->mid_insert($$mid0);
157
158                 # fall back to a random Message-ID and give up determinism:
159                 until (defined($num)) {
160                         $dig->add(rand);
161                         $$mid0 = PublicInbox::Import::digest2mid($dig);
162                         warn "using random Message-ID <$$mid0> as fallback\n";
163                         $num = $self->{skel}->{mm}->mid_insert($$mid0);
164                 }
165         }
166         my @cur = $hdr->header_raw('Message-Id');
167         $hdr->header_set('Message-Id', "<$$mid0>", @cur);
168         $num;
169 }
170
171 sub idx_part {
172         my ($self, $part) = @_;
173         $self->{idx_parts}->[$part];
174 }
175
176 # idempotent
177 sub idx_init {
178         my ($self) = @_;
179         return if $self->{idx_parts};
180         my $ibx = $self->{-inbox};
181
182         # do not leak read-only FDs to child processes, we only have these
183         # FDs for duplicate detection so they should not be
184         # frequently activated.
185         delete $ibx->{$_} foreach (qw(git mm search));
186
187         # first time initialization, first we create the skeleton pipe:
188         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
189
190         # need to create all parts before initializing msgmap FD
191         my $max = $self->{partitions} - 1;
192         my $idx = $self->{idx_parts} = [];
193         for my $i (0..$max) {
194                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
195         }
196
197         # Now that all subprocesses are up, we can open the FD for SQLite:
198         $skel->_msgmap_init->{dbh}->begin_work;
199 }
200
201 sub remove {
202         my ($self, $mime, $cmt_msg) = @_;
203         $self->barrier;
204         $self->idx_init;
205         my $im = $self->importer;
206         my $ibx = $self->{-inbox};
207         my $srch = $ibx->search;
208         my $cid = content_id($mime);
209         my $skel = $self->{skel};
210         my $parts = $self->{idx_parts};
211         my $mm = $skel->{mm};
212         my $removed;
213         my $mids = mids($mime->header_obj);
214         foreach my $mid (@$mids) {
215                 $srch->reopen->each_smsg_by_mid($mid, sub {
216                         my ($smsg) = @_;
217                         $smsg->load_expand;
218                         my $msg = $ibx->msg_by_smsg($smsg);
219                         if (!defined($msg)) {
220                                 warn "broken smsg for $mid\n";
221                                 return 1; # continue
222                         }
223                         my $orig = $$msg;
224                         my $cur = PublicInbox::MIME->new($msg);
225                         if (content_id($cur) eq $cid) {
226                                 $mm->num_delete($smsg->num);
227                                 # $removed should only be set once assuming
228                                 # no bugs in our deduplication code:
229                                 $removed = $smsg;
230                                 $removed->{mime} = $cur;
231                                 $im->remove(\$orig, $cmt_msg);
232                                 $orig = undef;
233                                 $removed->num; # memoize this for callers
234
235                                 my $oid = $smsg->{blob};
236                                 foreach my $idx (@$parts, $skel) {
237                                         $idx->remote_remove($oid, $mid);
238                                 }
239                         }
240                         1; # continue
241                 });
242                 $self->barrier;
243         }
244         $removed;
245 }
246
247 sub done {
248         my ($self) = @_;
249         my $im = delete $self->{im};
250         $im->done if $im; # PublicInbox::Import::done
251         $self->searchidx_checkpoint(0);
252 }
253
254 sub checkpoint {
255         my ($self) = @_;
256         my $im = $self->{im};
257         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
258         $self->searchidx_checkpoint(1);
259 }
260
261 # issue a write barrier to ensure all data is visible to other processes
262 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
263 sub barrier {
264         my ($self) = @_;
265
266         if (my $im = $self->{im}) {
267                 $im->barrier;
268         }
269         my $skel = $self->{skel};
270         my $parts = $self->{idx_parts};
271         if ($parts && $skel) {
272                 my $dbh = $skel->{mm}->{dbh};
273                 $dbh->commit; # SQLite data is second in importance
274
275                 # Now deal with Xapian
276                 $skel->barrier_init(scalar(@$parts));
277                 # each partition needs to issue a barrier command to skel:
278                 $_->barrier foreach @$parts;
279
280                 $skel->barrier_wait; # wait for each Xapian partition
281
282                 $dbh->begin_work;
283         }
284         $self->{transact_bytes} = 0;
285 }
286
287 sub searchidx_checkpoint {
288         my ($self, $more) = @_;
289
290         # order matters, we can only close {skel} after all partitions
291         # are done because the partitions also write to {skel}
292         if (my $parts = $self->{idx_parts}) {
293                 foreach my $idx (@$parts) {
294                         $idx->remote_commit; # propagates commit to skel
295                         $idx->remote_close unless $more;
296                 }
297                 delete $self->{idx_parts} unless $more;
298         }
299
300         if (my $skel = $self->{skel}) {
301                 my $dbh = $skel->{mm}->{dbh};
302                 $dbh->commit;
303                 if ($more) {
304                         $dbh->begin_work;
305                 } else {
306                         $skel->remote_close;
307                         delete $self->{skel};
308                 }
309         }
310         $self->{transact_bytes} = 0;
311 }
312
313 sub git_init {
314         my ($self, $new) = @_;
315         my $pfx = "$self->{-inbox}->{mainrepo}/git";
316         my $git_dir = "$pfx/$new.git";
317         die "$git_dir exists\n" if -e $git_dir;
318         my @cmd = (qw(git init --bare -q), $git_dir);
319         PublicInbox::Import::run_die(\@cmd);
320
321         my $all = "$self->{-inbox}->{mainrepo}/all.git";
322         unless (-d $all) {
323                 @cmd = (qw(git init --bare -q), $all);
324                 PublicInbox::Import::run_die(\@cmd);
325                 @cmd = (qw/git config/, "--file=$all/config",
326                                 'repack.writeBitmaps', 'true');
327                 PublicInbox::Import::run_die(\@cmd);
328         }
329
330         @cmd = (qw/git config/, "--file=$git_dir/config",
331                         'include.path', '../../all.git/config');
332         PublicInbox::Import::run_die(\@cmd);
333
334         my $alt = "$all/objects/info/alternates";
335         my $new_obj_dir = "../../git/$new.git/objects";
336         my %alts;
337         if (-e $alt) {
338                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
339                 %alts = map { chomp; $_ => 1 } (<$fh>);
340         }
341         return $git_dir if $alts{$new_obj_dir};
342         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
343         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
344         close $fh or die "close $alt: $!\n";
345         $git_dir
346 }
347
348 sub importer {
349         my ($self) = @_;
350         my $im = $self->{im};
351         if ($im) {
352                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
353                         return $im;
354                 } else {
355                         $self->{im} = undef;
356                         $im->done;
357                         $self->searchidx_checkpoint(1);
358                         $im = undef;
359                         my $git_dir = $self->git_init(++$self->{max_git});
360                         my $git = PublicInbox::Git->new($git_dir);
361                         return $self->import_init($git, 0);
362                 }
363         }
364         my $latest;
365         my $max = -1;
366         my $new = 0;
367         my $pfx = "$self->{-inbox}->{mainrepo}/git";
368         if (-d $pfx) {
369                 foreach my $git_dir (glob("$pfx/*.git")) {
370                         $git_dir =~ m!/(\d+)\.git\z! or next;
371                         my $n = $1;
372                         if ($n > $max) {
373                                 $max = $n;
374                                 $latest = $git_dir;
375                         }
376                 }
377         }
378         if (defined $latest) {
379                 my $git = PublicInbox::Git->new($latest);
380                 my $packed_bytes = $git->packed_bytes;
381                 if ($packed_bytes >= $self->{rotate_bytes}) {
382                         $new = $max + 1;
383                 } else {
384                         $self->{max_git} = $max;
385                         return $self->import_init($git, $packed_bytes);
386                 }
387         }
388         $self->{max_git} = $new;
389         $latest = $self->git_init($new);
390         $self->import_init(PublicInbox::Git->new($latest), 0);
391 }
392
393 sub import_init {
394         my ($self, $git, $packed_bytes) = @_;
395         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
396         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
397         $im->{want_object_info} = 1;
398         $im->{ssoma_lock} = 0;
399         $im->{path_type} = 'v2';
400         $self->{im} = $im;
401 }
402
403 sub lookup_content {
404         my ($self, $mime, $mid) = @_;
405         my $ibx = $self->{-inbox};
406
407         my $srch = $ibx->search->reopen;
408         my $cid = content_id($mime);
409         my $found;
410         $srch->each_smsg_by_mid($mid, sub {
411                 my ($smsg) = @_;
412                 $smsg->load_expand;
413                 my $msg = $ibx->msg_by_smsg($smsg);
414                 if (!defined($msg)) {
415                         warn "broken smsg for $mid\n";
416                         return 1; # continue
417                 }
418                 my $cur = PublicInbox::MIME->new($msg);
419                 if (content_id($cur) eq $cid) {
420                         $smsg->{mime} = $cur;
421                         $found = $smsg;
422                         return 0; # break out of loop
423                 }
424                 1; # continue
425         });
426         $found;
427 }
428
429 sub atfork_child {
430         my ($self) = @_;
431         if (my $parts = $self->{idx_parts}) {
432                 $_->atfork_child foreach @$parts;
433         }
434         if (my $im = $self->{im}) {
435                 $im->atfork_child;
436         }
437 }
438
439 1;