]> Sergey Matveev's repositories - public-inbox.git/blob - script/public-inbox-init
No ext_urls
[public-inbox.git] / script / public-inbox-init
1 #!perl -w
2 # Copyright (C) 2014-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict;
5 use v5.10.1;
6 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
7 use Fcntl qw(:DEFAULT);
8 my $help = <<EOF; # the following should fit w/o scrolling in 80x24 term:
9 usage: public-inbox-init NAME INBOX_DIR HTTP_URL ADDRESS [ADDRESS..]
10
11   Initialize a public-inbox
12
13 required arguments:
14
15   NAME                the name of the inbox
16   INBOX_DIR           pathname the inbox
17   HTTP_URL            HTTP (or HTTPS) URL
18   ADDRESS             email address(es), may be specified multiple times
19
20 options:
21
22   -V2                 use scalable public-inbox-v2-format(5)
23   -L LEVEL            index level `basic', `medium', or `full' (default: full)
24   --ng NEWSGROUP      set NNTP newsgroup name
25   -c KEY=VALUE        set additional config option(s)
26   --skip-artnum=NUM   NNTP article numbers to skip
27   --skip-epoch=NUM    epochs to skip (-V2 only)
28   -j JOBS             number of indexing jobs (-V2 only), (default: 4)
29
30 See public-inbox-init(1) man page for full documentation.
31 EOF
32
33 require PublicInbox::Admin;
34 PublicInbox::Admin::require_or_die('-base');
35
36 my ($version, $indexlevel, $skip_epoch, $skip_artnum, $jobs, $show_help);
37 my $skip_docdata;
38 my $ng = '';
39 my (@c_extra, @chdir);
40 my %opts = (
41         'V|version=i' => \$version,
42         'L|index-level|indexlevel=s' => \$indexlevel,
43         'S|skip|skip-epoch=i' => \$skip_epoch,
44         'skip-artnum=i' => \$skip_artnum,
45         'j|jobs=i' => \$jobs,
46         'ng|newsgroup=s' => \$ng,
47         'skip-docdata' => \$skip_docdata,
48         'help|h' => \$show_help,
49         'c=s@' => \@c_extra,
50         'C=s@' => \@chdir,
51 );
52 my $usage_cb = sub {
53         print STDERR $help;
54         exit 1;
55 };
56 GetOptions(%opts) or $usage_cb->();
57 if ($show_help) { print $help; exit 0 };
58 my $name = shift @ARGV or $usage_cb->();
59 my $inboxdir = shift @ARGV or $usage_cb->();
60 my $http_url = shift @ARGV or $usage_cb->();
61 my (@address) = @ARGV;
62 @address or $usage_cb->();
63 +PublicInbox::Admin::do_chdir(\@chdir);
64
65 @c_extra = map {
66         my ($k, $v) = split(/=/, $_, 2);
67         defined($v) or die "Usage: -c KEY=VALUE\n";
68         $k =~ /\A[a-z]+\z/i or die "$k contains invalid characters\n";
69         $k = lc($k);
70         if ($k eq 'newsgroup') {
71                 die "newsgroup already set ($ng)\n" if $ng ne '';
72                 $ng = $v;
73                 ();
74         } elsif ($k eq 'address') {
75                 push @address, $v; # for conflict checking
76                 ();
77         } elsif ($k =~ /\A(?:inboxdir|mainrepo)\z/) {
78                 die "$k not allowed via -c $_\n"
79         } elsif ($k eq 'indexlevel') {
80                 defined($indexlevel) and
81                         die "indexlevel already set ($indexlevel)\n";
82                 $indexlevel = $v;
83                 ();
84         } else {
85                 $_
86         }
87 } @c_extra;
88
89 PublicInbox::Admin::indexlevel_ok_or_die($indexlevel) if defined $indexlevel;
90
91 $ng =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! and
92         die "--newsgroup `$ng' is not valid\n";
93 ($ng =~ m!\A\.! || $ng =~ m!\.\z!) and
94         die "--newsgroup `$ng' must not start or end with `.'\n";
95
96 require PublicInbox::Config;
97 my $pi_config = PublicInbox::Config->default_file;
98 my ($dir) = ($pi_config =~ m!(.*?/)[^/]+\z!);
99 require File::Path;
100 File::Path::mkpath($dir); # will croak on fatal errors
101
102 # first, we grab a flock to prevent simultaneous public-inbox-init
103 # processes from trampling over each other, or exiting with 255 on
104 # O_EXCL failure below.  This gets unlocked automatically on exit:
105 require PublicInbox::Lock;
106 my $lock_obj = { lock_path => "$pi_config.flock" };
107 PublicInbox::Lock::lock_acquire($lock_obj);
108
109 # git-config will operate on this (and rename on success):
110 require File::Temp;
111 my $fh = File::Temp->new(TEMPLATE => 'pi-init-XXXX', DIR => $dir);
112
113 # Now, we grab another lock to use git-config(1) locking, so it won't
114 # wait on the lock, unlike some of our internal flock()-based locks.
115 # This is to prevent direct git-config(1) usage from clobbering our
116 # changes.
117 my $lockfile = "$pi_config.lock";
118 my $lockfh;
119 sysopen($lockfh, $lockfile, O_RDWR|O_CREAT|O_EXCL) or do {
120         warn "could not open config file: $lockfile: $!\n";
121         exit(255);
122 };
123 require PublicInbox::OnDestroy;
124 my $auto_unlink = PublicInbox::OnDestroy->new($$, sub { unlink $lockfile });
125 my ($perm, %seen);
126 if (-e $pi_config) {
127         open(my $oh, '<', $pi_config) or die "unable to read $pi_config: $!\n";
128         my @st = stat($oh);
129         $perm = $st[2];
130         defined $perm or die "(f)stat failed on $pi_config: $!\n";
131         chmod($perm & 07777, $fh) or
132                 die "(f)chmod failed on future $pi_config: $!\n";
133         defined(my $old = do { local $/; <$oh> }) or die "read $pi_config: $!\n";
134         print $fh $old or die "failed to write: $!\n";
135         close $oh or die "failed to close $pi_config: $!\n";
136
137         # yes, this conflict checking is racy if multiple instances of this
138         # script are run by the same $PI_DIR
139         my $cfg = PublicInbox::Config->new;
140         my $conflict;
141         foreach my $addr (@address) {
142                 my $found = $cfg->lookup($addr);
143                 if ($found) {
144                         if ($found->{name} ne $name) {
145                                 print STDERR
146                                         "`$addr' already defined for ",
147                                         "`$found->{name}',\n",
148                                         "does not match intend `$name'\n";
149                                 $conflict = 1;
150                         } else {
151                                 $seen{lc($addr)} = 1;
152                         }
153                 }
154         }
155
156         exit(1) if $conflict;
157
158         my $ibx = $cfg->lookup_name($name);
159         $indexlevel //= $ibx->{indexlevel} if $ibx;
160 }
161 my $pi_config_tmp = $fh->filename;
162 close($fh) or die "failed to close $pi_config_tmp: $!\n";
163
164 my $pfx = "publicinbox.$name";
165 my @x = (qw/git config/, "--file=$pi_config_tmp");
166
167 $inboxdir = PublicInbox::Config::rel2abs_collapsed($inboxdir);
168 die "`\\n' not allowed in `$inboxdir'\n" if index($inboxdir, "\n") >= 0;
169
170 if (-f "$inboxdir/inbox.lock") {
171         if (!defined $version) {
172                 $version = 2;
173         } elsif ($version != 2) {
174                 die "$inboxdir is a -V2 inbox, -V$version specified\n"
175         }
176 } elsif (-d "$inboxdir/objects") {
177         if (!defined $version) {
178                 $version = 1;
179         } elsif ($version != 1) {
180                 die "$inboxdir is a -V1 inbox, -V$version specified\n"
181         }
182 }
183
184 $version = 1 unless defined $version;
185
186 if ($version == 1 && defined $skip_epoch) {
187         die "--skip-epoch is only supported for -V2 inboxes\n";
188 }
189
190 my $ibx = PublicInbox::Inbox->new({
191         inboxdir => $inboxdir,
192         name => $name,
193         version => $version,
194         -primary_address => $address[0],
195         indexlevel => $indexlevel,
196 });
197
198 my $creat_opt = {};
199 if (defined $jobs) {
200         die "--jobs is only supported for -V2 inboxes\n" if $version == 1;
201         die "--jobs=$jobs must be >= 1\n" if $jobs <= 0;
202         $creat_opt->{nproc} = $jobs;
203 }
204
205 require PublicInbox::InboxWritable;
206 $ibx = PublicInbox::InboxWritable->new($ibx, $creat_opt);
207 if ($skip_docdata) {
208         $ibx->{indexlevel} //= 'full'; # ensure init_inbox writes xdb
209         $ibx->{indexlevel} eq 'basic' and
210                 die "--skip-docdata ignored with --indexlevel=basic\n";
211         $ibx->{-skip_docdata} = $skip_docdata;
212 }
213 $ibx->init_inbox(0, $skip_epoch, $skip_artnum);
214
215 my $f = "$inboxdir/description";
216 if (sysopen $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
217         print $fh "public inbox for $address[0]\n" or die "print($f): $!";
218         close $fh or die "close($f): $!";
219 }
220
221 # needed for git prior to v2.1.0
222 umask(0077) if defined $perm;
223
224 require PublicInbox::Spawn;
225 PublicInbox::Spawn->import(qw(run_die));
226
227 foreach my $addr (@address) {
228         next if $seen{lc($addr)};
229         run_die([@x, "--add", "$pfx.address", $addr]);
230 }
231 run_die([@x, "$pfx.url", $http_url]);
232 run_die([@x, "$pfx.inboxdir", $inboxdir]);
233
234 if (defined($indexlevel)) {
235         run_die([@x, "$pfx.indexlevel", $indexlevel]);
236 }
237 run_die([@x, "$pfx.newsgroup", $ng]) if $ng ne '';
238
239 for my $kv (@c_extra) {
240         my ($k, $v) = split(/=/, $kv, 2);
241         # git 2.30+ has --fixed-value for idempotent invocations,
242         # but that's too new to depend on in 2021.  Perl quotemeta
243         # seems compatible enough for POSIX ERE which git uses
244         my $re = '^'.quotemeta($v).'$';
245         run_die([@x, qw(--replace-all), "$pfx.$k", $v, $re]);
246 }
247
248 # needed for git prior to v2.1.0
249 if (defined $perm) {
250         chmod($perm & 07777, $pi_config_tmp) or
251                         die "(f)chmod failed on future $pi_config: $!\n";
252 }
253
254 rename $pi_config_tmp, $pi_config or
255         die "failed to rename `$pi_config_tmp' to `$pi_config': $!\n";
256 undef $auto_unlink; # trigger ->DESTROY