Debian Codegraph @

pg_upgradecluster

raw
1 #!/usr/bin/perl -wT
2
3 # Upgrade a PostgreSQL cluster to a newer major version.
4 #
5 # (C) 2005-2009 Martin Pitt <[email protected]>
6 # (C) 2013 Peter Eisentraut <[email protected]>
7 # (C) 2013-2026 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 File::Temp qw(tempfile);
23 use Getopt::Long;
24 use POSIX qw(lchown);
25
26 # untaint environment
27 $ENV{'PATH'} = '/bin:/usr/bin';
28 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
29
30 # global variables
31 my ($version, $newversion, $cluster, $newcluster);
32 my (%info, %newinfo);
33 my ($encoding, $old_lc_ctype, $old_lc_collate); # old cluster encoding
34 my ($old_locale_provider, $old_icu_locale, $old_icu_rules);
35 my $maintenance_db = 'template1';
36 my $keep_on_error = 0;
37
38 # do not trip over cwd not being accessible to postgres superuser
39 chdir '/';
40
41 sub pre_upgrade_check($$$) {
42 my ($oldversion, $newversion, $force_packages) = @_;
43
44 return 1 if ($version == $newversion);
45
46 my @new_packages = package_list("postgresql*-$newversion*");
47
48 my $missing = 0;
49 for my $oldpkg (package_list("postgresql*-$oldversion*")) {
50 next if ($oldpkg =~ /-(dbgsym|doc)/);
51 my $newpkg = $oldpkg;
52 $newpkg =~ s/-$oldversion/-$newversion/;
53
54 next if ($newpkg =~ /^postgresql-contrib-/ and $newversion >= 10); # postgresql-contrib-NN merged into postgresql-NN in 10+
55
56 if (not grep {$_ eq $newpkg} @new_packages) {
57 print "$oldpkg is installed, but $newpkg is missing\n";
58 $missing++;
59 }
60 }
61
62 if ($missing) {
63 print "$missing package(s) from version $oldversion missing for version $newversion\n";
64 if ($force_packages) {
65 print "Ignoring as --force-package was used\n";
66 } else {
67 print "Install the missing packages and try pg_upgradecluster again. To ignore the issue, use --force-packages\n";
68 return 0;
69 }
70 }
71
72 return 1;
73 }
74
75 # update the new cluster's conffiles
76 sub adapt_conffiles {
77 my ($newversion, $newcluster, $configfile) = @_;
78 my %c = read_cluster_conf_file $newversion, $newcluster, $configfile, 0;
79
80 # Arguments: <ref to conf hash> <name> <comment>
81 my $deprecate = sub {
82 my ($conf, $guc, $comment) = @_;
83 if (defined $conf->{$guc}) {
84 PgCommon::disable_conf_value $newversion, $newcluster,
85 $configfile, $guc, $comment;
86 }
87 };
88
89 # Arguments: <ref to conf hash> <old name> <new name>
90 my $rename = sub {
91 my ($conf, $old, $new) = @_;
92 if (defined ${$conf}{$old}) {
93 PgCommon::replace_conf_value $newversion, $newcluster,
94 $configfile, $old, "deprecated in favor of $new",
95 $new, ${$conf}{$old};
96 }
97 };
98
99 # Arguments: <config option> <value>
100 my $set = sub {
101 my ($guc, $val) = @_;
102 PgCommon::set_conf_value $newversion, $newcluster, $configfile,
103 $guc, $val;
104 };
105
106 # adapt paths to configuration files
107 if ($configfile eq 'postgresql.conf') {
108 $set->('data_directory', $newinfo{'pgdata'});
109 } else {
110 # fix bug in pg_upgradecluster 200..202
111 $deprecate->(\%c, 'data_directory', 'not valid in postgresql.auto.conf');
112 }
113 for my $guc (qw(hba_file ident_file external_pid_file stats_temp_directory)) {
114 next unless (defined $c{$guc});
115 my $val = $c{$guc};
116 $val =~ s/\b\Q$version\E\b/$newversion/g;
117 $val =~ s/\b\Q$cluster\E\b/$newcluster/g if ($cluster ne $newcluster);
118 $set->($guc, $val);
119 }
120
121 if ($newversion >= '8.2') {
122 # preload_libraries -> shared_preload_libraries transition
123 $rename->(\%c, 'preload_libraries', 'shared_preload_libraries');
124
125 # australian_timezones -> timezone_abbreviations transition
126 my $australian_timezones = config_bool $c{'australian_timezones'};
127 if (defined $australian_timezones) {
128 PgCommon::replace_conf_value $newversion, $newcluster, $configfile,
129 'australian_timezones', 'deprecated in favor of timezone_abbreviations',
130 'timezone_abbreviations', ($australian_timezones ? 'Australia' : 'Default');
131 }
132 }
133
134 if ($newversion >= '8.3') {
135 $deprecate->(\%c, 'bgwriter_lru_percent', 'deprecated');
136 $deprecate->(\%c, 'bgwriter_all_percent', 'deprecated');
137 $deprecate->(\%c, 'bgwriter_all_maxpages', 'deprecated');
138
139 $rename->(\%c, 'redirect_stderr', 'logging_collector');
140
141 $rename->(\%c, 'stats_command_string', 'track_activities');
142 $deprecate->(\%c, 'stats_start_collector', 'deprecated, always on now');
143 $deprecate->(\%c, 'stats_reset_on_server_start', 'deprecated');
144
145 # stats_block_level and stats_row_level are merged into track_counts
146 if ($c{'stats_block_level'} || $c{'stats_row_level'}) {
147 $deprecate->(\%c, 'stats_block_level', 'deprecated in favor of track_counts');
148 $deprecate->(\%c, 'stats_row_level', 'deprecated in favor of track_counts');
149 $set->('track_counts', (config_bool $c{'stats_block_level'} || config_bool $c{'stats_row_level'}) ? 'on' : 'off');
150 }
151
152 # archive_command now has to be enabled explicitly
153 if ($c{'archive_command'}) {
154 $set->('archive_mode', 'on');
155 }
156 }
157
158 if ($newversion >= '8.4') {
159 $deprecate->(\%c, 'max_fsm_pages', 'not needed anymore');
160 $deprecate->(\%c, 'max_fsm_relations', 'not needed anymore');
161 $deprecate->(\%c, 'krb_server_hostname', 'does not exist anymore');
162 $deprecate->(\%c, 'krb_realm', 'does not exist anymore');
163 $rename->(\%c, 'explain_pretty_print', 'debug_pretty_print');
164 }
165
166 if ($newversion >= '9.0') {
167 $deprecate->(\%c, 'add_missing_from', 'does not exist anymore');
168 $deprecate->(\%c, 'regex_flavor', 'does not exist anymore');
169 }
170
171 if ($newversion >= '9.2') {
172 $deprecate->(\%c, 'wal_sender_delay', 'does not exist anymore');
173 $deprecate->(\%c, 'silent_mode', 'does not exist anymore');
174 $deprecate->(\%c, 'custom_variable_classes', 'does not exist anymore');
175 }
176
177 if ($newversion >= '9.3') {
178 $rename->(\%c, 'unix_socket_directory', 'unix_socket_directories');
179 $rename->(\%c, 'replication_timeout', 'wal_sender_timeout');
180 }
181
182 if ($newversion >= '9.4') {
183 $deprecate->(\%c, 'krb_srvname', 'native krb5 authentication deprecated in favor of GSSAPI');
184 # grab dsmt from the new config just written by initdb
185 if (not $c{dynamic_shared_memory_type} and $configfile eq 'postgresql.conf') {
186 $set->('dynamic_shared_memory_type', ($newinfo{config}->{dynamic_shared_memory_type} || 'mmap'));
187 }
188 }
189
190 if ($newversion >= '9.5') {
191 if (exists $c{checkpoint_segments}) {
192 my $max_wal_size = 16*$c{checkpoint_segments} . 'MB';
193 $rename->(\%c, 'checkpoint_segments', 'max_wal_size');
194 $set->('max_wal_size', $max_wal_size);
195 }
196 $deprecate->(\%c, 'ssl_renegotiation_limit', 'does not exist anymore');
197 # adapt cluster_name
198 my $cluster_name = PgCommon::get_conf_value ($newversion, $newcluster, $configfile, 'cluster_name');
199 if ($cluster_name) {
200 $cluster_name =~ s/\Q$version\E/$newversion/g;
201 $cluster_name =~ s/\Q$cluster\E/$newcluster/g;
202 $set->('cluster_name', $cluster_name);
203 }
204 }
205
206 if ($newversion >= '10') {
207 $rename->(\%c, 'min_parallel_relation_size', 'min_parallel_table_scan_size');
208 $deprecate->(\%c, 'sql_inheritance', 'does not exist anymore');
209 }
210
211 if ($newversion >= '11') {
212 $deprecate->(\%c, 'replacement_sort_tuples', 'does not exist anymore');
213 }
214
215 if ($newversion >= '13') {
216 if (exists $c{wal_keep_segments}) {
217 my $wal_keep_size = 16*$c{wal_keep_segments} . 'MB';
218 $rename->(\%c, 'wal_keep_segments', 'wal_keep_size');
219 $set->('wal_keep_size', $wal_keep_size);
220 }
221 }
222
223 if ($newversion >= '14') {
224 $deprecate->(\%c, 'operator_precedence_warning', 'does not exist anymore');
225 if ($c{password_encryption} and $c{password_encryption} =~ /^(on|off|true|false)$/) {
226 $deprecate->(\%c, 'password_encryption', 'password_encryption is not a boolean anymore');
227 }
228 $deprecate->(\%c, 'vacuum_cleanup_index_scale_factor', 'does not exist anymore');
229 }
230
231 if ($newversion >= '15') {
232 $deprecate->(\%c, 'stats_temp_directory', 'does not exist anymore');
233 }
234
235 if ($newversion >= '16') {
236 $deprecate->(\%c, 'promote_trigger_file', 'does not exist anymore, use pg_promote() instead');
237 $deprecate->(\%c, 'vacuum_defer_cleanup_age', 'does not exist anymore');
238 $deprecate->(\%c, 'force_parallel_mode', 'does not exist anymore');
239 }
240
241 if ($newversion >= '17') {
242 $deprecate->(\%c, 'db_user_namespace', 'does not exist anymore');
243 $deprecate->(\%c, 'old_snapshot_threshold', 'does not exist anymore');
244 }
245
246 if ($newversion >= '18') {
247 $deprecate->(\%c, 'extension_destdir', 'replaced by extension_control_path');
248 }
249
250 if ($newversion >= '19') {
251 $deprecate->(\%c, 'escape_string_warning', 'standard_conforming_strings now always on');
252 $rename->(\%c, 'io_workers', 'io_max_workers');
253 }
254 }
255
256 sub migrate_config_files() {
257 # copy configuration files
258 print "Copying old configuration files...\n";
259 install_file $info{'configdir'}.'/postgresql.conf', $newinfo{'configdir'},
260 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "644";
261 adapt_conffiles $newversion, $newcluster, 'postgresql.conf';
262 # copy auto.conf after postgresql.conf has been updated
263 # (otherwise read_cluster_conf_file would also read auto.conf)
264 if ($version >= 9.4) {
265 install_file $info{'pgdata'}.'/postgresql.auto.conf', $newinfo{'pgdata'},
266 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "600";
267 adapt_conffiles $newversion, $newcluster, 'postgresql.auto.conf';
268 }
269 install_file $info{'configdir'}.'/pg_ident.conf', $newinfo{'configdir'},
270 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "640";
271 install_file $info{'configdir'}.'/pg_hba.conf', $newinfo{'configdir'},
272 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "640";
273 if ($version < 8.4 and $newversion >= 8.4) {
274 print "Removing 'ident sameuser' from pg_hba.conf...\n";
275 my $hba = "$PgCommon::confroot/$newversion/$newcluster/pg_hba.conf";
276 open O, $hba or error "open $hba: $!";
277 open N, ">$hba.new" or error "open $hba.new: $!";
278 while (<O>) {
279 s/ident\s+sameuser/ident/;
280 print N $_;
281 }
282 close O;
283 close N;
284 lchown $newinfo{'owneruid'}, $newinfo{'ownergid'}, "$hba.new";
285 chmod 0640, "$hba.new";
286 rename "$hba.new", $hba or error "rename: $!";
287 }
288 if ( -e $info{'configdir'}.'/start.conf') {
289 print "Copying old start.conf...\n";
290 install_file $info{'configdir'}.'/start.conf', $newinfo{'configdir'},
291 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "644";
292 }
293 if ( -e $info{'configdir'}.'/pg_ctl.conf') {
294 print "Copying old pg_ctl.conf...\n";
295 install_file $info{'configdir'}.'/pg_ctl.conf', $newinfo{'configdir'},
296 $newinfo{'owneruid'}, $newinfo{'ownergid'}, "644";
297 }
298
299 # copy SSL files (overwriting any file that pg_createcluster put there)
300 for my $file (qw/server.crt server.key root.crt root.crl/) {
301 if ( -e "$info{'pgdata'}/$file") {
302 print "Copying old $file...\n";
303 if (!fork) { # we don't use install_file because that converts symlinks to files
304 change_ugid $info{'owneruid'}, $info{'ownergid'};
305 system "cp -a $info{'pgdata'}/$file $newinfo{'pgdata'}";
306 exit 0;
307 }
308 wait;
309 }
310 }
311 if ($newversion >= 9.2) {
312 # SSL certificate paths have an explicit option now, older versions use
313 # a symlink
314 for my $f (['server.crt', 'ssl_cert_file'],
315 ['server.key', 'ssl_key_file'],
316 ['root.crt', 'ssl_ca_file'],
317 ['root.crl', 'ssl_crl_file']) {
318 my $file = "$newinfo{'pgdata'}/$f->[0]";
319 if (-l $file) { # migrate symlink to config entry with link target
320 PgCommon::set_conf_value $newversion, $newcluster, 'postgresql.conf',
321 $f->[1], (readlink $file);
322 unlink $file;
323 } elsif (-e $file) { # plain file in data dir, put in config
324 PgCommon::set_conf_value $newversion, $newcluster, 'postgresql.conf',
325 $f->[1], $file;
326 }
327 }
328 }
329 }
330
331 # Write temporary pg_hba.conf.
332 # Arguments: <version> <cluster> <owner> <owneruid>
333 sub temp_hba_conf {
334 my ($fh, $hba) = tempfile("pg_hba.XXXXXX", TMPDIR => 1, SUFFIX => ".conf");
335
336 if ($_[0] >= '8.4') {
337 print $fh "local all $_[2] ident\n";
338 } else {
339 print $fh "local all $_[2] ident sameuser\n";
340 }
341 close $fh;
342 chmod 0400, $hba;
343 lchown $_[3], 0, $hba;
344
345 return $hba;
346 }
347
348 # Get encoding and locales of a running cluster
349 # Arguments: <version> <cluster>
350 sub get_encoding {
351 my ($version, $cluster) = @_;
352 $encoding = get_db_encoding $version, $cluster, $maintenance_db;
353 if ($version <= '8.3') {
354 ($old_lc_ctype, $old_lc_collate) = get_cluster_locales $version, $cluster;
355 } else {
356 ($old_lc_ctype, $old_lc_collate, $old_locale_provider, $old_icu_locale, $old_icu_rules) = get_db_locales $version, $cluster, $maintenance_db;
357 }
358 unless ($encoding && $old_lc_ctype && $old_lc_collate) {
359 error 'could not get cluster locales';
360 }
361 }
362
363 # RedHat's run-parts doesn't support any options, supply a minimalistic implementation here
364 # BUG: we don't care about validating the filenames yet
365 # Arguments: <directory> <argv to pass to scripts>
366 sub run_parts {
367 my ($dir, @argv) = @_;
368 for my $script (<$dir/*>) {
369 my ($s) = $script =~ /(.*)/; # untaint
370 system ($s, @argv);
371 error "$s failed: $?" if ($?);
372 }
373 }
374
375 sub run_upgrade_scripts($) {
376 my $phase = shift;
377
378 print "Running $phase phase upgrade hook scripts ...\n";
379 if (!fork) {
380 change_ugid $info{'owneruid'}, $info{'ownergid'};
381
382 if ($PgCommon::rpm) {
383 run_parts ("$PgCommon::common_confdir/pg_upgradecluster.d",
384 $version, $newcluster, $newversion, $phase);
385 exit;
386 }
387
388 my @argv = ('run-parts', '--lsbsysinit', '-a', $version, '-a', $newcluster,
389 '-a', $newversion, '-a', $phase,
390 "$PgCommon::common_confdir/pg_upgradecluster.d");
391 error "$PgCommon::common_confdir/pg_upgradecluster.d script failed" if system @argv;
392 exit;
393 }
394 wait;
395 if ($? > 0) {
396 unless ($keep_on_error) {
397 print STDERR "Error during running upgrade hooks, removing new cluster\n";
398 system 'pg_dropcluster', '--stop', $newversion, $newcluster;
399 }
400 exit 1;
401 }
402 }
403
404 #
405 # Execution starts here
406 #
407
408 # command line arguments
409
410 my $newest_version = get_newest_version('postgres');
411 $newversion = $newest_version;
412
413 my $check_only = 0;
414 my $force_packages = 0;
415 my $method = 'dump';
416 my $link = 0;
417 my $clone = 0;
418 my $data_checksums; # default undef
419 my $keep_port = 0;
420 my $start = -1; # -1 = auto
421
422 my ($locale, $lc_collate, $lc_ctype, $lc_messages, $lc_monetary, $lc_numeric,
423 $lc_time, $logfile, $old_bindir, $jobs);
424 GetOptions ('v|version=s' => \$newversion,
425 'check' => \$check_only,
426 'force-packages' => \$force_packages,
427 'locale=s' => \$locale,
428 'lc-collate=s' => \$lc_collate,
429 'lc-ctype=s' => \$lc_ctype,
430 'lc-messages=s' => \$lc_messages,
431 'lc-monetary=s' => \$lc_monetary,
432 'lc-numeric=s' => \$lc_numeric,
433 'lc-time=s' => \$lc_time,
434 'logfile=s' => \$logfile,
435 'm|method=s' => \$method,
436 'j|jobs=s', => \$jobs,
437 'k|link' => \$link,
438 'clone' => \$clone,
439 'data-checksums!' => \$data_checksums,
440 'keep-port' => \$keep_port,
441 'rename=s' => \$newcluster,
442 'old-bindir=s' => \$old_bindir,
443 'maintenance-db=s' => \$maintenance_db,
444 'start!' => \$start,
445 'keep-on-error' => \$keep_on_error,
446 ) or exit 1;
447
448 if ($method eq 'dump') {
449 error 'cannot use --link with --method=dump' if ($link);
450 error 'cannot use --clone with --method=dump' if ($clone);
451 } elsif ($method eq 'link') {
452 $method = 'upgrade';
453 $link = 1;
454 } elsif ($method eq 'clone') {
455 $method = 'upgrade';
456 $clone = 1;
457 } elsif ($method ne 'upgrade') {
458 error 'method must be "dump", "upgrade", "link", or "clone"';
459 }
460 if (defined $data_checksums and $method ne 'dump') {
461 error "can only use --(no-)data-checksums with --method=dump";
462 }
463
464 # untaint
465 ($newversion) = $newversion =~ /^(\d+\.?\d+)$/;
466 ($locale) = $locale =~ /^([\w@._-]+)$/ if $locale;
467 ($lc_collate) = $lc_collate =~ /^([\w@._-]+)$/ if $lc_collate;
468 ($lc_ctype) = $lc_ctype =~ /^([\w@._-]+)$/ if $lc_ctype;
469 ($lc_messages) = $lc_messages =~ /^([\w@._-]+)$/ if $lc_messages;
470 ($lc_monetary) = $lc_monetary =~ /^([\w@._-]+)$/ if $lc_monetary;
471 ($lc_numeric) = $lc_numeric =~ /^([\w@._-]+)$/ if $lc_numeric;
472 ($lc_time) = $lc_time =~ /^([\w@._-]+)$/ if $lc_time;
473 ($logfile) = $logfile =~ /^([^\n]+)$/ if $logfile;
474 ($old_bindir) = $old_bindir =~ /^(\/.*)$/ if $old_bindir;
475 ($maintenance_db) = $maintenance_db =~ /^([\w-]+)$/ if $maintenance_db;
476 if ($jobs) {
477 ($jobs) = $jobs =~ /^(\d+)$/;
478 $ENV{PGJOBS} = $jobs; # make setting available to upgrade hooks
479 }
480
481 if ($#ARGV < 1) {
482 print "Usage: $0 [OPTIONS] <old version> <cluster name> [<new data directory>]\n";
483 exit 1;
484 }
485
486 ($version) = $ARGV[0] =~ /^(\d+\.?\d+)$/;
487 ($cluster) = $ARGV[1] =~ /^([-.\w]+)$/;
488 $newcluster ||= $cluster; # use old cluster name by default
489 ($newcluster) = $newcluster =~ /^([-.\w]+)$/;
490 my $datadir;
491 ($datadir) = $ARGV[2] =~ /(.*)/ if defined $ARGV[2];
492
493 error 'specified cluster does not exist' unless cluster_exists $version, $cluster;
494 %info = cluster_info ($version, $cluster);
495 validate_cluster_owner \%info;
496 error 'cluster is disabled' if $info{'start'} eq 'disabled';
497
498 error "cluster $version/$cluster is already on version $newversion. " .
499 "(The newest version installed on this system is $newest_version.)"
500 if ($version eq $newversion and $cluster eq $newcluster);
501
502 if (cluster_exists $newversion, $newcluster) {
503 error "target cluster $newversion/$newcluster already exists";
504 }
505
506 if (not pre_upgrade_check($version, $newversion, $force_packages)) {
507 error "pg_upgradecluster pre-upgrade checks failed";
508 }
509
510 if ($check_only) {
511 print "pg_upgradecluster pre-upgrade checks ok\n";
512 exit;
513 }
514
515 print "Upgrading cluster $version/$cluster to $newversion/$newcluster ...\n";
516
517 my $oldcontrol = get_cluster_controldata ($version, $cluster);
518
519 my $oldsocket = get_cluster_socketdir $version, $cluster;
520 my $owner = getpwuid $info{'owneruid'};
521 error 'could not get name of cluster owner' unless $owner;
522 my $temp_hba_conf = temp_hba_conf $version, $cluster, $owner, $info{'owneruid'};
523
524 # stop old cluster
525 if ($info{'running'}) {
526 get_encoding $version, $cluster;
527 print "Stopping old cluster...\n";
528 my @argv = ('pg_ctlcluster', $version, $cluster, 'stop');
529 error "Could not stop old cluster" if system @argv;
530 }
531
532 if ($method eq 'dump' or ($method eq 'upgrade' and not $info{'running'})) {
533 print "Restarting old cluster with restricted connections...\n";
534 my @argv = ('pg_ctlcluster',
535 ($old_bindir ? ("--bindir=$old_bindir") : ()),
536 $version, $cluster, 'start', '-o', "-c hba_file=$temp_hba_conf");
537 error "Could not restart old cluster" if system @argv;
538
539 get_encoding $version, $cluster unless ($encoding); # if the cluster was not running before, get encoding now
540
541 if ($method eq 'upgrade') {
542 print "Stopping old cluster...\n";
543 @argv = ('pg_ctlcluster', $version, $cluster, 'stop');
544 error "Could not stop old cluster" if system @argv;
545 }
546 }
547
548 # in dump mode, old cluster is running now
549 # in upgrade mode, old cluster is stopped
550
551 my $upgrade_port = next_free_port;
552
553 # create new cluster, preserving encoding and locales
554 my @argv = ('pg_createcluster', '-u', $info{'owneruid'}, '-g', $info{'ownergid'},
555 '--socketdir', $info{'socketdir'}, '--port', $upgrade_port, '--no-status',
556 $newversion, $newcluster);
557 push @argv, ('--datadir', $datadir) if $datadir;
558 push @argv, ('--logfile', $logfile) if $logfile;
559 push @argv, ('--encoding', $encoding) unless $locale or $lc_ctype;
560 $lc_ctype ||= $locale || $old_lc_ctype;
561 $lc_collate ||= $locale || $old_lc_collate;
562 push @argv, ('--locale', $locale) if $locale;
563 push @argv, ('--lc-collate', $lc_collate) if $lc_collate;
564 push @argv, ('--lc-ctype', $lc_ctype) if $lc_ctype;
565 push @argv, ('--lc-messages', $lc_messages) if $lc_messages;
566 push @argv, ('--lc-monetary', $lc_monetary) if $lc_monetary;
567 push @argv, ('--lc-numeric', $lc_numeric) if $lc_numeric;
568 push @argv, ('--lc-time', $lc_time) if $lc_time;
569 push @argv, ('--');
570 push @argv, ('--locale-provider', $old_locale_provider) if $old_locale_provider;
571 push @argv, ('--icu-locale', $old_icu_locale) if $old_icu_locale;
572 push @argv, ('--icu-rules', $old_icu_rules) if $old_icu_rules;
573 if ($oldcontrol->{'Data page checksum version'} or (defined $data_checksums and $data_checksums == 1)) { # oldcontrol 0 = off
574 # enable data checksums if the old cluster had them
575 push @argv, ('--data-checksums');
576 } else {
577 if ($newversion >= 18 and ($method eq 'upgrade' or (defined $data_checksums and $data_checksums == 0))) {
578 # disable data checksums when they would be enabled by default (18+), but the method uses doesn't allow transitioning
579 push @argv, ('--no-data-checksums');
580 }
581 }
582 push @argv, ('--encryption-key-command', $info{config}->{encryption_key_command}) if $info{config}->{encryption_key_command}; # PostgreSQL TDE
583
584 # call pg_createcluster
585 delete $ENV{'LC_ALL'};
586 error "Could not create target cluster" if system @argv;
587 print "\n";
588
589 # migrate config files to new cluster before running upgrade
590 %newinfo = cluster_info($newversion, $newcluster);
591 migrate_config_files();
592 set_cluster_port $newversion, $newcluster, $upgrade_port; # use free port during upgrade
593 %newinfo = cluster_info($newversion, $newcluster); # re-read info after migrate_config_files
594
595 if ($method eq 'dump') {
596 print "Starting new cluster...\n";
597 @argv = ('pg_ctlcluster', $newversion, $newcluster, 'start', '-o', "-c hba_file=$temp_hba_conf");
598 error "Could not start target cluster" if system @argv;
599 }
600
601 # check whether upgrade scripts exist
602 my $upgrade_scripts = (-d "$PgCommon::common_confdir/pg_upgradecluster.d" &&
603 ($PgCommon::rpm ? `ls $PgCommon::common_confdir/pg_upgradecluster.d` :
604 `run-parts --test $PgCommon::common_confdir/pg_upgradecluster.d`));
605
606 # Run upgrade scripts in init phase
607 run_upgrade_scripts('init') if ($upgrade_scripts);
608 print "\n";
609
610 # dump cluster; drop to cluster owner privileges
611
612 if (!fork) {
613 change_ugid $info{'owneruid'}, $info{'ownergid'};
614 my $pg_dumpall = get_program_path 'pg_dumpall', $newversion;
615 my $psql = get_program_path 'psql';
616 my $newsocket = get_cluster_socketdir $newversion, $newcluster;
617
618 # ensure we can upgrade DBs with default read-only transactions
619 $ENV{PGOPTIONS} .= " -cdefault_transaction_read_only=off";
620
621 if ($method eq 'dump') {
622 # get list of read-only databases
623 open F, '-|', $psql, '-h', $oldsocket, '-p', $info{'port'}, '-d', $maintenance_db, '-AXtc',
624 "SELECT datname FROM pg_database WHERE NOT datallowconn AND datname <> 'template0'" or
625 error 'Could not get pg_database list';
626 my $ro_databases = <F>;
627 close F;
628 error "some databases are not accepting connections, cannot upgrade cluster:\n$ro_databases" if ($ro_databases);
629
630 # Upgrade databases
631 print "Upgrading databases ...\n";
632 my @argv = (
633 '/usr/share/postgresql-common/pg_dumpcluster',
634 -A => $pg_dumpall, -h => $oldsocket, -p => $info{port},
635 -Q => $psql, -H => $newsocket, -P => $newinfo{port},
636 -U => $owner);
637 print "@argv\n";
638 my $status = system @argv;
639 exit 1 if ($status != 0);
640
641 } else {
642 # pg_upgrade
643
644 use File::Temp qw(tempdir);
645
646 my $pg_upgrade = get_program_path 'pg_upgrade', $newversion;
647 $pg_upgrade or error "pg_upgrade $newversion not found";
648 my @argv = ($pg_upgrade,
649 '-b', ($old_bindir || "$PgCommon::binroot$version/bin"),
650 '-B', "$PgCommon::binroot$newversion/bin",
651 '-p', $info{'port'},
652 '-P', $newinfo{'port'},
653 );
654 if ($version <= 9.1) {
655 push @argv, '-d', $info{pgdata}, '-o', "-D $info{configdir}"; # -o and -D configdir require $newversion >= 9.2
656 } else {
657 push @argv, '-d', $info{configdir};
658 }
659 push @argv, '-D', $newinfo{configdir};
660 push @argv, "--link" if $link;
661 push @argv, "--clone" if $clone;
662 push @argv, '-j', $jobs if $jobs;
663
664 # Make a directory for pg_upgrade to store its reports and log files.
665 my $logdir = tempdir("/var/log/postgresql/pg_upgradecluster-$version-$newversion-$newcluster.XXXX");
666 chdir $logdir;
667
668 # Run pg_upgrade.
669 print "@argv\n";
670 my $status = system @argv;
671
672 # Remove the PID file of the old cluster (normally removed by
673 # pg_ctlcluster, but not by pg_upgrade).
674 unlink "/var/run/postgresql/$version-$cluster.pid";
675
676 # Move output files to our log directory
677 if (-d (my $outdir = "$newinfo{pgdata}/pg_upgrade_output.d")) {
678 system mv => $outdir, $logdir
679 and error "Could not move $outdir to $logdir";
680 }
681 rmdir $logdir; # remove it if it's empty
682 print "pg_upgradecluster: pg_upgrade output scripts are in $logdir\n" if (-d $logdir);
683
684 exit 1 if ($status != 0);
685 }
686
687 exit 0;
688 }
689
690 wait;
691
692 if ($?) {
693 print "\n";
694
695 unless ($keep_on_error) {
696 print STDERR "Error during cluster dumping, removing new cluster\n";
697 system 'pg_dropcluster', '--stop', $newversion, $newcluster;
698 }
699
700 # Restart old cluster (two steps because we started without systemd)
701 system 'pg_ctlcluster', $version, $cluster, 'stop'; # ignore errors, it might be down anyway
702 if ($info{running}) {
703 print "Starting old cluster again ...\n";
704 if (system 'pg_ctlcluster', $version, $cluster, 'start') {
705 error 'could not start old cluster, please do that manually';
706 }
707 }
708 exit 1;
709 }
710
711 if ($method eq 'dump') {
712 print "Stopping target cluster...\n";
713 @argv = ('pg_ctlcluster', $newversion, $newcluster, 'stop');
714 error "Could not stop target cluster" if system @argv;
715
716 print "Stopping old cluster...\n";
717 @argv = ('pg_ctlcluster', $version, $cluster, 'stop');
718 error "Could not stop old cluster" if system @argv;
719 }
720
721 print "Disabling automatic startup of old cluster...\n";
722 my $startconf = $info{'configdir'}.'/start.conf';
723 if (open F, ">$startconf") {
724 print F "# This cluster was upgraded to a newer major version. The old
725 # cluster has been preserved for backup purposes, but is not started
726 # automatically.
727
728 manual
729 ";
730 close F;
731 } else {
732 error "could not create $startconf: $!";
733 }
734
735 my $free_port = next_free_port;
736 unless ($keep_port) {
737 set_cluster_port $version, $cluster, $upgrade_port;
738 set_cluster_port $newversion, $newcluster, $info{port};
739 $newinfo{port} = $info{port};
740 }
741
742 # notify systemd that we modified the old start.conf
743 if (not exists $ENV{'PG_CLUSTER_CONF_ROOT'} and -d '/run/systemd/system' and $> == 0) {
744 system 'systemctl daemon-reload';
745 }
746
747 # start cluster if it was running before, or upgrade scripts are present
748 $start = ($info{running} or $upgrade_scripts) if ($start == -1);
749 if ($start) {
750 print "Starting upgraded cluster on port $newinfo{port}...\n";
751 @argv = ('pg_ctlcluster', $newversion, $newcluster, 'start');
752 error "Could not start upgraded cluster; please check configuration and log files" if system @argv;
753 }
754
755 # Run upgrade scripts in finish phase
756 if ($upgrade_scripts) {
757 if ($start) {
758 run_upgrade_scripts('finish');
759 } else {
760 print "Warning: Skipping upgrade scripts because --no-start was given\n";
761 }
762 }
763
764 print "\nSuccess. Please check that the upgraded cluster works. If it does,
765 you can remove the old cluster with
766 pg_dropcluster $version $cluster\n\n";
767
768 system 'pg_lsclusters', $version, $cluster;
769 system 'pg_lsclusters', $newversion, $newcluster;
770
771 __END__
772
773 =head1 NAME
774
775 pg_upgradecluster - upgrade an existing PostgreSQL cluster to a new major version.
776
777 =head1 SYNOPSIS
778
779 B<pg_upgradecluster> [B<-v> I<newversion>] I<oldversion> I<name> [I<newdatadir>]
780
781 =head1 DESCRIPTION
782
783 B<pg_upgradecluster> upgrades an existing PostgreSQL server cluster (i. e. a
784 collection of databases served by a B<postgres> instance) to a new version
785 specified by I<newversion> (default: latest available version). The
786 configuration files of the old version are copied to the new cluster and
787 adjusted for the new version.
788
789 By default, L<pg_dump(1)> is used to migrate data and indexes to the new
790 cluster. This is slow, but safe. Upgrade variants based on L<pg_upgrade(1)> can
791 be selected using the B<--method=upgrade> parameter. This is faster, but care
792 must be taken when using it in the context of an operating system upgrade. The
793 sorting order ("collation") used in indexes is determined by B<libc> and
794 B<libicu>, and new versions of these libraries might have a differ ordering,
795 B<requiring index rebuilds after the upgrade>, or acknowledging that the
796 ordering did not change using the B<ALTER COLLATION REFRESH VERSION> command.
797 This step is not automated by B<pg_upgradecluster>.
798
799 The cluster of the old version will be configured to use a previously unused
800 port since the upgraded one will use the original port. The old cluster is not
801 automatically removed. After upgrading, please verify that the new cluster
802 indeed works as expected; if so, you should remove the old cluster with
803 L<pg_dropcluster(8)>. Please note that the old cluster is set to "manual"
804 startup mode, in order to avoid inadvertently changing it; this means that it
805 will not be started automatically on system boot, and you have to use
806 L<pg_ctlcluster(8)> to start/stop it. See section "STARTUP CONTROL" in
807 L<pg_createcluster(8)> for details.
808
809 The I<newdatadir> argument can be used to specify a non-default data directory
810 of the upgraded cluster. It is passed to B<pg_createcluster>. If not specified,
811 this defaults to /var/lib/postgresql/I<newversion>/I<name>.
812
813 =head1 OPTIONS
814
815 =over 4
816
817 =item B<-v> I<newversion>
818
819 Set the version to upgrade to (default: latest available).
820
821 =item B<--check>
822
823 Check if all packages required for the upgrade are installed.
824
825 =item B<--force-packages>
826
827 Proceed with upgrading even when not all packages from the old PostgreSQL
828 version are installed for the new version as well.
829
830 =item B<--logfile> I<filel>
831
832 Set a custom log file path for the upgraded database cluster.
833
834 =item B<--locale=>I<locale>
835
836 Set the default locale for the upgraded database cluster. If this option is not
837 specified, the locale is inherited from the old cluster.
838
839 When upgrading to PostgreSQL 11 or newer, this option no longer allows
840 switching the encoding of individual databases. (L<pg_dumpall(1)> was changed to
841 retain database encodings.)
842
843 =item B<--lc-collate=>I<locale>
844
845 =item B<--lc-ctype=>I<locale>
846
847 =item B<--lc-messages=>I<locale>
848
849 =item B<--lc-monetary=>I<locale>
850
851 =item B<--lc-numeric=>I<locale>
852
853 =item B<--lc-time=>I<locale>
854
855 Like B<--locale>, but only sets the locale in the specified category.
856
857 =item B<-m>, B<--method=>B<dump>|B<upgrade>|B<link>|B<clone>
858
859 Specify the upgrade method. B<dump> uses L<pg_dumpall(1)>, B<upgrade> uses
860 L<pg_upgrade(1)>. The default is B<dump>.
861
862 B<link> and B<clone> are shorthands for B<-m upgrade --link> and B<-m upgrade --clone>,
863 respectively.
864
865 =item B<-k>, B<--link>
866
867 In pg_upgrade mode, use hard links instead of copying files to the new
868 cluster. This option is merely passed on to pg_upgrade. See
869 L<pg_upgrade(1)> for details.
870
871 =item B<--clone>
872
873 In pg_upgrade mode, use efficient file cloning (also known as "reflinks"
874 on some systems) instead of copying files to the new cluster. This option
875 is merely passed on to pg_upgrade. See L<pg_upgrade(1)> for details.
876
877 =item B<--data-checksums>, B<--no-data-checksums>
878
879 By default, the new cluster is set up to use data page checksums if the old
880 cluster already uses them. Additionally, when using the B<dump> upgrade method,
881 the new cluster will use data page checksums when upgrading to PostgreSQL 18 or
882 later (which enables data page checksums by default).
883
884 The B<--method=dump> behavior can explictly be controlled by the
885 B<--data-checksums> and B<--no-data-checksums> options.
886
887 =item B<-j>, B<--jobs>
888
889 In pg_upgrade mode, number of simultaneous processes to use. This
890 option is passed on to pg_upgrade. See L<pg_upgrade(1)> for details.
891 It is also used by the B<analyze> upgrade hook (via the B<PGJOBS> environment
892 variable).
893
894 =item B<--keep-port>
895
896 By default, the old cluster is moved to a new port, and the new cluster is
897 moved to the original port so clients will see the upgraded cluster. This
898 option disables that.
899
900 =item B<--rename=>I<new cluster name>
901
902 Use a different name for the upgraded cluster.
903
904 =item B<--old-bindir=>I<directory>
905
906 Passed to B<pg_upgrade>.
907
908 =item B<--maintenance-db=>I<database>
909
910 Database to connect to for maintenance queries. The default is B<template1>.
911
912 =item B<--[no-]start>
913
914 Start the new database cluster after upgrading. The default is to start the new
915 cluster if the old cluster was running, or if upgrade hook scripts are present.
916
917 =item B<--keep-on-error>
918
919 If upgrading fails, the newly created cluster is removed. This option disables
920 that.
921
922 =back
923
924 =head1 HOOK SCRIPTS
925
926 Some PostgreSQL extensions like PostGIS need metadata in auxiliary tables which
927 must not be upgraded from the old version, but rather initialized for the new
928 version before copying the table data. For this purpose, extensions (as well as
929 administrators, of course) can drop upgrade hook scripts into
930 C</etc/postgresql-common/pg_upgradecluster.d/>. Script file names must consist
931 entirely of upper and lower case letters, digits, underscores, and hyphens; in
932 particular, dots (i. e. file extensions) are not allowed.
933
934 Scripts in that directory will be called with the following arguments:
935
936 <old version> <cluster name> <new version> <phase>
937
938 Phases:
939
940 =over
941
942 =item B<init>
943
944 A virgin cluster of version I<new version> has been created, i. e. this new
945 cluster will already have B<template1> and B<postgres>, but no user databases. Please note that
946 you should not create tables in this phase, since they will be overwritten by
947 the dump/restore or B<pg_upgrade> operation.
948
949 =item B<finish>
950
951 All data from the old version cluster has been restored into the new
952 one. The old cluster still exists, but is not running.
953
954 =back
955
956 Failing scripts will abort the upgrade.
957 The scripts are called as the user who owns the database.
958
959 =head1 SEE ALSO
960
961 L<pg_createcluster(8)>, L<pg_dropcluster(8)>, L<pg_lsclusters(1)>, L<pg_wrapper(1)>,
962 L<pg_dumpall(1)>, L<pg_upgrade(1)>
963
964 =head1 AUTHORS
965
966 Martin Pitt L<E<lt>[email protected]<gt>>, Christoph Berg L<E<lt>[email protected]<gt>>