Debian Codegraph @

pg_createcluster

raw
1 #!/usr/bin/perl -w
2
3 # Create new PostgreSQL cluster or integrate an existing data directory into
4 # the postgresql-common infrastructure.
5 #
6 # (C) 2005-2013 Martin Pitt <[email protected]>
7 # (C) 2012-2024 Christoph Berg <[email protected]>
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18
19 use strict;
20 use warnings;
21 use PgCommon;
22 use Getopt::Long;
23 use POSIX qw/lchown setlocale LC_ALL LC_NUMERIC/;
24
25 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin'; # untaint
26
27 my @postgres_user = getpwnam 'postgres';
28 my %defaultconf;
29 my $explicit_auth_config = 0;
30 my $quiet;
31
32 chdir '/';
33
34 # call initdb
35 sub init_db {
36 my ($version, $cluster, $datadir, $owneruid, $ownergid, $local_method, $host_method, $initdb_opts_from_cli) = @_;
37 $datadir = readlink $datadir if (-l $datadir);
38
39 if (system 'install', '-d', '-o', $owneruid, '-g', $ownergid, $datadir) {
40 error 'could not create data directory; you might need to run this program with root privileges';
41 }
42
43 # disable copy-on-write semantics for PostgreSQL data on btrfs and similar;
44 # this fails on file systems which don't support it, so ignore errors
45 system "chattr +C '$datadir' 2>/dev/null";
46
47 my @initdb = (get_program_path 'initdb', $version);
48 die 'Internal error: could not determine initdb path' unless $initdb[0];
49 push @initdb, ('-D', $datadir);
50 if (my $waldir = $defaultconf{'waldir'} || $defaultconf{'xlogdir'}) {
51 my $wal = $version >= 10 ? 'wal' : 'xlog'; # renamed in PG 10
52 push @initdb, ("--${wal}dir", replace_v_c ($waldir, $version, $cluster));
53 }
54 unless ($explicit_auth_config) {
55 if ($version >= '9.2') {
56 push @initdb, ('--auth-local', $local_method);
57 push @initdb, ('--auth-host', $host_method);
58 } else {
59 # trust is the default, but set it explicitly to mute a warning from initdb
60 # the actual method will be filled in by setup_pg_hba()
61 push @initdb, ('-A', 'trust');
62 }
63 }
64
65 # cluster startup message
66 if ($version >= 14) {
67 push @initdb, '--no-instructions';
68 } else {
69 # ask initdb to print a different cluster start command (Debian patch)
70 $ENV{CLUSTER_START_COMMAND} = "pg_ctlcluster $version $cluster start";
71 }
72
73 # options from config and command line
74 if (my $options = $defaultconf{'initdb_options'}) {
75 push @initdb, split (/\s+/, replace_v_c ($options, $version, $cluster));
76 }
77 push @initdb, @$initdb_opts_from_cli;
78
79 if (fork) {
80 wait;
81 error 'initdb failed' if $?;
82 } else{
83 change_ugid $owneruid, $ownergid;
84 print "@initdb\n" unless ($quiet);
85 close STDOUT if ($quiet); # suppress initdb output
86 exec @initdb;
87 }
88 }
89
90 # move a file to a directory with defined permissions; set <postgresql.conf option> in
91 # postgresql.conf.
92 # Arguments: <source file> <target dir> <uid> <gid> <perms> <postgresql.conf option>
93 sub move_conffile {
94 my ($file, $target, $version, $cluster, $uid, $gid, $perms, $confopt) = @_;
95 my $realfile = $file;
96 while (-l $realfile) {
97 $realfile = readlink $realfile;
98 }
99 if (-e $file) {
100 install_file $realfile, $target, $uid, $gid, $perms;
101 unlink $file, $realfile;
102
103 my @pathcomps = split ('/', $file);
104 $target .= '/' . $pathcomps[-1];
105 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf', $confopt, $target if $confopt;
106 } else {
107 error "move_conffile: required configuration file $realfile does not exist";
108 }
109 }
110
111 # Set up the default pg_hba.conf file:
112 # - Add a "local all" entry to pg_hba.conf for the db superuser before all
113 # other entries.
114 # - Change default authentication for host entries to md5.
115 sub setup_pg_hba {
116 my ($version, $owneruid, $confdir, $local_method, $host_method) = @_;
117 my $user = (getpwuid $owneruid)[0];
118 my $fname = "$confdir/pg_hba.conf";
119 my $su_comment = "
120 # DO NOT DISABLE!
121 # If you change this first entry you will need to make sure that the
122 # database superuser can access the database using some other method.
123 # Noninteractive access to all databases is required during automatic
124 # maintenance (custom daily cronjobs, replication, and similar tasks).
125 #
126 # Database administrative login by Unix domain socket
127 ";
128
129 open my $hba, '<', $fname or error "could not open $fname for reading";
130 my $search = 1;
131 my @lines;
132 while (my $line = <$hba>) {
133 # add superuser entry before column description line
134 if ($search && $line =~ /#.*TYPE\s+DATABASE/) {
135 push @lines, $su_comment;
136 push @lines, sprintf "%-7s %-15s %-39s %s\n", 'local', 'all', $user, $local_method;
137 push @lines, "\n";
138 $search = 0;
139 }
140
141 if ($version < '9.2' and not $explicit_auth_config) {
142 # default authentication for Unix socket connections
143 if ($line =~ /^#?local/) {
144 $line =~ s/trust/$local_method/;
145 }
146
147 # default authentication for TCP connections
148 if ($line =~ /^#?host/) {
149 $line =~ s/trust/$host_method/;
150 }
151 }
152
153 push @lines, $line;
154 }
155 close $hba;
156
157 error "setup_pg_hba: did not find insert position" if $search;
158
159 open my $new_hba, '>', $fname or error "could not open $fname for writing";
160 foreach (@lines) {
161 print $new_hba $_;
162 }
163 close $new_hba;
164 }
165
166 #
167 # Execution starts here
168 #
169
170 # this flag gets set when we started creating the cluster, and thus we need to
171 # clean up on errors
172 my $cleanup_cruft = 0;
173
174 # command line arguments
175
176 my $startconf = '';
177 my @pgoptions;
178 my $createclusterconf;
179 my $environmentfile = "$PgCommon::common_confdir/environment";
180 my ($owneruid, $ownergid, $socketdir, $datadir, $custom_logfile, $start, $port);
181 my ($encoding, $locale, $lc_collate, $lc_ctype, $lc_messages, $lc_monetary, $lc_numeric, $lc_time);
182 my ($no_status);
183
184 exit 1 unless GetOptions ('u|user=s' => \$owneruid, 'g|group=s' => \$ownergid,
185 's|socketdir=s' => \$socketdir, 'd|datadir=s' => \$datadir,
186 'start' => \$start, 'e|encoding=s' => \$encoding,
187 'l|logfile=s' => \$custom_logfile, 'start-conf=s' => \$startconf,
188 'o|pgoption=s' => sub { $_[1] =~ /(.*?)=(.*)/ or error ("No '=' in pgoption '$_[1]'");
189 push @pgoptions, [$1, $2];
190 },
191 'createclusterconf=s' => \$createclusterconf,
192 'environment=s' => \$environmentfile,
193 'no-status' => \$no_status,
194 'p|port=i' => \$port,
195 'q|quiet' => \$quiet,
196 'locale=s' => \$locale,
197 'lc-collate=s' => \$lc_collate, 'lc-ctype=s' => \$lc_ctype,
198 'lc-messages=s' => \$lc_messages, 'lc-monetary=s' => \$lc_monetary,
199 'lc-numeric=s' => \$lc_numeric, 'lc-time=s' => \$lc_time);
200
201 # read defaults from /etc/postgresql-common/createcluster.conf
202 %defaultconf = PgCommon::read_conf_file ($createclusterconf // "$PgCommon::common_confdir/createcluster.conf", not $createclusterconf);
203 # process --pgoption parameters
204 foreach my $guc (@pgoptions) {
205 if ($guc->[1] eq '') {
206 delete $defaultconf{$guc->[0]};
207 } else {
208 $defaultconf{$guc->[0]} = $guc->[1];
209 }
210 }
211
212 $explicit_auth_config = 1 if ($defaultconf{initdb_options} and $defaultconf{initdb_options} =~ /(^| )(-\w*A|--auth\b)/);
213
214 # check validity of locale
215 unless (setlocale (LC_ALL, "")) {
216 my $env = join "\n",
217 map { " $_: $ENV{$_}" }
218 grep { /^(LC_|LANG)/ } sort keys %ENV;
219 error ("The locale requested by the environment is invalid:\n$env")
220 }
221 setlocale (LC_NUMERIC, "C"); # otherwise version comparisons break
222
223 if (@ARGV < 2) {
224 print "Usage: $0 [options] <version> <cluster name> [-- <initdb options>]
225
226 Options:
227 -u <uid> cluster owner and superuser (default: 'postgres')
228 -g <gid> group for data files (default: primary group of owner)
229 -d <dir> data directory (default:
230 /var/lib/postgresql/<version>/<cluster name>)
231 -s <dir> socket directory (default: /var/run/postgresql for clusters
232 owned by 'postgres', /tmp for other clusters)
233 -l <dir> path to desired log file (default:
234 /var/log/postgresql/postgresql-<version>-<cluster>.log)
235 --locale <encoding>
236 set cluster locale (default: inherit from environment)
237 --lc-collate/ctype/messages/monetary/numeric/time <locale>
238 like --locale, but only set for a particular category
239 -e <encoding> Default encoding (default: derived from locale)
240 -p <port> port number (default: next free port starting from 5432)
241 --start start the cluster after creating it
242 --start-conf auto|manual|disabled
243 Set automatic startup behaviour in start.conf (default: 'auto')
244 --createclusterconf=file alternative createcluster.conf to use
245 --environment=file alternative environment file to use
246 <initdb options> other options to pass to initdb
247 ";
248 exit 1;
249 }
250
251 $startconf ||= $defaultconf{'start_conf'} || 'auto';
252 error "Invalid --start-conf value: $startconf" if $startconf ne 'auto' &&
253 $startconf ne 'manual' && $startconf ne 'disabled';
254
255 if ($owneruid) {
256 $owneruid = (getpwnam $owneruid)[2] unless $owneruid =~ /^\d+$/;
257 } elsif ($> == 0) {
258 $owneruid = getpwnam 'postgres';
259 error 'User postgres does not exist' unless $owneruid;
260 } else
261 {
262 $owneruid = $>;
263 }
264
265 if ($ownergid) {
266 $ownergid = (getgrnam $ownergid)[2] unless $ownergid =~ /^\d+$/;
267 } else {
268 $ownergid = (getpwuid $owneruid)[3];
269 }
270
271 error 'clusters must not be owned by root' unless $owneruid;
272
273 my ($version) = $ARGV[0] =~ /^(\d+\.?\d+)$/;
274 error "invalid version '$ARGV[0]'" unless defined $version;
275 my ($cluster) = $ARGV[1] =~ /^([-.\w]+)$/;
276 error "invalid cluster name '$ARGV[1]'" unless defined $cluster;
277 if ($cluster =~ /-/ and -t 1) {
278 print "Warning: cluster names containing dashes (-) will cause problems when running from systemd. Continuing anyway\n";
279 }
280 splice @ARGV, 0, 2;
281
282 my @initdb_opts_from_cli;
283 # options passed through to initdb
284 push @initdb_opts_from_cli, ('--encoding', $encoding) if $encoding;
285 push @initdb_opts_from_cli, ('--locale', $locale) if $locale;
286 push @initdb_opts_from_cli, ('--lc-collate', $lc_collate) if $lc_collate;
287 push @initdb_opts_from_cli, ('--lc-ctype', $lc_ctype) if $lc_ctype;
288 push @initdb_opts_from_cli, ('--lc-messages', $lc_messages) if $lc_messages;
289 push @initdb_opts_from_cli, ('--lc-monetary', $lc_monetary) if $lc_monetary;
290 push @initdb_opts_from_cli, ('--lc-numeric', $lc_numeric) if $lc_numeric;
291 push @initdb_opts_from_cli, ('--lc-time', $lc_time) if $lc_time;
292
293 # initdb options passed after --
294 foreach my $argv (@ARGV) {
295 # the user passed an authentication method, don't mess with initdb and pg_hba.conf
296 if ($argv =~ /^(-\w*A|--auth\b)/) { # -A --auth --auth-host --auth-local
297 $explicit_auth_config = 1;
298 }
299 push @initdb_opts_from_cli, $argv =~ /(.*)/; # untaint
300 }
301
302 # pg_hba.conf authentication settings
303 my $local_method = $version >= 9.1 ? 'peer' :
304 ($version >= 8.4 ? 'ident' :
305 'ident sameuser');
306 my $host_method = $version >= 14 ? 'scram-sha-256' : 'md5';
307
308 # create parent of data directory if missing
309 my $datadirp_created;
310 if (!defined $datadir) {
311 $datadir = replace_v_c ($defaultconf{'data_directory'} || "/var/lib/postgresql/%v/%c", $version, $cluster);
312 $datadir =~ s!/+$!!;
313 my $pd = $datadir;
314 $pd =~ s!/[^/]*$!!;
315
316 # ensure that the version data dir is owned by postgres as well, so that
317 # it can be administrated without root permissions
318 if (!stat $pd) {
319 my @install = qw(install -d);
320 push @install, '-o', $postgres_user[2], '-g', $postgres_user[3] if ($> == 0);
321 system @install, $pd;
322 $datadirp_created = $pd; # clean up in case of error
323 }
324 }
325 my $confdirp = "$PgCommon::confroot/$version";
326 my $confdir = "$confdirp/$cluster";
327
328 # some sanity checks
329 error "no initdb program for version $version found" unless get_program_path 'initdb', $version;
330 error 'cluster configuration already exists'
331 if -e "$confdir/postgresql.conf" || -e "$confdir/pg_hba.conf";
332
333 if (defined $port) {
334 error 'port must be a positive integer between 1024 and 65535'
335 unless $port =~ /^\d+/ && $port >= 1024 && $port <= 65535;
336 } else {
337 $port = next_free_port;
338 }
339
340 # create configuration directory
341 if (!stat $confdirp) {
342 my @install = qw(install -d);
343 push @install, '-o', $postgres_user[2], '-g', $postgres_user[3] if ($> == 0);
344 system @install, $confdirp;
345 }
346 # now we created the first new directory for this cluster and start to rollback
347 # on error
348 $cleanup_cruft = 1;
349
350 error 'could not create configuration directory; you might ' .
351 'need to run this program with root privileges' if system ('install', '-d', $confdir);
352
353 # check whether we have an already existing cluster; check version and
354 # determine owner in this case
355 my $newcluster = 0;
356
357 if (-f "$datadir/PG_VERSION") {
358 open my $fh, '<', "$datadir/PG_VERSION" or error "could not open $datadir/PG_VERSION";
359 chomp(my $existingver = <$fh>);
360 close $fh;
361
362 ($owneruid, $ownergid) = (stat "$datadir/PG_VERSION")[4,5];
363 if ($existingver == $version) {
364 print "Configuring already existing cluster (configuration: $confdir, data: $datadir, owner: $owneruid:$ownergid)\n";
365 # Do not remove already existing data directory on errors
366 $cleanup_cruft = 0;
367 } else {
368 error "$datadir contains a version $existingver cluster, but $version was requested";
369 }
370 } else {
371 print "Creating new PostgreSQL cluster $version/$cluster ...\n";
372 init_db $version, $cluster, $datadir, $owneruid, $ownergid,
373 $local_method, $host_method, \@initdb_opts_from_cli;
374 $newcluster = 1;
375 }
376
377 # create default "start" file
378 set_cluster_start_conf $version, $cluster, $startconf;
379
380 # create default pg_ctl.conf file
381 set_cluster_pg_ctl_conf $version, $cluster, '';
382
383 # move conffiles, setup permissions
384 move_conffile "$datadir/postgresql.conf", $confdir, $version, $cluster, $owneruid, $ownergid, '644';
385 move_conffile "$datadir/pg_hba.conf", $confdir, $version, $cluster, $owneruid, $ownergid, '640', 'hba_file';
386 move_conffile "$datadir/pg_ident.conf", $confdir, $version, $cluster, $owneruid, $ownergid, '640', 'ident_file';
387 foreach my $f ($datadir, $confdir, "$confdir/start.conf", "$confdir/pg_ctl.conf") {
388 lchown $owneruid, $ownergid, $f or error "lchown $f: $!";
389 }
390
391 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf', 'data_directory', $datadir;
392
393 # add access for database superuser
394 setup_pg_hba $version, $owneruid, $confdir, $local_method, $host_method
395 if $newcluster and not $explicit_auth_config;
396
397 # configure socket directory
398 if (! $socketdir && ! -e '/var/run/postgresql') {
399 system 'install', '-d', '-o', $postgres_user[2], '-g', $postgres_user[3], '/var/run/postgresql';
400 }
401 if ($socketdir && ! -e $socketdir) {
402 if (system 'install', '-d', '-m', '0755', '-o', $owneruid, '-g', $ownergid, $socketdir) {
403 error "could not create socket directory $socketdir";
404 }
405 }
406 my $orig_euid = $>;
407 my $orig_egid = $);
408 $) = $ownergid;
409 $> = $owneruid;
410 unless ($socketdir) {
411 if ($version < 9.4 and $PgCommon::rpm) {
412 $socketdir = '/tmp'; # PGDG 9.3 and earlier defaults to /tmp in libpq et al.
413 } elsif (-w '/var/run/postgresql') {
414 $socketdir = '/var/run/postgresql';
415 } else {
416 $socketdir='/tmp';
417 }
418 }
419 set_cluster_socketdir $version, $cluster, $socketdir;
420 $> = $orig_euid;
421 $) = $orig_egid;
422
423 set_cluster_port $version, $cluster, $port;
424
425 # create log file
426 if (! -d '/var/log/postgresql') {
427 mkdir '/var/log/postgresql' or
428 error "could not create log directory; you might need to run this program with root privileges";
429 chmod 01775, '/var/log/postgresql';
430 lchown 0, $postgres_user[3], '/var/log/postgresql';
431 }
432 my $real_logfile = $custom_logfile || "/var/log/postgresql/postgresql-$version-$cluster.log";
433 error "logfile $real_logfile is a directory, not a file" if (-d $real_logfile);
434 if (! -e $real_logfile) {
435 open my $fh, '>>', $real_logfile or error "could not create log file $real_logfile";
436 }
437 chmod 0640, $real_logfile;
438 my $g;
439 if ($owneruid < 500) {
440 $g = (getgrnam 'adm')[2];
441 } else {
442 $g = $ownergid;
443 }
444 lchown $owneruid, $g, $real_logfile;
445 # if we are using a non-default log file, create a log symlink
446 if ($custom_logfile) {
447 symlink $real_logfile, "$confdir/log";
448 lchown $owneruid, $ownergid, "$confdir/log";
449 }
450
451 # SSL configuration
452 my $want_ssl = PgCommon::config_bool($defaultconf{ssl} || 'on');
453 # older versions (<= 9.1 as of 2019-03) do not support ssl anymore
454 $want_ssl = 0 if ($version <= 9.1);
455
456 # Check whether we can access the SSL private key as the cluster owner
457 my $ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key';
458 my $ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem';
459 my $ssl_ca_file = "$PgCommon::common_confdir/root.crt";
460 my $ssl_key_access;
461 my ($uid, $euid, $gid, $egid) = ($<, $>, $(, $));
462 change_ugid $owneruid, $ownergid;
463 $ssl_key_access = -r $ssl_key_file;
464
465 # check for stats_temp_directory access
466 delete $defaultconf{stats_temp_directory} if ($version < 8.4 or $version >= 15);
467 if ($defaultconf{stats_temp_directory}) {
468 my $stats_temp_directory = replace_v_c ($defaultconf{stats_temp_directory}, $version, $cluster);
469 $stats_temp_directory =~ s!/$!!; # strip trailing slash
470 my $stats_temp_parent = $stats_temp_directory;
471 $stats_temp_parent =~ s!/[^/]+$!!;
472 if (-d $stats_temp_directory) {
473 if (! -w $stats_temp_directory) {
474 print "Warning: The selected stats_temp_directory $stats_temp_directory
475 is not writable for the cluster owner. Not adding this setting in
476 postgresql.conf.\n";
477 delete $defaultconf{stats_temp_directory};
478 }
479 } elsif (! -d $stats_temp_parent) {
480 print "Warning: The parent $stats_temp_parent of the selected
481 stats_temp_directory does not exist. Not adding this setting in
482 postgresql.conf.\n";
483 delete $defaultconf{stats_temp_directory};
484 } elsif (! -w $stats_temp_parent) {
485 print "Warning: The parent $stats_temp_parent of the selected
486 stats_temp_directory is not writable for the cluster owner. Not adding this
487 setting in postgresql.conf.\n";
488 delete $defaultconf{stats_temp_directory};
489 }
490 # create the stats directory now. pg_ctlcluster would create it anyway, but
491 # when using pg_upgradecluster -m upgrade, it is not run before the cluster
492 # is started for the first time
493 if ($defaultconf{stats_temp_directory}) {
494 system 'install', '-d', '-m', '750', '-o', $owneruid, '-g', $ownergid, $stats_temp_directory;
495 }
496 }
497
498 $> = $euid;
499 $< = $uid;
500 $( = $gid;
501 $) = $egid;
502 die "changing euid back: $!" if $> != $euid;
503 die "changing egid back: $!" if $) != $egid;
504
505 # enable SSL if we have the snakeoil default certificate
506 if ($want_ssl && $newcluster && -e $ssl_cert_file && $ssl_key_access) {
507 if ($version >= '9.2') {
508 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf',
509 'ssl_cert_file', $ssl_cert_file;
510 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf',
511 'ssl_key_file', $ssl_key_file;
512 } else {
513 symlink $ssl_cert_file, "$datadir/server.crt";
514 symlink $ssl_key_file, "$datadir/server.key";
515 }
516
517 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf', 'ssl', 'on';
518 }
519
520 # SSL client certificate CA
521 if ($want_ssl && $newcluster && -e $ssl_ca_file) {
522 # check if we have a cert in there or just the boilerplate installed by our postinst
523 open my $fh, '<', $ssl_ca_file or error "could not open $ssl_ca_file for reading";
524 my $val;
525 read $fh, $val, 4096;
526 if ($val =~ /^-----BEGIN CERTIFICATE-----/m) {
527 if ($version >= '9.2') {
528 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf',
529 'ssl_ca_file', $ssl_ca_file;
530 } else {
531 symlink $ssl_ca_file, $datadir.'/root.crt';
532 }
533 }
534 }
535
536 # SSL client certificate revocation list
537 if ($want_ssl && $newcluster && -e "$PgCommon::common_confdir/root.crl") {
538 if ($version >= '9.2') {
539 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf',
540 'ssl_crl_file', "$PgCommon::common_confdir/root.crl";
541 } else {
542 symlink "$PgCommon::common_confdir/root.crl", $datadir.'/root.crl';
543 }
544 }
545
546 # create default (empty) environment file
547 my $defaultenv = "# environment variables for postgres processes
548 # This file has the same syntax as postgresql.conf:
549 # VARIABLE = simple_value
550 # VARIABLE2 = 'any value!'
551 # I. e. you need to enclose any value which does not only consist of letters,
552 # numbers, and '-', '_', '.' in single quotes. Shell commands are not
553 # evaluated.
554 ";
555 if (-e $environmentfile) {
556 open my $env, '<', $environmentfile or error "could not read environment file $environmentfile";
557 local $/; # slurp mode
558 $defaultenv = <$env>;
559 }
560 $defaultenv = replace_v_c ($defaultenv, $version, $cluster);
561 open my $env, '>', "$confdir/environment" or error "could not create environment file $confdir/environment";
562 print $env $defaultenv;
563 close $env;
564 chmod 0644, "$confdir/environment";
565 lchown $owneruid, $ownergid, "$confdir/environment";
566
567 $cleanup_cruft = 0;
568
569 # configure to create external PID file
570 if ($socketdir eq '/var/run/postgresql') {
571 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf', 'external_pid_file', "/var/run/postgresql/$version-$cluster.pid";
572 }
573
574 # handle other createcluster.conf parameters, including --pgoption parameters
575 foreach my $guc (sort keys %defaultconf) {
576 next if $guc =~ /^(create_main_cluster|start_conf|data_directory|waldir|xlogdir|initdb_options|ssl)$/;
577 next if $guc eq 'logging_collector' and $version < 8.3;
578 next if $guc eq 'cluster_name' and $version < 9.5;
579 my $val = replace_v_c ($defaultconf{$guc}, $version, $cluster);
580 $guc =~ s/^add_include/include/; # remove harness from include directives in createcluster.conf
581 if ($guc eq 'include_dir') {
582 next if ($version < 9.3);
583 if ($val =~ /^[\w.]+$/ and not -e "$confdir/$val") { # create directory relative to new config directory
584 mkdir "$confdir/$val", 0755;
585 lchown $owneruid, $ownergid, "$confdir/$val";
586 }
587 }
588 PgCommon::set_conf_value $version, $cluster, 'postgresql.conf', $guc, $val;
589 }
590
591 # notify systemd about the new cluster
592 if (not exists $ENV{'PG_CLUSTER_CONF_ROOT'} and $startconf eq 'auto' and -d '/run/systemd/system') {
593 if ($> == 0) {
594 system 'systemctl daemon-reload';
595 } elsif (-t 1) {
596 print "Warning: systemd does not know about the new cluster yet. Operations like \"service postgresql start\" will not handle it. To fix, run:\n";
597 print " sudo systemctl daemon-reload\n";
598 }
599 }
600
601 # notify apt about the new cluster
602 if (not exists $ENV{'PG_CLUSTER_CONF_ROOT'} and $> == 0) {
603 system "/usr/share/postgresql-common/pg_updateaptconfig";
604 }
605
606 # start it if requested
607 if ($start) {
608 system 'pg_ctlcluster', $version, $cluster, 'start';
609 die "Could not start cluster\n" if ($?);
610 }
611
612 # finally, show the cluster we created
613 system 'pg_lsclusters', $version, $cluster unless ($quiet or $no_status);
614
615 END {
616 # clean up cruft if something went wrong
617 if ($cleanup_cruft && defined $version && defined $cluster) {
618 system "pg_dropcluster $version $cluster 2>/dev/null";
619 rmdir $datadirp_created if ($datadirp_created); # clean up after early errors which pg_dropcluster doesn't handle
620 exit 1;
621 }
622 }
623
624 __END__
625
626 =head1 NAME
627
628 pg_createcluster - create a new PostgreSQL cluster
629
630 =head1 SYNOPSIS
631
632 B<pg_createcluster> [I<options>] I<version> I<name> [B<--> I<initdb options>]
633
634 =head1 DESCRIPTION
635
636 B<pg_createcluster> creates a new PostgreSQL server cluster (i. e. a
637 collection of databases served by a L<postgres(1)> instance) and
638 integrates it into the multi-version/multi-cluster architecture of the
639 B<postgresql-common> package.
640
641 Every cluster is uniquely identified by its version and name. The name can be
642 arbitrary. The default cluster that is created on installation of a server
643 package is C<main>. However, you might wish to create other clusters for
644 testing, with other superusers, a cluster for each user on a shared server,
645 etc. C<pg_createcluster> will abort with an error if you try to create a
646 cluster with a name that already exists for that version.
647
648 For compatibility with B<systemd> service units, the cluster name should not
649 contain any dashes (B<->). B<pg_ctlcluster> will warn about the problem, but
650 succeed with the operation.
651
652 Given a major PostgreSQL I<version> (like "8.2" or "8.3") and a cluster
653 I<name>, it creates the necessary configuration files in
654 C</etc/postgresql/>I<version>C</>I<name>C</>; in particular these are
655 C<postgresql.conf>, C<pg_ident.conf>, C<pg_hba.conf>, a postgresql-common
656 specific configuration file C<start.conf> (see B<STARTUP CONTROL> below),
657 C<pg_ctl.conf>, and a symbolic link C<log> which points to the log file (by
658 default, C</var/log/postgresql/postgresql->I<version>C<->I<name>C<.log>).
659
660 C<postgresql.conf> is automatically adapted to use the next available port, i.
661 e. the first port (starting from 5432) which is not yet used by an already
662 existing cluster.
663
664 If the data directory does not yet exist, PostgreSQL's L<initdb(1)> command is
665 used to generate a new cluster structure. If the data directory already exists,
666 it is integrated into the B<postgresql-common> structure by moving the
667 configuration file and setting the data_directory option. Please note that this
668 I<only> works for data directories which were created directly with B<initdb>, i.
669 e. all the configuration files (C<postgresql.conf> etc.) must be present in the
670 data directory.
671
672 If a custom socket directory is given and it does not exist, it is created.
673
674 If the log file does not exist, it is created. In any case the permissions are
675 adjusted to allow write access to the cluster owner. Please note that
676 C<postgresql.conf> can be customized to specify C<log_directory> and/or
677 C<log_filename>; if at least one of these options is present, then the symbolic
678 link C<log> in the cluster configuration directory is ignored.
679
680 If the default snakeoil SSL certificate exists
681 (C</etc/ssl/certs/ssl-cert-snakeoil.pem> and
682 C</etc/ssl/private/ssl-cert-snakeoil.key>), and the C<postgres> user is in the
683 C<ssl-cert> Unix group, B<pg_createcluster> configures the cluster to use this
684 certificate, and enables SSL. Therefore all clusters will use the same SSL
685 certificate by default. For versions up to 9.1, symlinks in the data directory
686 will be created (C<server.crt> and C<server.key>); for 9.2 and later, the
687 appropriate C<postgresql.conf> options will be set (C<ssl_cert_file> and
688 C<ssl_key_file>). Of course you can replace this with a cluster specific
689 certificate. Similarly for C</etc/postgresql-common/root.crt> and
690 C</etc/postgresql-common/root.crl>, these files will be configured as client
691 certificate CA and revocation list, when present. (C<root.crt> is initially a
692 placeholder that will only be used if real certificates are added to the file.)
693
694 =head1 OPTIONS
695
696 =over 4
697
698 =item B<-u> I<user>, B<--user=>I<user>
699
700 Set the user who owns the cluster and becomes the database superuser to the
701 given name or uid. By default, this is the user B<postgres>. A cluster must
702 not be owned by root.
703
704 =item B<-g> I<group>, B<--group=>I<group>
705
706 Change the group of the cluster related data files. By default this will be the
707 primary group of the database owner.
708
709 =item B<-d> I<dir>, B<--datadir=>I<dir>
710
711 Explicitly set the data directory path, which is used to store all the actual
712 databases and tables. This will become quite big (easily in the order of five
713 times the amount of actual data stored in the cluster). Defaults to
714 C</var/lib/postgresql/>I<version>C</>I<cluster>.
715
716 =item B<-s> I<dir>, B<--socketdir=>I<dir>
717
718 Explicitly set the directory where the L<postgres(1)> server stores the Unix
719 socket for local connections. Defaults to C</var/run/postgresql/> for clusters
720 owned by the user B<postgres>, and C</tmp> for clusters owned by other users.
721 Please be aware that C</tmp> is an unsafe directory since everybody can create
722 a socket there and impersonate the database server. If the given directory does
723 not exist, it is created with appropriate permissions.
724
725 =item B<-l> I<path>, B<--logfile=>I<path>
726
727 Explicitly set the path for the L<postgres(1)> server log file. Defaults to
728 C</var/log/postgresql/postgresql->I<version>C<->I<cluster>C<.log>.
729
730 =item B<--locale=>I<locale>
731
732 Set the default locale for the database cluster. If this option is not
733 specified, the locale is inherited from the environment that
734 B<pg_createcluster> runs in.
735
736 =item B<--lc-collate=>I<locale>
737
738 =item B<--lc-ctype=>I<locale>
739
740 =item B<--lc-messages=>I<locale>
741
742 =item B<--lc-monetary=>I<locale>
743
744 =item B<--lc-numeric=>I<locale>
745
746 =item B<--lc-time=>I<locale>
747
748 Like B<--locale>, but only sets the locale in the specified category.
749
750 =item B<-e> I<encoding>, B<--encoding=>I<encoding>
751
752 Select the encoding of the template database. This will also be the default
753 encoding of any database you create later, unless you override it there. The
754 default is derived from the locale, or SQL_ASCII if that does not work. The
755 character sets supported by the PostgreSQL server are described in the
756 documentation.
757
758 B<Note>: It is not recommended to set this option directly! Set the locale
759 instead.
760
761 =item B<-p> I<port>, B<--port=>I<port>
762
763 Select the port the new cluster listens on (for the Unix socket and the TCP
764 port); this must be a number between 1024 and 65535, since PostgreSQL does not
765 run as root and thus needs an unprivileged port number. By default the next
766 free port starting from 5432 is assigned.
767
768 =item B<-q> B<--quiet> B<--no-status>
769
770 Suppress output from B<initdb> and (or only) the cluster status message at the
771 end of the output.
772
773 =item B<--start>
774
775 Immediately start a server for the cluster after creating it (i. e. call
776 C<pg_ctlcluster> I<version cluster> C<start> on it). By default, the cluster is
777 not started.
778
779 =item B<--start-conf=>B<auto>|B<manual>|B<disabled>
780
781 Set the initial value in the C<start.conf> configuration file. See B<STARTUP
782 CONTROL> below. By default, B<auto> is used, which means that the cluster is
783 handled by C</etc/init.d/postgresql>, i. e. starts and stops
784 automatically on system boot.
785
786 =item B<-o> I<guc>B<=>I<value>, B<--pgoption> I<guc>B<=>I<value>
787
788 Configuration option to set in the new C<postgresql.conf> file.
789
790 =item B<--createclusterconf=>I<file>
791
792 Alternative B<createcluster.conf> file to use. Default is
793 C</etc/postgresql-common/createcluster.conf> (or
794 C<$PGSYSCONFDIR/createcluster.conf>).
795
796 =item B<--environment=>I<file>
797
798 Alternative default B<environment> file to use. Default is
799 C</etc/postgresql-common/environment> (or C<$PGSYSCONFDIR/environment>).
800 If the file is missing, a placeholder string is used.
801 %v and %c are replaced; see DEFAULT VALUES below.
802
803 =item B<--> I<initdb options>
804
805 Options passed directly to L<initdb(1)>.
806
807 Per default, B<pg_createcluster> will update the C<pg_hba.conf> file generated
808 by initdb to use peer authentication on local (unix) connections, and md5 on
809 TCP (host) connections. If explicit authentication config is included here
810 (B<-A>, B<--auth>, B<--auth-host>, B<--auth-local>), the C<pg_hba.conf> file
811 will be left untouched.
812
813 I<Note:> If only one of B<--auth-host> and B<--auth-local> is provided, the
814 other setting will default to B<trust> as per B<initdb>'s defaults, opening a
815 potential security risk.
816
817 =back
818
819 =head1 STARTUP CONTROL
820
821 The C<start.conf> file in the cluster configuration directory controls the
822 start/stop behavior of that cluster's postgres process. The file can contain
823 comment lines (started with '#'), empty lines, and must have exactly one
824 line with one of the following keywords:
825
826 =over 4
827
828 =item B<auto>
829
830 The postgres process is started/stopped automatically in the init script.
831
832 When running from B<systemd>, the cluster is started/stopped when
833 B<postgresql.service> is started/stopped.
834 This is also the default if the file is missing.
835
836 =item B<manual>
837
838 The postgres process is not handled by the init script, but manually
839 controlling the cluster with L<pg_ctlcluster(1)> is permitted.
840
841 When running from B<systemd>, the cluster is not started automatically when
842 B<postgresql.service> is started. However, stopping/restarting
843 B<postgresql.service> will stop/restart the cluster. The cluster can be started
844 using B<systemctl start postgresql@>I<version>B<->I<cluster>.
845
846 =item B<disabled>
847
848 Neither the init script, L<pg_ctlcluster(1)>, nor B<[email protected]> are permitted to start/stop the
849 cluster. Please be aware that this will not stop the cluster owner from calling
850 lower level tools to control the postgres process; this option is only meant
851 to prevent accidents during maintenance, not more.
852
853 =back
854
855 When running from B<systemd>, invoke B<systemctl daemon-reload> after editing
856 C<start.conf>.
857
858 The C<pg_ctl.conf> file in the cluster configuration directory can contain
859 additional options passed to B<pg_ctl> of that cluster.
860
861 =head1 DEFAULT VALUES
862
863 Some default values used by B<pg_createcluster> can be modified in
864 C</etc/postgresql-common/createcluster.conf>. Occurrences of B<%v> are replaced
865 by the major version number, and B<%c> by the cluster name. Use B<%%> for a
866 literal B<%>.
867
868 =over 4
869
870 =item B<create_main_cluster> (Default: B<true>)
871
872 Create a B<main> cluster when a new postgresql-NN server package is installed
873 and no clusters exist yet.
874
875 =item B<start_conf> (Default: B<auto>)
876
877 Default C<start.conf> value to use.
878
879 =back
880
881 =over 4
882
883 =item B<data_directory> (Default: B</var/lib/postgresql/%v/%c>)
884
885 Default data directory.
886
887 =item B<waldir|xlogdir> (Default: unset)
888
889 Default directory for transaction logs. When used, B<initdb> will create a
890 symlink from C<pg_wal> (PostgreSQL 9.6 and earlier: C<pg_xlog>) in the data
891 directory to this location. Unset by default, i.e. transaction logs remain in
892 the data directory. Both spellings of this option are accepted, and translated
893 to the correct initdb invocation depending on the cluster version.
894
895 =item B<initdb_options> (Default: unset)
896
897 Other options to pass to B<initdb>.
898
899 =item Other options
900
901 All other options listed are copied into the new cluster's postgresql.conf, e.g.:
902
903 listen_addresses = '*'
904 log_line_prefix = '%%t '
905
906 Some postgresql.conf options are treated specially:
907
908 =over 4
909
910 =item B<ssl>
911
912 Only added to postgresql.conf if the default snakeoil certificates exist and
913 are readable for the cluster owner as detailed above.
914
915 =item B<stats_temp_directory>
916
917 Only added to postgresql.conf if existing, and writable for the cluster owner,
918 or else if the parent directory is writable. Not used on PostgreSQL 15 or later.
919
920 =back
921
922 =item Include files
923
924 =over 4
925
926 =item B<include>
927
928 =item B<include_if_exists>
929
930 =item B<include_dir>
931
932 B<createcluster.conf> supports the same include directives as
933 B<postgresql.conf>.
934
935 =item B<add_include>
936
937 =item B<add_include_if_exists>
938
939 =item B<add_include_dir>
940
941 To add include directives to the new postgresql.conf file, use the B<add_*>
942 directives. The B<add_> prefix is removed.
943
944 =back
945
946 =back
947
948 =head1 SEE ALSO
949
950 L<initdb(1)>, L<pg_ctlcluster(8)>, L<pg_lsclusters(1)>, L<pg_wrapper(1)>
951
952 =head1 AUTHORS
953
954 Martin Pitt L<E<lt>[email protected]<gt>>, Christoph Berg L<E<lt>[email protected]<gt>>