]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
import: (v2): write deletes to a separate '_' subdirectory
[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 # used for v2
152 sub get_mark {
153         my ($self, $mark) = @_;
154         die "not active\n" unless $self->{pid};
155         my ($r, $w) = $self->gfi_start;
156         print $w "get-mark $mark\n" or wfail;
157         defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
158         $oid;
159 }
160
161 # returns undef on non-existent
162 # ('MISMATCH', Email::MIME) on mismatch
163 # (:MARK, Email::MIME) on success
164 #
165 # v2 callers should check with Xapian before calling this as
166 # it is not idempotent.
167 sub remove {
168         my ($self, $mime, $msg) = @_; # mime = Email::MIME
169
170         my $path_type = $self->{path_type};
171         my ($path, $err, $cur, $blob);
172
173         my ($r, $w) = $self->gfi_start;
174         my $tip = $self->{tip};
175         if ($path_type eq '2/38') {
176                 $path = mid2path(mid_mime($mime));
177                 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
178                 return ($err, $cur) if $err;
179         } else {
180                 my $sref;
181                 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
182                         $sref = $mime;
183                 } else { # XXX should not be necessary:
184                         my $str = $mime->as_string;
185                         $sref = \$str;
186                 }
187                 my $len = length($$sref);
188                 $blob = $self->{mark}++;
189                 print $w "blob\nmark :$blob\ndata $len\n",
190                         $$sref, "\n" or wfail;
191         }
192
193         my $ref = $self->{ref};
194         my $commit = $self->{mark}++;
195         my $parent = $tip =~ /\A:/ ? $tip : undef;
196         unless ($parent) {
197                 print $w "reset $ref\n" or wfail;
198         }
199         my $ident = $self->{ident};
200         my $now = now_raw();
201         $msg ||= 'rm';
202         my $len = length($msg) + 1;
203         print $w "commit $ref\nmark :$commit\n",
204                 "author $ident $now\n",
205                 "committer $ident $now\n",
206                 "data $len\n$msg\n\n",
207                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
208         if (defined $path) {
209                 print $w "D $path\n\n" or wfail;
210         } else {
211                 print $w "M 100644 :$blob _/D\n\n" or wfail;
212         }
213         $self->{nchg}++;
214         (($self->{tip} = ":$commit"), $cur);
215 }
216
217 sub parse_date ($) {
218         my ($mime) = @_;
219         my ($ts, $zone) = msg_timestamp($mime->header_obj);
220         $ts = 0 if $ts < 0; # git uses unsigned times
221         "$ts $zone";
222 }
223
224 sub extract_author_info ($) {
225         my ($mime) = @_;
226
227         my $sender = '';
228         my $from = $mime->header('From');
229         my ($email) = PublicInbox::Address::emails($from);
230         my ($name) = PublicInbox::Address::names($from);
231         if (!defined($name) || !defined($email)) {
232                 $sender = $mime->header('Sender');
233                 if (!defined($name)) {
234                         ($name) = PublicInbox::Address::names($sender);
235                 }
236                 if (!defined($email)) {
237                         ($email) = PublicInbox::Address::emails($sender);
238                 }
239         }
240         if (defined $email) {
241                 # quiet down wide character warnings with utf8::encode
242                 utf8::encode($email);
243         } else {
244                 $email = '';
245                 warn "no email in From: $from or Sender: $sender\n";
246         }
247
248         # git gets confused with:
249         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
250         # ref:
251         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
252         if (defined $name) {
253                 $name =~ tr/<>//d;
254                 utf8::encode($name);
255         } else {
256                 $name = '';
257                 warn "no name in From: $from or Sender: $sender\n";
258         }
259         ($name, $email);
260 }
261
262 # returns undef on duplicate
263 # returns the :MARK of the most recent commit
264 sub add {
265         my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
266
267         my ($name, $email) = extract_author_info($mime);
268         my $date_raw = parse_date($mime);
269         my $subject = $mime->header('Subject');
270         $subject = '(no subject)' unless defined $subject;
271         my $path_type = $self->{path_type};
272
273         my $path;
274         if ($path_type eq '2/38') {
275                 $path = mid2path(mid_mime($mime));
276         } else { # v2 layout, one file:
277                 $path = 'm';
278         }
279
280         my ($r, $w) = $self->gfi_start;
281         my $tip = $self->{tip};
282         if ($path_type eq '2/38') {
283                 _check_path($r, $w, $tip, $path) and return;
284         }
285
286         # kill potentially confusing/misleading headers
287         $mime->header_set($_) for qw(bytes lines content-length status);
288
289         # spam check:
290         if ($check_cb) {
291                 $mime = $check_cb->($mime) or return;
292         }
293
294         my $blob = $self->{mark}++;
295         my $str = $mime->as_string;
296         my $n = length($str);
297         $self->{bytes_added} += $n;
298         print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
299         print $w $str, "\n" or wfail;
300
301         # v2: we need this for Xapian
302         if ($self->{want_object_info}) {
303                 chomp(my $oid = $self->get_mark(":$blob"));
304                 $self->{last_object} = [ $oid, $n, \$str ];
305         }
306         my $ref = $self->{ref};
307         my $commit = $self->{mark}++;
308         my $parent = $tip =~ /\A:/ ? $tip : undef;
309
310         unless ($parent) {
311                 print $w "reset $ref\n" or wfail;
312         }
313
314         utf8::encode($subject);
315         print $w "commit $ref\nmark :$commit\n",
316                 "author $name <$email> $date_raw\n",
317                 "committer $self->{ident} ", now_raw(), "\n" or wfail;
318         print $w "data ", (length($subject) + 1), "\n",
319                 $subject, "\n\n" or wfail;
320         if ($tip ne '') {
321                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
322         }
323         print $w "M 100644 :$blob $path\n\n" or wfail;
324         $self->{nchg}++;
325         $self->{tip} = ":$commit";
326 }
327
328 sub run_die ($;$) {
329         my ($cmd, $env) = @_;
330         my $pid = spawn($cmd, $env, undef);
331         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
332         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
333         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
334 }
335
336 sub done {
337         my ($self) = @_;
338         my $w = delete $self->{out} or return;
339         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
340         print $w "done\n" or wfail;
341         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
342         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
343         $? == 0 or die "fast-import failed: $?";
344         my $nchg = delete $self->{nchg};
345
346         # for compatibility with existing ssoma installations
347         # we can probably remove this entirely by 2020
348         my $git_dir = $self->{git}->{git_dir};
349         my @cmd = ('git', "--git-dir=$git_dir");
350         my $index = "$git_dir/ssoma.index";
351         if ($nchg && -e $index && !$ENV{FAST}) {
352                 my $env = { GIT_INDEX_FILE => $index };
353                 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
354         }
355         if ($nchg) {
356                 run_die([@cmd, 'update-server-info'], undef);
357                 ($self->{path_type} eq '2/38') and eval {
358                         require PublicInbox::SearchIdx;
359                         my $inbox = $self->{inbox} || $git_dir;
360                         my $s = PublicInbox::SearchIdx->new($inbox);
361                         $s->index_sync({ ref => $self->{ref} });
362                 };
363
364                 eval { run_die([@cmd, qw(gc --auto)], undef) };
365         }
366
367         $self->{ssoma_lock} or return;
368         my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
369         flock($lockfh, LOCK_UN) or die "unlock failed: $!";
370         close $lockfh or die "close lock failed: $!";
371 }
372
373 sub atfork_child {
374         my ($self) = @_;
375         foreach my $f (qw(in out)) {
376                 close $self->{$f} or die "failed to close import[$f]: $!\n";
377         }
378 }
379
380 1;
381 __END__
382 =pod
383
384 =head1 NAME
385
386 PublicInbox::Import - message importer for public-inbox
387
388 =head1 VERSION
389
390 version 1.0
391
392 =head1 SYNOPSYS
393
394         use Email::MIME;
395         use PublicInbox::Git;
396         use PublicInbox::Import;
397
398         chomp(my $git_dir = `git rev-parse --git-dir`);
399         $git_dir or die "GIT_DIR= must be specified\n";
400         my $git = PublicInbox::Git->new($git_dir);
401         my @committer = ('inbox', 'inbox@example.org');
402         my $im = PublicInbox::Import->new($git, @committer);
403
404         # to add a message:
405         my $message = "From: <u\@example.org>\n".
406                 "Subject: test message \n" .
407                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
408                 "Message-ID: <m\@example.org>\n".
409                 "\ntest message";
410         my $parsed = Email::MIME->new($message);
411         my $ret = $im->add($parsed);
412         if (!defined $ret) {
413                 warn "duplicate: ",
414                         $parsed->header_obj->header_raw('Message-ID'), "\n";
415         } else {
416                 print "imported at mark $ret\n";
417         }
418         $im->done;
419
420         # to remove a message
421         my $junk = Email::MIME->new($message);
422         my ($mark, $orig) = $im->remove($junk);
423         if ($mark eq 'MISSING') {
424                 print "not found\n";
425         } elsif ($mark eq 'MISMATCH') {
426                 print "Message exists but does not match\n\n",
427                         $orig->as_string, "\n",;
428         } else {
429                 print "removed at mark $mark\n\n",
430                         $orig->as_string, "\n";
431         }
432         $im->done;
433
434 =head1 DESCRIPTION
435
436 An importer and remover for public-inboxes which takes L<Email::MIME>
437 messages as input and stores them in a ssoma repository as
438 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
439 except it does not allow duplicate Message-IDs.
440
441 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
442
443 =head1 METHODS
444
445 =cut
446
447 =head2 new
448
449         my $im = PublicInbox::Import->new($git, @committer);
450
451 Initialize a new PublicInbox::Import object.
452
453 =head2 add
454
455         my $parsed = Email::MIME->new($message);
456         $im->add($parsed);
457
458 Adds a message to to the git repository.  This will acquire
459 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
460
461 Messages added will not be visible to other processes until L</done>
462 is called, but L</remove> may be called on them.
463
464 =head2 remove
465
466         my $junk = Email::MIME->new($message);
467         my ($code, $orig) = $im->remove($junk);
468
469 Removes a message from the repository.  On success, it returns
470 a ':'-prefixed numeric code representing the git-fast-import
471 mark and the original messages as an Email::MIME object.
472 If the message could not be found, the code is "MISSING"
473 and the original message is undef.  If there is a mismatch where
474 the "Message-ID" is matched but the subject and body do not match,
475 the returned code is "MISMATCH" and the conflicting message
476 is returned as orig.
477
478 =head2 done
479
480 Finalizes the L<git-fast-import(1)> and unlocks the repository.
481 Calling this is required to finalize changes to a repository.
482
483 =head1 SEE ALSO
484
485 L<Email::MIME>
486
487 =head1 CONTACT
488
489 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
490
491 The mail archives are hosted at L<https://public-inbox.org/meta/>
492
493 =head1 COPYRIGHT
494
495 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
496
497 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
498
499 =cut