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