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