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