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";
153 my ($self, $mark) = @_;
154 die "not active\n" unless $self->{pid};
155 my ($r, $w) = $self->gfi_start;
156 print $w "get-mark $mark\n" or wfail;
157 defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
161 # returns undef on non-existent
162 # ('MISMATCH', Email::MIME) on mismatch
163 # (:MARK, Email::MIME) on success
165 # v2 callers should check with Xapian before calling this as
166 # it is not idempotent.
168 my ($self, $mime, $msg) = @_; # mime = Email::MIME
170 my $path_type = $self->{path_type};
171 my ($path, $err, $cur, $blob);
173 my ($r, $w) = $self->gfi_start;
174 my $tip = $self->{tip};
175 if ($path_type eq '2/38') {
176 $path = mid2path(mid_mime($mime));
177 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
178 return ($err, $cur) if $err;
181 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
183 } else { # XXX should not be necessary:
184 my $str = $mime->as_string;
187 my $len = length($$sref);
188 $blob = $self->{mark}++;
189 print $w "blob\nmark :$blob\ndata $len\n",
190 $$sref, "\n" or wfail;
193 my $ref = $self->{ref};
194 my $commit = $self->{mark}++;
195 my $parent = $tip =~ /\A:/ ? $tip : undef;
197 print $w "reset $ref\n" or wfail;
199 my $ident = $self->{ident};
202 my $len = length($msg) + 1;
203 print $w "commit $ref\nmark :$commit\n",
204 "author $ident $now\n",
205 "committer $ident $now\n",
206 "data $len\n$msg\n\n",
207 'from ', ($parent ? $parent : $tip), "\n" or wfail;
209 print $w "D $path\n\n" or wfail;
211 print $w "M 100644 :$blob _/D\n\n" or wfail;
214 (($self->{tip} = ":$commit"), $cur);
219 my ($ts, $zone) = msg_timestamp($mime->header_obj);
220 $ts = 0 if $ts < 0; # git uses unsigned times
224 sub extract_author_info ($) {
228 my $from = $mime->header('From');
229 my ($email) = PublicInbox::Address::emails($from);
230 my ($name) = PublicInbox::Address::names($from);
231 if (!defined($name) || !defined($email)) {
232 $sender = $mime->header('Sender');
233 if (!defined($name)) {
234 ($name) = PublicInbox::Address::names($sender);
236 if (!defined($email)) {
237 ($email) = PublicInbox::Address::emails($sender);
240 if (defined $email) {
241 # quiet down wide character warnings with utf8::encode
242 utf8::encode($email);
245 warn "no email in From: $from or Sender: $sender\n";
248 # git gets confused with:
249 # "'A U Thor <u@example.com>' via foo" <foo@example.com>
251 # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
257 warn "no name in From: $from or Sender: $sender\n";
262 # returns undef on duplicate
263 # returns the :MARK of the most recent commit
265 my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
267 my ($name, $email) = extract_author_info($mime);
268 my $date_raw = parse_date($mime);
269 my $subject = $mime->header('Subject');
270 $subject = '(no subject)' unless defined $subject;
271 my $path_type = $self->{path_type};
274 if ($path_type eq '2/38') {
275 $path = mid2path(mid_mime($mime));
276 } else { # v2 layout, one file:
280 my ($r, $w) = $self->gfi_start;
281 my $tip = $self->{tip};
282 if ($path_type eq '2/38') {
283 _check_path($r, $w, $tip, $path) and return;
286 # kill potentially confusing/misleading headers
287 $mime->header_set($_) for qw(bytes lines content-length status);
291 $mime = $check_cb->($mime) or return;
294 my $blob = $self->{mark}++;
295 my $str = $mime->as_string;
296 my $n = length($str);
297 $self->{bytes_added} += $n;
298 print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
299 print $w $str, "\n" or wfail;
301 # v2: we need this for Xapian
302 if ($self->{want_object_info}) {
303 chomp(my $oid = $self->get_mark(":$blob"));
304 $self->{last_object} = [ $oid, $n, \$str ];
306 my $ref = $self->{ref};
307 my $commit = $self->{mark}++;
308 my $parent = $tip =~ /\A:/ ? $tip : undef;
311 print $w "reset $ref\n" or wfail;
314 utf8::encode($subject);
315 print $w "commit $ref\nmark :$commit\n",
316 "author $name <$email> $date_raw\n",
317 "committer $self->{ident} ", now_raw(), "\n" or wfail;
318 print $w "data ", (length($subject) + 1), "\n",
319 $subject, "\n\n" or wfail;
321 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
323 print $w "M 100644 :$blob $path\n\n" or wfail;
325 $self->{tip} = ":$commit";
329 my ($cmd, $env) = @_;
330 my $pid = spawn($cmd, $env, undef);
331 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
332 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
333 $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
338 my $w = delete $self->{out} or return;
339 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
340 print $w "done\n" or wfail;
341 my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
342 waitpid($pid, 0) == $pid or die 'fast-import did not finish';
343 $? == 0 or die "fast-import failed: $?";
344 my $nchg = delete $self->{nchg};
346 # for compatibility with existing ssoma installations
347 # we can probably remove this entirely by 2020
348 my $git_dir = $self->{git}->{git_dir};
349 my @cmd = ('git', "--git-dir=$git_dir");
350 my $index = "$git_dir/ssoma.index";
351 if ($nchg && -e $index && !$ENV{FAST}) {
352 my $env = { GIT_INDEX_FILE => $index };
353 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
356 run_die([@cmd, 'update-server-info'], undef);
357 ($self->{path_type} eq '2/38') and eval {
358 require PublicInbox::SearchIdx;
359 my $inbox = $self->{inbox} || $git_dir;
360 my $s = PublicInbox::SearchIdx->new($inbox);
361 $s->index_sync({ ref => $self->{ref} });
364 eval { run_die([@cmd, qw(gc --auto)], undef) };
367 $self->{ssoma_lock} or return;
368 my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
369 flock($lockfh, LOCK_UN) or die "unlock failed: $!";
370 close $lockfh or die "close lock failed: $!";
375 foreach my $f (qw(in out)) {
376 close $self->{$f} or die "failed to close import[$f]: $!\n";
386 PublicInbox::Import - message importer for public-inbox
395 use PublicInbox::Git;
396 use PublicInbox::Import;
398 chomp(my $git_dir = `git rev-parse --git-dir`);
399 $git_dir or die "GIT_DIR= must be specified\n";
400 my $git = PublicInbox::Git->new($git_dir);
401 my @committer = ('inbox', 'inbox@example.org');
402 my $im = PublicInbox::Import->new($git, @committer);
405 my $message = "From: <u\@example.org>\n".
406 "Subject: test message \n" .
407 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
408 "Message-ID: <m\@example.org>\n".
410 my $parsed = Email::MIME->new($message);
411 my $ret = $im->add($parsed);
414 $parsed->header_obj->header_raw('Message-ID'), "\n";
416 print "imported at mark $ret\n";
420 # to remove a message
421 my $junk = Email::MIME->new($message);
422 my ($mark, $orig) = $im->remove($junk);
423 if ($mark eq 'MISSING') {
425 } elsif ($mark eq 'MISMATCH') {
426 print "Message exists but does not match\n\n",
427 $orig->as_string, "\n",;
429 print "removed at mark $mark\n\n",
430 $orig->as_string, "\n";
436 An importer and remover for public-inboxes which takes L<Email::MIME>
437 messages as input and stores them in a ssoma repository as
438 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
439 except it does not allow duplicate Message-IDs.
441 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
449 my $im = PublicInbox::Import->new($git, @committer);
451 Initialize a new PublicInbox::Import object.
455 my $parsed = Email::MIME->new($message);
458 Adds a message to to the git repository. This will acquire
459 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
461 Messages added will not be visible to other processes until L</done>
462 is called, but L</remove> may be called on them.
466 my $junk = Email::MIME->new($message);
467 my ($code, $orig) = $im->remove($junk);
469 Removes a message from the repository. On success, it returns
470 a ':'-prefixed numeric code representing the git-fast-import
471 mark and the original messages as an Email::MIME object.
472 If the message could not be found, the code is "MISSING"
473 and the original message is undef. If there is a mismatch where
474 the "Message-ID" is matched but the subject and body do not match,
475 the returned code is "MISMATCH" and the conflicting message
480 Finalizes the L<git-fast-import(1)> and unlocks the repository.
481 Calling this is required to finalize changes to a repository.
489 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
491 The mail archives are hosted at L<https://public-inbox.org/meta/>
495 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
497 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>