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