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