Postgres.pm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package Troglodyne::API::Postgres;
  2. use strict;
  3. use warnings;
  4. use Cpanel::LoadModule::Custom;
  5. our $dir = '/var/cpanel/logs/troglodyne/pgupgrade';
  6. sub get_postgresql_versions {
  7. Cpanel::LoadModule::Custom::load_perl_module('Troglodyne::CpPostgreSQL');
  8. require Cpanel::PostgresUtils;
  9. my @ver_arr = ( Cpanel::PostgresUtils::get_version() );
  10. my $running = eval { readlink("$dir/INSTALL_IN_PROGRESS"); } || 0;
  11. return {
  12. 'installed_version' => { 'major' => $ver_arr[0], 'minor' => $ver_arr[1] },
  13. 'minimum_supported_version' => $Troglodyne::CpPostgreSQL::MINIMUM_SUPPORTED_VERSION,
  14. 'available_versions' => \%Troglodyne::CpPostgreSQL::SUPPORTED_VERSIONS_MAP,
  15. 'eol_versions' => \%Troglodyne::CpPostgreSQL::CP_UNSUPPORTED_VERSIONS_MAP,
  16. 'install_currently_running' => $running,
  17. };
  18. }
  19. sub enable_community_repositories {
  20. Cpanel::LoadModule::Custom::load_perl_module('Troglodyne::CpPostgreSQL');
  21. require Cpanel::Sys::OS;
  22. my $centos_ver = substr( Cpanel::Sys::OS::getreleaseversion(), 0, 1 );
  23. my $repo_rpm_url = $Troglodyne::CpPostgreSQL::REPO_RPM_URLS{$centos_ver};
  24. # TODO Use Cpanel::SafeRun::Object to run the install?
  25. require Capture::Tiny;
  26. my @cmd = qw{/bin/rpm -q pgdg-redhat-repo};
  27. my ( $stdout, $stderr, $ret ) = Capture::Tiny::capture( sub {
  28. system(@cmd);
  29. });
  30. my $installed = !$ret;
  31. if( !$installed ) {
  32. @cmd = ( qw{/bin/rpm -i}, $repo_rpm_url );
  33. ( $stdout, $stderr, $ret ) = Capture::Tiny::capture( sub {
  34. system(@cmd);
  35. } );
  36. }
  37. return {
  38. 'last_yum_command' => join( " ", @cmd ),
  39. 'already_installed' => $installed,
  40. 'stdout' => $stdout,
  41. 'stderr' => $stderr,
  42. 'exit_code' => $ret,
  43. };
  44. }
  45. sub start_postgres_install {
  46. my ( $args_hr ) = @_;
  47. my $version = $args_hr->{'version'};
  48. require Cpanel::Mkdir;
  49. Cpanel::Mkdir::ensure_directory_existence_and_mode( $dir, 0711 );
  50. require Cpanel::FileUtils::Touch;
  51. my $time = time;
  52. my $lgg = "$dir/pgupgrade-to-$version-at-$time.log";
  53. Cpanel::FileUtils::Touch::touch_if_not_exists($lgg);
  54. require Cpanel::Autodie;
  55. Cpanel::Autodie::unlink_if_exists("$dir/last");
  56. require Cpanel::Chdir;
  57. {
  58. my $chdir = Cpanel::Chdir->new($dir);
  59. symlink( "pgupgrade-to-$version-at-$time.log", "last" );
  60. }
  61. # OK. We are logging, now return the log loc after kicking it off.
  62. # Yeah, yeah, I'm forking twice. who cares
  63. require Cpanel::Daemonizer::Tiny;
  64. my $pid = Cpanel::Daemonizer::Tiny::run_as_daemon( \&_real_install, $version, $lgg );
  65. symlink( $pid, "$dir/INSTALL_IN_PROGRESS" ) if $pid;
  66. return {
  67. 'log' => $lgg,
  68. 'pid' => $pid,
  69. };
  70. }
  71. our @ROLLBACKS;
  72. sub _real_install {
  73. my ( $ver2install, $log ) = @_;
  74. @ROLLBACKS = ();
  75. require Cpanel::AccessIds::ReducedPrivileges;
  76. my $no_period_version = $ver2install =~ s/\.//r;
  77. my @RPMS = (
  78. "postgresql$no_period_version",
  79. "postgresql$no_period_version-server",
  80. );
  81. # TODO: Use Cpanel::Yum::Install based module, let all that stuff handle this "for you".
  82. open( my $lh, ">", $log ) or return _cleanup("255");
  83. select $lh;
  84. $| = 1;
  85. select $lh;
  86. print $lh "Beginning install...\n";
  87. require Whostmgr::Services;
  88. require Cpanel::Services::Enabled;
  89. if( Cpanel::Services::Enabled::is_enabled('postgresql') ) {
  90. print $lh "Disabling postgresql during the upgrade window since it is currently enabled...\n";
  91. Whostmgr::Services::disable('postgresql');
  92. my $rb = sub { Whostmgr::Services::enable('postgresql'); };
  93. push @ROLLBACKS, $rb;
  94. }
  95. # Check for CCS. Temporarily disable it if so.
  96. my ( $ccs_installed, $err );
  97. {
  98. local $@;
  99. eval {
  100. require Cpanel::RPM;
  101. $ccs_installed = Cpanel::RPM->new()->get_version('cpanel-ccs-calendarserver');
  102. $ccs_installed = $ccs_installed->{'cpanel-ccs-calendarserver'};
  103. };
  104. $err = $@;
  105. }
  106. if($err) {
  107. print $lh "[ERROR] $err\n";
  108. return _cleanup('255');
  109. }
  110. if($ccs_installed) {
  111. print $lh "\ncpanel-ccs-calendarserver is installed.\nDisabling the service while the upgrade is in process.\n\n";
  112. Whostmgr::Services::disable('cpanel-ccs');
  113. my $rb = sub { Whostmgr::Services::enable('cpanel-ccs'); };
  114. push @ROLLBACKS, $rb;
  115. }
  116. require Cpanel::SafeRun::Object;
  117. my $exit = _saferun( $lh, 'yum', qw{install -y}, @RPMS );
  118. return _cleanup("$exit") if $exit;
  119. my $rollbck = sub { _saferun( $lh, 'yum', qw{remove -y}, @RPMS ) };
  120. push @ROLLBACKS, $rollbck;
  121. # Init the DB
  122. {
  123. local $@;
  124. eval {
  125. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  126. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '-D', "/var/lib/pgsql/$ver2install/data/" );
  127. };
  128. $err = $@;
  129. }
  130. if($err) {
  131. print $lh "[ERROR] $err\n";
  132. return _cleanup('255');
  133. }
  134. return _cleanup("$exit") if $exit;
  135. # probably shouldn't do it this way. Whatever
  136. my $rd_rllr = sub { _saferun( $lh, qw{rm -rf}, "/var/lib/pgsql/$ver2install/data" ) };
  137. push @ROLLBACKS, $rd_rllr;
  138. require File::Slurper;
  139. # Move some bullcrap out of the way if we're on old PGs
  140. require Cpanel::PostgresUtils;
  141. my @cur_ver = ( Cpanel::PostgresUtils::get_version() );
  142. my $str_ver = join( '.', @cur_ver );
  143. if( $str_ver + 0 < 9.4 ) {
  144. print $lh "\n\nInstalled version is less than 9.4 ($str_ver), Implementing workaround in pg_ctl to ensure pg_upgrade works...\n";
  145. require File::Copy;
  146. print $lh "Backing up /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig\n";
  147. File::Copy::cp('/usr/bin/pg_ctl','/usr/bin/pg_ctl.orig') or do {
  148. print $lh "Backup of /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig failed: $!\n";
  149. return _cleanup("255");
  150. };
  151. chmod(0755, '/usr/bin/pg_ctl.orig');
  152. my $rb = sub { File::Copy::mv('/usr/bin/pg_ctl.orig','/usr/bin/pg_ctl'); };
  153. push @ROLLBACKS, $rb;
  154. local $@;
  155. my $pg_ctl_contents = "#!/bin/bash\n\"\$0\".orig \"\${@/unix_socket_directory/unix_socket_directories}\"";
  156. eval {
  157. File::Slurper::write_binary( "/usr/bin/pg_ctl", $pg_ctl_contents );
  158. chmod( 0755, '/usr/bin/pg_ctl' );
  159. };
  160. if($@) {
  161. print $lh "[ERROR] Write to /usr/bin/pg_ctl failed: $@\n";
  162. return _cleanup('255');
  163. }
  164. print $lh "Workaround should be in place now. Proceeding with pg_upgrade.\n\n";
  165. }
  166. require Cpanel::Chdir;
  167. # Upgrade the cluster
  168. # /usr/pgsql-9.6/bin/pg_upgrade --old-datadir /var/lib/pgsql/data/ --new-datadir /var/lib/pgsql/9.6/data/ --old-bindir /usr/bin/ --new-bindir /usr/pgsql-9.6/bin/
  169. my ( $old_datadir, $old_bindir ) = ( $str_ver + 0 < 9.5 ) ? ( '/var/lib/pgsql/data', '/usr/bin' ) : ( "/var/lib/pgsql/$str_ver/data/", "/usr/pgsql-$str_ver/bin/" );
  170. unlink '/var/lib/pgsql/data/postmaster.pid';
  171. # Copy over the .pgpass file for the postgres user so that it knows how to connect as itself (oof)
  172. File::Copy::cp('/root/.pgpass', '/var/lib/pgsql/.pgpass');
  173. my $reb = sub { unlink '/var/lib/pgsql/.pgpass' };
  174. push @ROLLBACKS, $reb;
  175. require Cpanel::SafetyBits::Chown;
  176. Cpanel::SafetyBits::Chown::safe_chown( 'postgres', 'postgres', '/var/lib/pgsql/.pgpass' );
  177. chmod( 0600, '/var/lib/pgsql/.pgpass' );
  178. {
  179. local $@;
  180. eval {
  181. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  182. my $cd_obj = Cpanel::Chdir->new('/var/lib/pgsql');
  183. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  184. '-d', $old_datadir,
  185. '-D', "/var/lib/pgsql/$ver2install/data/",
  186. '-b', $old_bindir,
  187. '-B', "/usr/pgsql-$ver2install/bin/",
  188. );
  189. };
  190. $err = $@;
  191. }
  192. if($err) {
  193. print $lh "[ERROR] $err\n";
  194. return _cleanup('255');
  195. }
  196. return _cleanup("$exit") if $exit;
  197. # Start the server.
  198. $exit = _saferun( $lh, qw{systemctl start}, "postgresql-$ver2install" );
  199. return _cleanup("$exit") if $exit;
  200. if( $ccs_installed ) {
  201. print $lh "\n\nNow upgrading PG cluster for cpanel-ccs-calendarserver...\n";
  202. my $ccs_pg_datadir = '/opt/cpanel-ccs/data/Data/Database/cluster';
  203. print $lh "Old PG datadir is being moved to '$ccs_pg_datadir.old'...\n";
  204. File::Copy::mv( $ccs_pg_datadir, "$ccs_pg_datadir.old" );
  205. mkdir($ccs_pg_datadir);
  206. my $rb = sub { File::Copy::mv( "$ccs_pg_datadir.old", $ccs_pg_datadir ); };
  207. push @ROLLBACKS, $rb;
  208. unlink '/opt/cpanel-ccs/data/Data/Database/cluster/postmaster.pid';
  209. # Init the DB
  210. {
  211. local $@;
  212. eval {
  213. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  214. local $ENV{'PGSETUP_INITDB_OPTIONS'} = "-U caldav --locale=C -E=UTF8";
  215. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '-D', $ccs_pg_datadir );
  216. };
  217. $err = $@;
  218. }
  219. if($err) {
  220. print $lh "[ERROR] $err\n";
  221. return _cleanup('255');
  222. }
  223. return _cleanup("$exit") if $exit;
  224. # Upgrade the DB
  225. {
  226. local $@;
  227. eval {
  228. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  229. my $cd_obj = Cpanel::Chdir->new('/opt/cpanel-ccs');
  230. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  231. '-d', "$ccs_pg_datadir.old",
  232. '-D', $ccs_pg_datadir,
  233. '-b', $old_bindir,
  234. '-B', "/usr/pgsql-$ver2install/bin/",
  235. qw{-c -U caldav},
  236. );
  237. };
  238. $err = $@;
  239. }
  240. if($err) {
  241. print $lh "[ERROR] $err\n";
  242. return _cleanup('255');
  243. }
  244. return _cleanup("$exit") if $exit;
  245. }
  246. # At this point we're at the point where we don't need to restore. Just clean up.
  247. @ROLLBACKS = ();
  248. if( $str_ver + 0 < 9.4 ) {
  249. print $lh "\n\nWorkaround resulted in successful start of the server. Reverting workaround changes to pg_ctl...\n\n";
  250. rename( '/usr/bin/pg_ctl.orig', '/usr/bin/pg_ctl' ) or do {
  251. print $lh "Restore of /usr/bin/pg_ctl.orig to /usr/bin/pg_ctl failed: $!\n";
  252. return _cleanup("255");
  253. };
  254. }
  255. print $lh "\n\nNow cleaning up old postgresql version...\n";
  256. my $svc2remove = ( $str_ver + 0 < 9.5 ) ? 'postgresql' : "postgresql-$str_ver";
  257. $exit = _saferun( $lh, qw{systemctl disable}, $svc2remove );
  258. return _cleanup("$exit") if $exit;
  259. $exit = _saferun( $lh, qw{yum -y remove}, $svc2remove );
  260. return _cleanup("$exit") if $exit;
  261. print $lh "\n\nNow enabling postgresql-$ver2install on startup...\n";
  262. $exit = _saferun( $lh, qw{systemctl enable}, "postgresql-$ver2install" );
  263. return _cleanup("$exit") if $exit;
  264. # Update alternatives. Should be fine to use --auto, as no other alternatives will exist for the installed version.
  265. # Create alternatives for pg_ctl, etc. as those don't get made by the RPM.
  266. print $lh "\n\nUpdating alternatives to ensure the newly installed version is considered canonical...\n";
  267. my @normie_alts = qw{pg_ctl initdb pg_config pg_upgrade};
  268. my @manual_alts = qw{clusterdb createdb createuser dropdb droplang dropuser pg_basebackup pg_dump pg_dumpall pg_restore psql psql-reindexdb vaccumdb};
  269. foreach my $alt ( @normie_alts ) {
  270. $exit = _saferun( $lh, qw{update-alternatives --install}, "/usr/bin/$alt", "pgsql-$alt", "/usr/pgsql-$ver2install/bin/$alt", "50" );
  271. return _cleanup("$exit") if $exit;
  272. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-$alt" );
  273. return _cleanup("$exit") if $exit;
  274. }
  275. foreach my $alt ( @manual_alts ) {
  276. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-$alt" );
  277. return _cleanup("$exit") if $exit;
  278. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-${alt}man" );
  279. return _cleanup("$exit") if $exit;
  280. }
  281. print $lh "\n\nWriting new .bash_profile for the 'postgres' user...\n";
  282. my $bash_profile = "[ -f /etc/profile ] && source /etc/profile
  283. PGDATA=/var/lib/pgsql/$ver2install/data
  284. export PGDATA
  285. [ -f /var/lib/pgsql/.pgsql_profile ] && source /var/lib/pgsql/.pgsql_profile
  286. export PATH=\$PATH:/usr/pgsql-$ver2install/bin\n";
  287. File::Slurper::write_text( '/var/lib/pgsql/.bash_profile', $bash_profile );
  288. if($ccs_installed) {
  289. File::Slurper::write_text( '/opt/cpanel-ccs/.bash_profile', $bash_profile );
  290. print $lh "\nRe-Enabling cpanel-ccs-calendarserver...\n\n";
  291. require Whostmgr::Services;
  292. Whostmgr::Services::enable('cpanel-ccs');
  293. }
  294. return _cleanup("0");
  295. }
  296. sub _saferun {
  297. my ( $lh, $prog, @args ) = @_;
  298. my $run_result = Cpanel::SafeRun::Object->new(
  299. 'program' => $prog,
  300. 'args' => [ @args ],
  301. 'stdout' => $lh,
  302. 'stderr' => $lh,
  303. );
  304. my $exit = $run_result->error_code() || 0;
  305. return $exit;
  306. }
  307. sub _cleanup {
  308. my ( $code ) = @_;
  309. # Do rollbacks in reverse order
  310. foreach my $rb ( reverse @ROLLBACKS ) {
  311. local $@;
  312. eval { $rb->(); };
  313. my $exit = $@ ? 255 : 0;
  314. if($exit) {
  315. $code = $exit;
  316. last;
  317. }
  318. }
  319. # Signal completion
  320. eval { symlink( $code, "$dir/INSTALL_EXIT_CODE" ); };
  321. unlink("$dir/INSTALL_IN_PROGRESS");
  322. return;
  323. }
  324. # Elegance??? Websocket??? Nah. EZ mode actibated
  325. sub get_latest_upgradelog_messages {
  326. my ( $args_hr ) = @_;
  327. my $child_exit;
  328. my $in_progress = -l "$dir/INSTALL_IN_PROGRESS";
  329. if(!$in_progress) {
  330. $child_exit = readlink("$dir/INSTALL_EXIT_CODE");
  331. }
  332. # XXX validate log arg? Don't want arbitrary file reads?
  333. # read from it using seek and tell to control
  334. open( my $rh, "<", $args_hr->{'log'} );
  335. seek( $rh, $args_hr->{'start'}, 0 ) if $args_hr->{'start'};
  336. my $content = '';
  337. while( my $line = <$rh> ) {
  338. $content .= $line;
  339. }
  340. my $pos = tell($rh);
  341. close($rh);
  342. return {
  343. 'in_progress' => $in_progress,
  344. 'child_exit' => $child_exit,
  345. 'next' => $pos,
  346. 'new_content' => $content,
  347. }
  348. }
  349. 1;