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>
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;
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::MsgTime qw(msg_timestamp);
17 my ($class, $git, $name, $email, $ibx) = @_;
18 my $ref = 'refs/heads/master';
20 $ref = $ibx->{ref_head} || 'refs/heads/master';
21 $name ||= $ibx->{name};
22 $email ||= $ibx->{-primary_address};
26 ident => "$name <$email>",
30 path_type => '2/38', # or 'v2'
31 ssoma_lock => 1, # disable for v2
36 # idempotent start function
40 return ($self->{in}, $self->{out}) if $self->{pid};
42 my ($in_r, $in_w, $out_r, $out_w);
43 pipe($in_r, $in_w) or die "pipe failed: $!";
44 pipe($out_r, $out_w) or die "pipe failed: $!";
45 my $git = $self->{git};
46 my $git_dir = $git->{git_dir};
49 if ($self->{ssoma_lock}) {
50 my $lockpath = "$git_dir/ssoma.lock";
51 sysopen($lockfh, $lockpath, O_WRONLY|O_CREAT) or
52 die "failed to open lock $lockpath: $!";
53 # wait for other processes to be done
54 flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
58 chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
60 my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
61 --quiet --done --date-format=raw));
62 my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
63 my $pid = spawn(\@cmd, undef, $rdr);
64 die "spawn fast-import failed: $!" unless defined $pid;
67 $self->{out} = $out_w;
68 $self->{lockfh} = $lockfh;
71 binmode $out_w, ':raw' or die "binmode :raw failed: $!";
72 binmode $in_r, ':raw' or die "binmode :raw failed: $!";
76 sub wfail () { die "write to fast-import failed: $!" }
78 sub now_raw () { time . ' +0000' }
82 my $b = $mime->body_raw;
83 $b =~ s/(\r?\n)+\z//s;
87 # only used for v1 (ssoma) inboxes
88 sub _check_path ($$$$) {
89 my ($r, $w, $tip, $path) = @_;
91 print $w "ls $tip $path\n" or wfail;
93 defined(my $info = <$r>) or die "EOF from fast-import: $!";
94 $info =~ /\Amissing / ? undef : $info;
98 my ($r, $w, $tip, $path, $mime) = @_;
100 my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
101 $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
104 print $w "cat-blob $blob\n" or wfail;
107 defined $info or die "EOF from fast-import / cat-blob: $!";
108 $info =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
109 die "unexpected cat-blob response: $info";
115 $n = read($r, $buf, $left, $offset);
116 defined($n) or die "read cat-blob failed: $!";
117 $n == 0 and die 'fast-export (cat-blob) died';
121 $n = read($r, my $lf, 1);
122 defined($n) or die "read final byte of cat-blob failed: $!";
123 die "bad read on final byte: <$lf>" if $lf ne "\n";
124 my $cur = PublicInbox::MIME->new(\$buf);
125 my $cur_s = $cur->header('Subject');
126 $cur_s = '' unless defined $cur_s;
127 my $cur_m = $mime->header('Subject');
128 $cur_m = '' unless defined $cur_m;
129 if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
130 return ('MISMATCH', $cur);
137 return unless $self->{pid};
138 print { $self->{out} } "checkpoint\n" or wfail;
143 my ($self, $msg) = @_;
144 return unless $self->{pid};
145 print { $self->{out} } "progress $msg\n" or wfail;
146 $self->{in}->getline eq "progress $msg\n" or die
147 "progress $msg not received\n";
151 sub _update_git_info ($$) {
152 my ($self, $do_gc) = @_;
153 # for compatibility with existing ssoma installations
154 # we can probably remove this entirely by 2020
155 my $git_dir = $self->{git}->{git_dir};
156 my @cmd = ('git', "--git-dir=$git_dir");
157 my $index = "$git_dir/ssoma.index";
158 if (-e $index && !$ENV{FAST}) {
159 my $env = { GIT_INDEX_FILE => $index };
160 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
162 run_die([@cmd, 'update-server-info'], undef);
163 ($self->{path_type} eq '2/38') and eval {
164 require PublicInbox::SearchIdx;
165 my $inbox = $self->{inbox} || $git_dir;
166 my $s = PublicInbox::SearchIdx->new($inbox);
167 $s->index_sync({ ref => $self->{ref} });
169 eval { run_die([@cmd, qw(gc --auto)], undef) } if $do_gc;
175 # For safety, we ensure git checkpoint is complete before because
176 # the data in git is still more important than what is in Xapian
177 # in v2. Performance may be gained by delaying the ->progress
178 # call but we lose safety
181 $self->progress('checkpoint');
182 _update_git_info($self, 0);
189 my ($self, $mark) = @_;
190 die "not active\n" unless $self->{pid};
191 my ($r, $w) = $self->gfi_start;
192 print $w "get-mark $mark\n" or wfail;
193 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
197 # returns undef on non-existent
198 # ('MISMATCH', Email::MIME) on mismatch
199 # (:MARK, Email::MIME) on success
201 # v2 callers should check with Xapian before calling this as
202 # it is not idempotent.
204 my ($self, $mime, $msg) = @_; # mime = Email::MIME
206 my $path_type = $self->{path_type};
207 my ($path, $err, $cur, $blob);
209 my ($r, $w) = $self->gfi_start;
210 my $tip = $self->{tip};
211 if ($path_type eq '2/38') {
212 $path = mid2path(mid_mime($mime));
213 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
214 return ($err, $cur) if $err;
217 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
219 } else { # XXX should not be necessary:
220 my $str = $mime->as_string;
223 my $len = length($$sref);
224 $blob = $self->{mark}++;
225 print $w "blob\nmark :$blob\ndata $len\n",
226 $$sref, "\n" or wfail;
229 my $ref = $self->{ref};
230 my $commit = $self->{mark}++;
231 my $parent = $tip =~ /\A:/ ? $tip : undef;
233 print $w "reset $ref\n" or wfail;
235 my $ident = $self->{ident};
238 my $len = length($msg) + 1;
239 print $w "commit $ref\nmark :$commit\n",
240 "author $ident $now\n",
241 "committer $ident $now\n",
242 "data $len\n$msg\n\n",
243 'from ', ($parent ? $parent : $tip), "\n" or wfail;
245 print $w "D $path\n\n" or wfail;
247 print $w "M 100644 :$blob _/D\n\n" or wfail;
250 (($self->{tip} = ":$commit"), $cur);
255 my ($ts, $zone) = msg_timestamp($mime->header_obj);
256 $ts = 0 if $ts < 0; # git uses unsigned times
260 sub extract_author_info ($) {
264 my $from = $mime->header('From');
265 my ($email) = PublicInbox::Address::emails($from);
266 my ($name) = PublicInbox::Address::names($from);
267 if (!defined($name) || !defined($email)) {
268 $sender = $mime->header('Sender');
269 if (!defined($name)) {
270 ($name) = PublicInbox::Address::names($sender);
272 if (!defined($email)) {
273 ($email) = PublicInbox::Address::emails($sender);
276 if (defined $email) {
277 # quiet down wide character warnings with utf8::encode
278 utf8::encode($email);
281 warn "no email in From: $from or Sender: $sender\n";
284 # git gets confused with:
285 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
287 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
293 warn "no name in From: $from or Sender: $sender\n";
298 # returns undef on duplicate
299 # returns the :MARK of the most recent commit
301 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
303 my ($name, $email) = extract_author_info($mime);
304 my $date_raw = parse_date($mime);
305 my $subject = $mime->header('Subject');
306 $subject = '(no subject)' unless defined $subject;
307 my $path_type = $self->{path_type};
310 if ($path_type eq '2/38') {
311 $path = mid2path(mid_mime($mime));
312 } else { # v2 layout, one file:
316 my ($r, $w) = $self->gfi_start;
317 my $tip = $self->{tip};
318 if ($path_type eq '2/38') {
319 _check_path($r, $w, $tip, $path) and return;
322 # kill potentially confusing/misleading headers
323 $mime->header_set($_) for qw(bytes lines content-length status);
327 $mime = $check_cb->($mime) or return;
330 my $blob = $self->{mark}++;
331 my $str = $mime->as_string;
332 my $n = length($str);
333 $self->{bytes_added} += $n;
334 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
335 print $w $str, "\n" or wfail;
337 # v2: we need this for Xapian
338 if ($self->{want_object_info}) {
339 chomp(my $oid = $self->get_mark(":$blob"));
340 $self->{last_object} = [ $oid, $n, \$str ];
342 my $ref = $self->{ref};
343 my $commit = $self->{mark}++;
344 my $parent = $tip =~ /\A:/ ? $tip : undef;
347 print $w "reset $ref\n" or wfail;
350 utf8::encode($subject);
351 print $w "commit $ref\nmark :$commit\n",
352 "author $name <$email> $date_raw\n",
353 "committer $self->{ident} ", now_raw(), "\n" or wfail;
354 print $w "data ", (length($subject) + 1), "\n",
355 $subject, "\n\n" or wfail;
357 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
359 print $w "M 100644 :$blob $path\n\n" or wfail;
361 $self->{tip} = ":$commit";
365 my ($cmd, $env) = @_;
366 my $pid = spawn($cmd, $env, undef);
367 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
368 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
369 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
374 my $w = delete $self->{out} or return;
375 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
376 print $w "done\n" or wfail;
377 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
378 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
379 $? == 0 or die "fast-import failed: $?";
381 _update_git_info($self, 1) if delete $self->{nchg};
383 $self->{ssoma_lock} or return;
384 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
385 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
386 close $lockfh or die "close lock failed: $!";
391 foreach my $f (qw(in out)) {
392 close $self->{$f} or die "failed to close import[$f]: $!\n";
402 PublicInbox::Import - message importer for public-inbox
411 use PublicInbox::Git;
412 use PublicInbox::Import;
414 chomp(my $git_dir = `git rev-parse --git-dir`);
415 $git_dir or die "GIT_DIR= must be specified\n";
416 my $git = PublicInbox::Git->new($git_dir);
417 my @committer = ('inbox', 'inbox@example.org');
418 my $im = PublicInbox::Import->new($git, @committer);
421 my $message = "From: <u\@example.org>\n".
422 "Subject: test message \n" .
423 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
424 "Message-ID: <m\@example.org>\n".
426 my $parsed = Email::MIME->new($message);
427 my $ret = $im->add($parsed);
430 $parsed->header_obj->header_raw('Message-ID'), "\n";
432 print "imported at mark $ret\n";
436 # to remove a message
437 my $junk = Email::MIME->new($message);
438 my ($mark, $orig) = $im->remove($junk);
439 if ($mark eq 'MISSING') {
441 } elsif ($mark eq 'MISMATCH') {
442 print "Message exists but does not match\n\n",
443 $orig->as_string, "\n",;
445 print "removed at mark $mark\n\n",
446 $orig->as_string, "\n";
452 An importer and remover for public-inboxes which takes L<Email::MIME>
453 messages as input and stores them in a ssoma repository as
454 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
455 except it does not allow duplicate Message-IDs.
457 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
465 my $im = PublicInbox::Import->new($git, @committer);
467 Initialize a new PublicInbox::Import object.
471 my $parsed = Email::MIME->new($message);
474 Adds a message to to the git repository. This will acquire
475 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
477 Messages added will not be visible to other processes until L</done>
478 is called, but L</remove> may be called on them.
482 my $junk = Email::MIME->new($message);
483 my ($code, $orig) = $im->remove($junk);
485 Removes a message from the repository. On success, it returns
486 a ':'-prefixed numeric code representing the git-fast-import
487 mark and the original messages as an Email::MIME object.
488 If the message could not be found, the code is "MISSING"
489 and the original message is undef. If there is a mismatch where
490 the "Message-ID" is matched but the subject and body do not match,
491 the returned code is "MISMATCH" and the conflicting message
496 Finalizes the L<git-fast-import(1)> and unlocks the repository.
497 Calling this is required to finalize changes to a repository.
505 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
507 The mail archives are hosted at L<https://public-inbox.org/meta/>
511 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
513 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>