]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
caabc8e4a885f660a5e31d982f3ef3796491a027
[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 my $NPROC = int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
23
24 sub new {
25         my ($class, $v2ibx, $creat) = @_;
26         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
27         unless (-d $dir) {
28                 if ($creat) {
29                         require File::Path;
30                         File::Path::mkpath($dir);
31                 } else {
32                         die "$dir does not exist\n";
33                 }
34         }
35         my $self = {
36                 -inbox => $v2ibx,
37                 im => undef, #  PublicInbox::Import
38                 xap_rw => undef, # PublicInbox::V2SearchIdx
39                 xap_ro => undef,
40                 partitions => $NPROC,
41                 transact_bytes => 0,
42                 # limit each repo to 1GB or so
43                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
44         };
45         bless $self, $class
46 }
47
48 # returns undef on duplicate or spam
49 # mimics Import::add and wraps it for v2
50 sub add {
51         my ($self, $mime, $check_cb) = @_;
52
53         # spam check:
54         if ($check_cb) {
55                 $mime = $check_cb->($mime) or return;
56         }
57
58         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
59         # as does SQLite 3.4.1+ (released in 2007-07-20), and
60         # Xapian 1.3.2+ (released 2015-03-15).
61         # For the most part, we can spawn git-fast-import without
62         # leaking FDs to it...
63         $self->idx_init;
64
65         my $mid0;
66         my $num = num_for($self, $mime, \$mid0);
67         defined $num or return; # duplicate
68         defined $mid0 or die "BUG: $mid0 undefined\n";
69         my $im = $self->importer;
70         my $cmt = $im->add($mime);
71         $cmt = $im->get_mark($cmt);
72         my $oid = $im->{last_object_id};
73         my ($len, $msgref) = @{$im->{last_object}};
74
75         my $nparts = $self->{partitions};
76         my $part = $num % $nparts;
77         my $idx = $self->idx_part($part);
78         $idx->index_raw($len, $msgref, $num, $oid, $mid0);
79         my $n = $self->{transact_bytes} += $len;
80         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
81                 $self->checkpoint;
82         }
83
84         $mime;
85 }
86
87 sub num_for {
88         my ($self, $mime, $mid0) = @_;
89         my $mids = mids($mime->header_obj);
90         if (@$mids) {
91                 my $mid = $mids->[0];
92                 my $num = $self->{skel}->{mm}->mid_insert($mid);
93                 if (defined $num) { # common case
94                         $$mid0 = $mid;
95                         return $num;
96                 };
97
98                 # crap, Message-ID is already known, hope somebody just resent:
99                 $self->done; # write barrier, clears $self->{skel}
100                 foreach my $m (@$mids) {
101                         # read-only lookup now safe to do after above barrier
102                         my $existing = $self->lookup_content($mime, $m);
103                         if ($existing) {
104                                 warn "<$m> resent\n";
105                                 return; # easy, don't store duplicates
106                         }
107                 }
108
109                 # very unlikely:
110                 warn "<$mid> reused for mismatched content\n";
111                 $self->idx_init;
112
113                 # try the rest of the mids
114                 foreach my $i (1..$#$mids) {
115                         my $m = $mids->[$i];
116                         $num = $self->{skel}->{mm}->mid_insert($m);
117                         if (defined $num) {
118                                 warn "alternative <$m> for <$mid> found\n";
119                                 $$mid0 = $m;
120                                 return $num;
121                         }
122                 }
123         }
124         # none of the existing Message-IDs are good, generate a new one:
125         num_for_harder($self, $mime, $mid0);
126 }
127
128 sub num_for_harder {
129         my ($self, $mime, $mid0) = @_;
130
131         my $hdr = $mime->header_obj;
132         my $dig = content_digest($mime);
133         $$mid0 = $dig->clone->hexdigest . '@localhost';
134         my $num = $self->{skel}->{mm}->mid_insert($$mid0);
135         unless (defined $num) {
136                 # it's hard to spoof the last Received: header
137                 my @recvd = $hdr->header_raw('Received');
138                 $dig->add("Received: $_") foreach (@recvd);
139                 $$mid0 = $dig->clone->hexdigest . '@localhost';
140                 $num = $self->{skel}->{mm}->mid_insert($$mid0);
141
142                 # fall back to a random Message-ID and give up determinism:
143                 until (defined($num)) {
144                         $dig->add(rand);
145                         $$mid0 = $dig->clone->hexdigest . '@localhost';
146                         warn "using random Message-ID <$$mid0> as fallback\n";
147                         $num = $self->{skel}->{mm}->mid_insert($$mid0);
148                 }
149         }
150         my @cur = $hdr->header_raw('Message-Id');
151         $hdr->header_set('Message-Id', "<$$mid0>", @cur);
152         $num;
153 }
154
155 sub idx_part {
156         my ($self, $part) = @_;
157         $self->{idx_parts}->[$part];
158 }
159
160 # idempotent
161 sub idx_init {
162         my ($self) = @_;
163         return if $self->{idx_parts};
164         my $ibx = $self->{-inbox};
165
166         # do not leak read-only FDs to child processes, we only have these
167         # FDs for duplicate detection so they should not be
168         # frequently activated.
169         delete $ibx->{$_} foreach (qw(git mm search));
170
171         # first time initialization, first we create the skeleton pipe:
172         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
173
174         # need to create all parts before initializing msgmap FD
175         my $max = $self->{partitions} - 1;
176         my $idx = $self->{idx_parts} = [];
177         for my $i (0..$max) {
178                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
179         }
180
181         # Now that all subprocesses are up, we can open the FD for SQLite:
182         $skel->_msgmap_init->{dbh}->begin_work;
183 }
184
185 sub remove {
186         my ($self, $mime, $msg) = @_;
187         my $existing = $self->lookup_content($mime) or return;
188
189         # don't touch ghosts or already junked messages
190         return unless $existing->type eq 'mail';
191
192         # always write removals to the current (latest) git repo since
193         # we process chronologically
194         my $im = $self->importer;
195         my ($cmt, undef) = $im->remove($mime, $msg);
196         $cmt = $im->get_mark($cmt);
197         $self->unindex_msg($existing, $cmt);
198 }
199
200 sub done {
201         my ($self) = @_;
202         my $im = delete $self->{im};
203         $im->done if $im; # PublicInbox::Import::done
204         $self->searchidx_checkpoint(0);
205 }
206
207 sub checkpoint {
208         my ($self) = @_;
209         my $im = $self->{im};
210         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
211         $self->searchidx_checkpoint(1);
212 }
213
214 sub searchidx_checkpoint {
215         my ($self, $more) = @_;
216
217         # order matters, we can only close {skel} after all partitions
218         # are done because the partitions also write to {skel}
219         if (my $parts = $self->{idx_parts}) {
220                 foreach my $idx (@$parts) {
221                         $idx->remote_commit; # propagates commit to skel
222                         $idx->remote_close unless $more;
223                 }
224                 delete $self->{idx_parts} unless $more;
225         }
226
227         if (my $skel = $self->{skel}) {
228                 my $dbh = $skel->{mm}->{dbh};
229                 $dbh->commit;
230                 if ($more) {
231                         $dbh->begin_work;
232                 } else {
233                         $skel->remote_commit; # XXX should be unnecessary...
234                         $skel->remote_close;
235                         delete $self->{skel};
236                 }
237         }
238         $self->{transact_bytes} = 0;
239 }
240
241 sub git_init {
242         my ($self, $new) = @_;
243         my $pfx = "$self->{-inbox}->{mainrepo}/git";
244         my $git_dir = "$pfx/$new.git";
245         die "$git_dir exists\n" if -e $git_dir;
246         my @cmd = (qw(git init --bare -q), $git_dir);
247         PublicInbox::Import::run_die(\@cmd);
248         @cmd = (qw/git config/, "--file=$git_dir/config",
249                         'repack.writeBitmaps', 'true');
250         PublicInbox::Import::run_die(\@cmd);
251
252         my $all = "$self->{-inbox}->{mainrepo}/all.git";
253         unless (-d $all) {
254                 @cmd = (qw(git init --bare -q), $all);
255                 PublicInbox::Import::run_die(\@cmd);
256         }
257
258         my $alt = "$all/objects/info/alternates";
259         my $new_obj_dir = "../../git/$new.git/objects";
260         my %alts;
261         if (-e $alt) {
262                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
263                 %alts = map { chomp; $_ => 1 } (<$fh>);
264         }
265         return $git_dir if $alts{$new_obj_dir};
266         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
267         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
268         close $fh or die "close $alt: $!\n";
269         $git_dir
270 }
271
272 sub importer {
273         my ($self) = @_;
274         my $im = $self->{im};
275         if ($im) {
276                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
277                         return $im;
278                 } else {
279                         $self->{im} = undef;
280                         $im->done;
281                         $self->searchidx_checkpoint(1);
282                         $im = undef;
283                         my $git_dir = $self->git_init(++$self->{max_git});
284                         my $git = PublicInbox::Git->new($git_dir);
285                         return $self->import_init($git, 0);
286                 }
287         }
288         my $latest;
289         my $max = -1;
290         my $new = 0;
291         my $pfx = "$self->{-inbox}->{mainrepo}/git";
292         if (-d $pfx) {
293                 foreach my $git_dir (glob("$pfx/*.git")) {
294                         $git_dir =~ m!/(\d+)\.git\z! or next;
295                         my $n = $1;
296                         if ($n > $max) {
297                                 $max = $n;
298                                 $latest = $git_dir;
299                         }
300                 }
301         }
302         if (defined $latest) {
303                 my $git = PublicInbox::Git->new($latest);
304                 my $packed_bytes = $git->packed_bytes;
305                 if ($packed_bytes >= $self->{rotate_bytes}) {
306                         $new = $max + 1;
307                 } else {
308                         $self->{max_git} = $max;
309                         return $self->import_init($git, $packed_bytes);
310                 }
311         }
312         $self->{max_git} = $new;
313         $latest = $self->git_init($new);
314         $self->import_init(PublicInbox::Git->new($latest), 0);
315 }
316
317 sub import_init {
318         my ($self, $git, $packed_bytes) = @_;
319         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
320         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
321         $im->{want_object_id} = 1;
322         $im->{ssoma_lock} = 0;
323         $im->{path_type} = 'v2';
324         $self->{im} = $im;
325 }
326
327 sub lookup_content {
328         my ($self, $mime, $mid) = @_;
329         my $ibx = $self->{-inbox};
330
331         my $srch = $ibx->search;
332         my $cid = content_id($mime);
333         my $found;
334         $srch->each_smsg_by_mid($mid, sub {
335                 my ($smsg) = @_;
336                 $smsg->load_expand;
337                 my $msg = $ibx->msg_by_smsg($smsg);
338                 if (!defined($msg)) {
339                         warn "broken smsg for $mid\n";
340                         return 1; # continue
341                 }
342                 my $cur = PublicInbox::MIME->new($msg);
343                 if (content_id($cur) eq $cid) {
344                         $smsg->{mime} = $cur;
345                         $found = $smsg;
346                         return 0; # break out of loop
347                 }
348                 1; # continue
349         });
350         $found;
351 }
352
353 sub atfork_child {
354         my ($self) = @_;
355         if (my $parts = $self->{idx_parts}) {
356                 $_->atfork_child foreach @$parts;
357         }
358         if (my $im = $self->{im}) {
359                 $im->atfork_child;
360         }
361 }
362
363 1;