]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
import: implement barrier operation for v1 repos
[public-inbox.git] / lib / PublicInbox / Import.pm
1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # git fast-import-based ssoma-mda MDA replacement
5 # This is only ever run by public-inbox-mda and public-inbox-learn,
6 # not the WWW or NNTP code which only requires read-only access.
7 package PublicInbox::Import;
8 use strict;
9 use warnings;
10 use Fcntl qw(:flock :DEFAULT);
11 use PublicInbox::Spawn qw(spawn);
12 use PublicInbox::MID qw(mid_mime mid2path);
13 use PublicInbox::Address;
14 use PublicInbox::MsgTime qw(msg_timestamp);
15
16 sub new {
17         my ($class, $git, $name, $email, $ibx) = @_;
18         my $ref = 'refs/heads/master';
19         if ($ibx) {
20                 $ref = $ibx->{ref_head} || 'refs/heads/master';
21                 $name ||= $ibx->{name};
22                 $email ||= $ibx->{-primary_address};
23         }
24         bless {
25                 git => $git,
26                 ident => "$name <$email>",
27                 mark => 1,
28                 ref => $ref,
29                 inbox => $ibx,
30                 path_type => '2/38', # or 'v2'
31                 ssoma_lock => 1, # disable for v2
32                 bytes_added => 0,
33         }, $class
34 }
35
36 # idempotent start function
37 sub gfi_start {
38         my ($self) = @_;
39
40         return ($self->{in}, $self->{out}) if $self->{pid};
41
42         my ($in_r, $in_w, $out_r, $out_w);
43         pipe($in_r, $in_w) or die "pipe failed: $!";
44         pipe($out_r, $out_w) or die "pipe failed: $!";
45         my $git = $self->{git};
46         my $git_dir = $git->{git_dir};
47
48         my $lockfh;
49         if ($self->{ssoma_lock}) {
50                 my $lockpath = "$git_dir/ssoma.lock";
51                 sysopen($lockfh, $lockpath, O_WRONLY|O_CREAT) or
52                         die "failed to open lock $lockpath: $!";
53                 # wait for other processes to be done
54                 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
55         }
56
57         local $/ = "\n";
58         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
59
60         my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
61                         --quiet --done --date-format=raw));
62         my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
63         my $pid = spawn(\@cmd, undef, $rdr);
64         die "spawn fast-import failed: $!" unless defined $pid;
65         $out_w->autoflush(1);
66         $self->{in} = $in_r;
67         $self->{out} = $out_w;
68         $self->{lockfh} = $lockfh;
69         $self->{pid} = $pid;
70         $self->{nchg} = 0;
71         binmode $out_w, ':raw' or die "binmode :raw failed: $!";
72         binmode $in_r, ':raw' or die "binmode :raw failed: $!";
73         ($in_r, $out_w);
74 }
75
76 sub wfail () { die "write to fast-import failed: $!" }
77
78 sub now_raw () { time . ' +0000' }
79
80 sub norm_body ($) {
81         my ($mime) = @_;
82         my $b = $mime->body_raw;
83         $b =~ s/(\r?\n)+\z//s;
84         $b
85 }
86
87 # only used for v1 (ssoma) inboxes
88 sub _check_path ($$$$) {
89         my ($r, $w, $tip, $path) = @_;
90         return if $tip eq '';
91         print $w "ls $tip $path\n" or wfail;
92         local $/ = "\n";
93         defined(my $info = <$r>) or die "EOF from fast-import: $!";
94         $info =~ /\Amissing / ? undef : $info;
95 }
96
97 sub check_remove_v1 {
98         my ($r, $w, $tip, $path, $mime) = @_;
99
100         my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
101         $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
102         my $blob = $1;
103
104         print $w "cat-blob $blob\n" or wfail;
105         local $/ = "\n";
106         $info = <$r>;
107         defined $info or die "EOF from fast-import / cat-blob: $!";
108         $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
109                                 die "unexpected cat-blob response: $info";
110         my $left = $1;
111         my $offset = 0;
112         my $buf = '';
113         my $n;
114         while ($left > 0) {
115                 $n = read($r, $buf, $left, $offset);
116                 defined($n) or die "read cat-blob failed: $!";
117                 $n == 0 and die 'fast-export (cat-blob) died';
118                 $left -= $n;
119                 $offset += $n;
120         }
121         $n = read($r, my $lf, 1);
122         defined($n) or die "read final byte of cat-blob failed: $!";
123         die "bad read on final byte: <$lf>" if $lf ne "\n";
124         my $cur = PublicInbox::MIME->new(\$buf);
125         my $cur_s = $cur->header('Subject');
126         $cur_s = '' unless defined $cur_s;
127         my $cur_m = $mime->header('Subject');
128         $cur_m = '' unless defined $cur_m;
129         if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
130                 return ('MISMATCH', $cur);
131         }
132         (undef, $cur);
133 }
134
135 sub checkpoint {
136         my ($self) = @_;
137         return unless $self->{pid};
138         print { $self->{out} } "checkpoint\n" or wfail;
139         undef;
140 }
141
142 sub progress {
143         my ($self, $msg) = @_;
144         return unless $self->{pid};
145         print { $self->{out} } "progress $msg\n" or wfail;
146         $self->{in}->getline eq "progress $msg\n" or die
147                 "progress $msg not received\n";
148         undef;
149 }
150
151 sub _update_git_info ($$) {
152         my ($self, $do_gc) = @_;
153         # for compatibility with existing ssoma installations
154         # we can probably remove this entirely by 2020
155         my $git_dir = $self->{git}->{git_dir};
156         my @cmd = ('git', "--git-dir=$git_dir");
157         my $index = "$git_dir/ssoma.index";
158         if (-e $index && !$ENV{FAST}) {
159                 my $env = { GIT_INDEX_FILE => $index };
160                 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
161         }
162         run_die([@cmd, 'update-server-info'], undef);
163         ($self->{path_type} eq '2/38') and eval {
164                 require PublicInbox::SearchIdx;
165                 my $inbox = $self->{inbox} || $git_dir;
166                 my $s = PublicInbox::SearchIdx->new($inbox);
167                 $s->index_sync({ ref => $self->{ref} });
168         };
169         eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
170 }
171
172 sub barrier {
173         my ($self) = @_;
174
175         # For safety, we ensure git checkpoint is complete before because
176         # the data in git is still more important than what is in Xapian
177         # in v2.  Performance may be gained by delaying the ->progress
178         # call but we lose safety
179         if ($self->{nchg}) {
180                 $self->checkpoint;
181                 $self->progress('checkpoint');
182                 _update_git_info($self, 0);
183                 $self->{nchg} = 0;
184         }
185 }
186
187 # used for v2
188 sub get_mark {
189         my ($self, $mark) = @_;
190         die "not active\n" unless $self->{pid};
191         my ($r, $w) = $self->gfi_start;
192         print $w "get-mark $mark\n" or wfail;
193         defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
194         $oid;
195 }
196
197 # returns undef on non-existent
198 # ('MISMATCH', Email::MIME) on mismatch
199 # (:MARK, Email::MIME) on success
200 #
201 # v2 callers should check with Xapian before calling this as
202 # it is not idempotent.
203 sub remove {
204         my ($self, $mime, $msg) = @_; # mime = Email::MIME
205
206         my $path_type = $self->{path_type};
207         my ($path, $err, $cur, $blob);
208
209         my ($r, $w) = $self->gfi_start;
210         my $tip = $self->{tip};
211         if ($path_type eq '2/38') {
212                 $path = mid2path(mid_mime($mime));
213                 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
214                 return ($err, $cur) if $err;
215         } else {
216                 my $sref;
217                 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
218                         $sref = $mime;
219                 } else { # XXX should not be necessary:
220                         my $str = $mime->as_string;
221                         $sref = \$str;
222                 }
223                 my $len = length($$sref);
224                 $blob = $self->{mark}++;
225                 print $w "blob\nmark :$blob\ndata $len\n",
226                         $$sref, "\n" or wfail;
227         }
228
229         my $ref = $self->{ref};
230         my $commit = $self->{mark}++;
231         my $parent = $tip =~ /\A:/ ? $tip : undef;
232         unless ($parent) {
233                 print $w "reset $ref\n" or wfail;
234         }
235         my $ident = $self->{ident};
236         my $now = now_raw();
237         $msg ||= 'rm';
238         my $len = length($msg) + 1;
239         print $w "commit $ref\nmark :$commit\n",
240                 "author $ident $now\n",
241                 "committer $ident $now\n",
242                 "data $len\n$msg\n\n",
243                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
244         if (defined $path) {
245                 print $w "D $path\n\n" or wfail;
246         } else {
247                 print $w "M 100644 :$blob _/D\n\n" or wfail;
248         }
249         $self->{nchg}++;
250         (($self->{tip} = ":$commit"), $cur);
251 }
252
253 sub parse_date ($) {
254         my ($mime) = @_;
255         my ($ts, $zone) = msg_timestamp($mime->header_obj);
256         $ts = 0 if $ts < 0; # git uses unsigned times
257         "$ts $zone";
258 }
259
260 sub extract_author_info ($) {
261         my ($mime) = @_;
262
263         my $sender = '';
264         my $from = $mime->header('From');
265         my ($email) = PublicInbox::Address::emails($from);
266         my ($name) = PublicInbox::Address::names($from);
267         if (!defined($name) || !defined($email)) {
268                 $sender = $mime->header('Sender');
269                 if (!defined($name)) {
270                         ($name) = PublicInbox::Address::names($sender);
271                 }
272                 if (!defined($email)) {
273                         ($email) = PublicInbox::Address::emails($sender);
274                 }
275         }
276         if (defined $email) {
277                 # quiet down wide character warnings with utf8::encode
278                 utf8::encode($email);
279         } else {
280                 $email = '';
281                 warn "no email in From: $from or Sender: $sender\n";
282         }
283
284         # git gets confused with:
285         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
286         # ref:
287         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
288         if (defined $name) {
289                 $name =~ tr/<>//d;
290                 utf8::encode($name);
291         } else {
292                 $name = '';
293                 warn "no name in From: $from or Sender: $sender\n";
294         }
295         ($name, $email);
296 }
297
298 # returns undef on duplicate
299 # returns the :MARK of the most recent commit
300 sub add {
301         my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
302
303         my ($name, $email) = extract_author_info($mime);
304         my $date_raw = parse_date($mime);
305         my $subject = $mime->header('Subject');
306         $subject = '(no subject)' unless defined $subject;
307         my $path_type = $self->{path_type};
308
309         my $path;
310         if ($path_type eq '2/38') {
311                 $path = mid2path(mid_mime($mime));
312         } else { # v2 layout, one file:
313                 $path = 'm';
314         }
315
316         my ($r, $w) = $self->gfi_start;
317         my $tip = $self->{tip};
318         if ($path_type eq '2/38') {
319                 _check_path($r, $w, $tip, $path) and return;
320         }
321
322         # kill potentially confusing/misleading headers
323         $mime->header_set($_) for qw(bytes lines content-length status);
324
325         # spam check:
326         if ($check_cb) {
327                 $mime = $check_cb->($mime) or return;
328         }
329
330         my $blob = $self->{mark}++;
331         my $str = $mime->as_string;
332         my $n = length($str);
333         $self->{bytes_added} += $n;
334         print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
335         print $w $str, "\n" or wfail;
336
337         # v2: we need this for Xapian
338         if ($self->{want_object_info}) {
339                 chomp(my $oid = $self->get_mark(":$blob"));
340                 $self->{last_object} = [ $oid, $n, \$str ];
341         }
342         my $ref = $self->{ref};
343         my $commit = $self->{mark}++;
344         my $parent = $tip =~ /\A:/ ? $tip : undef;
345
346         unless ($parent) {
347                 print $w "reset $ref\n" or wfail;
348         }
349
350         utf8::encode($subject);
351         print $w "commit $ref\nmark :$commit\n",
352                 "author $name <$email> $date_raw\n",
353                 "committer $self->{ident} ", now_raw(), "\n" or wfail;
354         print $w "data ", (length($subject) + 1), "\n",
355                 $subject, "\n\n" or wfail;
356         if ($tip ne '') {
357                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
358         }
359         print $w "M 100644 :$blob $path\n\n" or wfail;
360         $self->{nchg}++;
361         $self->{tip} = ":$commit";
362 }
363
364 sub run_die ($;$) {
365         my ($cmd, $env) = @_;
366         my $pid = spawn($cmd, $env, undef);
367         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
368         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
369         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
370 }
371
372 sub done {
373         my ($self) = @_;
374         my $w = delete $self->{out} or return;
375         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
376         print $w "done\n" or wfail;
377         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
378         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
379         $? == 0 or die "fast-import failed: $?";
380
381         _update_git_info($self, 1) if delete $self->{nchg};
382
383         $self->{ssoma_lock} or return;
384         my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
385         flock($lockfh, LOCK_UN) or die "unlock failed: $!";
386         close $lockfh or die "close lock failed: $!";
387 }
388
389 sub atfork_child {
390         my ($self) = @_;
391         foreach my $f (qw(in out)) {
392                 close $self->{$f} or die "failed to close import[$f]: $!\n";
393         }
394 }
395
396 1;
397 __END__
398 =pod
399
400 =head1 NAME
401
402 PublicInbox::Import - message importer for public-inbox
403
404 =head1 VERSION
405
406 version 1.0
407
408 =head1 SYNOPSYS
409
410         use Email::MIME;
411         use PublicInbox::Git;
412         use PublicInbox::Import;
413
414         chomp(my $git_dir = `git rev-parse --git-dir`);
415         $git_dir or die "GIT_DIR= must be specified\n";
416         my $git = PublicInbox::Git->new($git_dir);
417         my @committer = ('inbox', 'inbox@example.org');
418         my $im = PublicInbox::Import->new($git, @committer);
419
420         # to add a message:
421         my $message = "From: <u\@example.org>\n".
422                 "Subject: test message \n" .
423                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
424                 "Message-ID: <m\@example.org>\n".
425                 "\ntest message";
426         my $parsed = Email::MIME->new($message);
427         my $ret = $im->add($parsed);
428         if (!defined $ret) {
429                 warn "duplicate: ",
430                         $parsed->header_obj->header_raw('Message-ID'), "\n";
431         } else {
432                 print "imported at mark $ret\n";
433         }
434         $im->done;
435
436         # to remove a message
437         my $junk = Email::MIME->new($message);
438         my ($mark, $orig) = $im->remove($junk);
439         if ($mark eq 'MISSING') {
440                 print "not found\n";
441         } elsif ($mark eq 'MISMATCH') {
442                 print "Message exists but does not match\n\n",
443                         $orig->as_string, "\n",;
444         } else {
445                 print "removed at mark $mark\n\n",
446                         $orig->as_string, "\n";
447         }
448         $im->done;
449
450 =head1 DESCRIPTION
451
452 An importer and remover for public-inboxes which takes L<Email::MIME>
453 messages as input and stores them in a ssoma repository as
454 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
455 except it does not allow duplicate Message-IDs.
456
457 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
458
459 =head1 METHODS
460
461 =cut
462
463 =head2 new
464
465         my $im = PublicInbox::Import->new($git, @committer);
466
467 Initialize a new PublicInbox::Import object.
468
469 =head2 add
470
471         my $parsed = Email::MIME->new($message);
472         $im->add($parsed);
473
474 Adds a message to to the git repository.  This will acquire
475 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
476
477 Messages added will not be visible to other processes until L</done>
478 is called, but L</remove> may be called on them.
479
480 =head2 remove
481
482         my $junk = Email::MIME->new($message);
483         my ($code, $orig) = $im->remove($junk);
484
485 Removes a message from the repository.  On success, it returns
486 a ':'-prefixed numeric code representing the git-fast-import
487 mark and the original messages as an Email::MIME object.
488 If the message could not be found, the code is "MISSING"
489 and the original message is undef.  If there is a mismatch where
490 the "Message-ID" is matched but the subject and body do not match,
491 the returned code is "MISMATCH" and the conflicting message
492 is returned as orig.
493
494 =head2 done
495
496 Finalizes the L<git-fast-import(1)> and unlocks the repository.
497 Calling this is required to finalize changes to a repository.
498
499 =head1 SEE ALSO
500
501 L<Email::MIME>
502
503 =head1 CONTACT
504
505 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
506
507 The mail archives are hosted at L<https://public-inbox.org/meta/>
508
509 =head1 COPYRIGHT
510
511 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
512
513 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
514
515 =cut