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