Postgres.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. my $no_period_version = $ver2install =~ s/\.//r;
  76. my @RPMS = (
  77. "postgresql$no_period_version",
  78. "postgresql$no_period_version-libs",
  79. "postgresql$no_period_version-server",
  80. "postgresql$no_period_version-devel", # For CCS
  81. );
  82. # TODO: Use Cpanel::Yum::Install based module, let all that stuff handle this "for you".
  83. open( my $lh, ">", $log ) or return _cleanup("255");
  84. select $lh;
  85. $| = 1;
  86. select $lh;
  87. # So, since I can't know what all crap to eval here,
  88. # let's just catch all the dies and throw generic
  89. # errors in this event then trigger rollback.
  90. local $SIG{__DIE__} = sub {
  91. print $lh "# [ERROR] ", @_;
  92. require Devel::StackTrace;
  93. my $trace = Devel::StackTrace->new();
  94. print $lh $trace->as_string(), "\n";
  95. _cleanup('255');
  96. die @_;
  97. };
  98. print $lh "# [INFO] Beginning install...\n";
  99. my $exit;
  100. require Cpanel::AccessIds::ReducedPrivileges;
  101. require Cpanel::SafeRun::Object;
  102. require Cpanel::Services::Enabled;
  103. my $postgres_enabled = Cpanel::Services::Enabled::is_enabled('postgresql');
  104. if( Cpanel::Services::Enabled::is_enabled('postgresql') ) {
  105. print $lh "# [INFO] Disabling postgresql during the upgrade window since it is currently enabled...\n";
  106. # Don't use Whostmgr::Services, as that bungles the __DIE__ overwrite.
  107. $exit = _saferun( $lh, qw{/usr/local/cpanel/bin/whmapi1 configureservice service=postgresql enabled=0 monitored=0} );
  108. return _cleanup("$exit") if $exit;
  109. print $lh "# [INFO] Adding 're-enable postgresql' to \@ROLLBACKS stack...\n";
  110. my $rb = sub { _saferun( $lh, qw{/usr/local/cpanel/bin/whmapi1 configureservice service=postgresql enabled=1 monitored=1} ); };
  111. push @ROLLBACKS, $rb;
  112. }
  113. # Check for CCS. Temporarily disable it if so.
  114. require Cpanel::RPM;
  115. my $ccs_installed = Cpanel::RPM->new()->get_version('cpanel-ccs-calendarserver');
  116. $ccs_installed = $ccs_installed->{'cpanel-ccs-calendarserver'};
  117. my $ccs_enabled = Cpanel::Services::Enabled::is_enabled('cpanel-ccs');
  118. if( $ccs_installed && $ccs_enabled ) {
  119. print $lh "# [INFO] cpanel-ccs-calendarserver is installed.\nDisabling the service while the upgrade is in process.\n\n";
  120. $exit = _saferun( $lh, qw{/usr/local/cpanel/bin/whmapi1 configureservice service=cpanel-ccs enabled=0 monitored=0} );
  121. return _cleanup("$exit") if $exit;
  122. print $lh "# [INFO] Adding 're-enable cpanel-ccs' to \@ROLLBACKS stack...\n";
  123. my $rb = sub { _saferun( $lh, qw{/usr/local/cpanel/bin/whmapi1 configureservice service=cpanel-ccs enabled=1 monitored=1} ) };
  124. push @ROLLBACKS, $rb;
  125. }
  126. $exit = _saferun( $lh, 'yum', qw{install -y}, @RPMS );
  127. return _cleanup("$exit") if $exit;
  128. print $lh "# [INFO] Adding 'yum remove new pg version' to \@ROLLBACKS stack...\n";
  129. my $rollbck = sub { _saferun( $lh, 'yum', qw{remove -y}, @RPMS ) };
  130. push @ROLLBACKS, $rollbck;
  131. # Init the DB
  132. my $locale = $ENV{'LANG'} || 'en_US.UTF-8';
  133. {
  134. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  135. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '--locale', $locale, '-E', 'UTF8', '-D', "/var/lib/pgsql/$ver2install/data/" );
  136. }
  137. return _cleanup("$exit") if $exit;
  138. # probably shouldn't do it this way. Whatever
  139. print $lh "# [INFO] Adding 'Clean up new pgdata dir' to \@ROLLBACKS stack...\n";
  140. my $rd_rllr = sub { _saferun( $lh, qw{rm -rf}, "/var/lib/pgsql/$ver2install/data" ) };
  141. push @ROLLBACKS, $rd_rllr;
  142. require File::Slurper;
  143. # Move some bullcrap out of the way if we're on old PGs
  144. require Cpanel::PostgresUtils;
  145. my @cur_ver = ( Cpanel::PostgresUtils::get_version() );
  146. my $str_ver = join( '.', @cur_ver );
  147. if( $str_ver + 0 < 9.4 ) {
  148. print $lh "# [INFO] Installed version is less than 9.4 ($str_ver), Implementing workaround in pg_ctl to ensure pg_upgrade works...\n";
  149. require File::Copy;
  150. print $lh "# [BACKUP] Backing up /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig\n";
  151. File::Copy::cp('/usr/bin/pg_ctl','/usr/bin/pg_ctl.orig') or do {
  152. print $lh "Backup of /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig failed: $!\n";
  153. return _cleanup("255");
  154. };
  155. chmod(0755, '/usr/bin/pg_ctl.orig');
  156. print $lh "# [INFO] Adding 'Restore old pg_ctl process to \@ROLLBACKS stack...\n";
  157. my $rb = sub { File::Copy::mv('/usr/bin/pg_ctl.orig','/usr/bin/pg_ctl'); };
  158. push @ROLLBACKS, $rb;
  159. my $pg_ctl_contents = "#!/bin/bash\n\"\$0\".orig \"\${@/unix_socket_directory/unix_socket_directories}\"";
  160. File::Slurper::write_binary( "/usr/bin/pg_ctl", $pg_ctl_contents );
  161. chmod( 0755, '/usr/bin/pg_ctl' );
  162. print $lh "# [INFO] Workaround should be in place now. Proceeding with pg_upgrade.\n\n";
  163. }
  164. print $lh "# [INFO] Setting things up for pg_upgrade -- delete postmaster.pid, ensure .pgpass in place.\n";
  165. require Cpanel::Chdir;
  166. # Upgrade the cluster
  167. # /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/
  168. 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/" );
  169. unlink '/var/lib/pgsql/data/postmaster.pid';
  170. # Copy over the .pgpass file for the postgres user so that it knows how to connect as itself (oof)
  171. File::Copy::cp('/root/.pgpass', '/var/lib/pgsql/.pgpass');
  172. print $lh "# [INFO] Adding 'cleanup .pgpass file to \@ROLLBACKS stack...\n";
  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. print "# [INFO] Now running pg_upgrade on the default cluster...\n";
  179. {
  180. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  181. my $cd_obj = Cpanel::Chdir->new('/var/lib/pgsql');
  182. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  183. '-d', $old_datadir,
  184. '-D', "/var/lib/pgsql/$ver2install/data/",
  185. '-b', $old_bindir,
  186. '-B', "/usr/pgsql-$ver2install/bin/",
  187. );
  188. }
  189. return _cleanup("$exit") if $exit;
  190. # Start the server.
  191. print $lh "# [INFO] Starting up postgresql-$ver2install...\n";
  192. $exit = _saferun( $lh, qw{systemctl start}, "postgresql-$ver2install" );
  193. return _cleanup("$exit") if $exit;
  194. if( $ccs_installed ) {
  195. my $ccs_pg_datadir = '/opt/cpanel-ccs/data/Data/Database/cluster';
  196. print $lh "# [INFO] Old PG datadir is being moved to '$ccs_pg_datadir.old'...\n";
  197. File::Copy::mv( $ccs_pg_datadir, "$ccs_pg_datadir.old" );
  198. mkdir($ccs_pg_datadir);
  199. chmod( 0700, $ccs_pg_datadir );
  200. Cpanel::SafetyBits::Chown::safe_chown( 'cpanel-ccs', 'cpanel-ccs', $ccs_pg_datadir );
  201. print $lh "# [INFO] Adding 'restore old CCS cluster' to \@ROLLBACKS stack...\n";
  202. my $rb = sub {
  203. require File::Path;
  204. File::Path::remove_tree($ccs_pg_datadir, { 'error' => \my $err } );
  205. print $lh join( "\n", @$err ) if ( $err && @$err );
  206. File::Copy::mv( "$ccs_pg_datadir.old", $ccs_pg_datadir );
  207. };
  208. push @ROLLBACKS, $rb;
  209. print $lh "# [INFO] Now initializing the new PG cluster for cpanel-ccs-calendarserver...\n";
  210. unlink '/opt/cpanel-ccs/data/Data/Database/cluster/postmaster.pid';
  211. # Init the DB
  212. {
  213. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  214. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '-D', $ccs_pg_datadir, '-U', 'caldav', '--locale', $locale, '-E', 'UTF8' );
  215. }
  216. return _cleanup("$exit") if $exit;
  217. print $lh "# [INFO] Now upgrading the PG cluster for cpanel-ccs-calendarserver...\n";
  218. # Upgrade the DB
  219. {
  220. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  221. my $cd_obj = Cpanel::Chdir->new('/opt/cpanel-ccs');
  222. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  223. '-d', "$ccs_pg_datadir.old",
  224. '-D', $ccs_pg_datadir,
  225. '-b', $old_bindir,
  226. '-B', "/usr/pgsql-$ver2install/bin/",
  227. qw{-U caldav},
  228. );
  229. }
  230. return _cleanup("$exit") if $exit;
  231. }
  232. # At this point we're at the point where we don't need to restore. Just clean up.
  233. print $lh "# [INFO] Clearing \@ROLLBACKS stack, as we have cleared the necessary checkpoint.\n";
  234. @ROLLBACKS = ();
  235. if( $str_ver + 0 < 9.4 ) {
  236. print $lh "# [INFO] Workaround resulted in successful start of the server. Reverting workaround changes to pg_ctl...\n\n";
  237. rename( '/usr/bin/pg_ctl.orig', '/usr/bin/pg_ctl' ) or do {
  238. print $lh "# [ERROR] Restore of /usr/bin/pg_ctl.orig to /usr/bin/pg_ctl failed: $!\n";
  239. return _cleanup("255");
  240. };
  241. }
  242. print $lh "# [INFO] Now cleaning up old postgresql version...\n";
  243. my $svc2remove = ( $str_ver + 0 < 9.5 ) ? 'postgresql' : "postgresql-$str_ver";
  244. $exit = _saferun( $lh, qw{systemctl disable}, $svc2remove );
  245. return _cleanup("$exit") if $exit;
  246. $exit = _saferun( $lh, qw{yum -y remove}, $svc2remove );
  247. return _cleanup("$exit") if $exit;
  248. print $lh "# [INFO] Now enabling postgresql-$ver2install on startup...\n";
  249. $exit = _saferun( $lh, qw{systemctl enable}, "postgresql-$ver2install" );
  250. return _cleanup("$exit") if $exit;
  251. if($ccs_installed && $ccs_enabled) {
  252. print $lh "# [INFO] Re-Enabling cpanel-ccs-calendarserver...\n";
  253. $exit = _saferun( $lh, qw{/usr/local/cpanel/bin/whmapi1 configureservice service=cpanel-ccs enabled=1 monitored=1} );
  254. return _cleanup("$exit") if $exit;
  255. }
  256. # XXX Now the postgres service appears as "disabled" for cPanel's sake. Frowny faces everywhere.
  257. # Not sure how to fix yet.
  258. if($postgres_enabled) {
  259. print $lh "# [INFO] Re-Enabling postgres services for cPanel...\n";
  260. print $lh "# [TODO] Actually do this!\n";
  261. }
  262. return _cleanup("0");
  263. }
  264. sub _saferun {
  265. my ( $lh, $prog, @args ) = @_;
  266. my $run_result = Cpanel::SafeRun::Object->new(
  267. 'program' => $prog,
  268. 'args' => [ @args ],
  269. 'stdout' => $lh,
  270. 'stderr' => $lh,
  271. );
  272. my $exit = $run_result->error_code() || 0;
  273. return $exit;
  274. }
  275. sub _cleanup {
  276. my ( $code ) = @_;
  277. # Do rollbacks in reverse order
  278. foreach my $rb ( reverse @ROLLBACKS ) {
  279. local $@;
  280. eval { $rb->(); };
  281. my $exit = $@ ? 255 : 0;
  282. if($exit) {
  283. $code = $exit;
  284. last;
  285. }
  286. }
  287. # Signal completion
  288. eval { symlink( $code, "$dir/INSTALL_EXIT_CODE" ); };
  289. unlink("$dir/INSTALL_IN_PROGRESS");
  290. return;
  291. }
  292. # Elegance??? Websocket??? Nah. EZ mode actibated
  293. sub get_latest_upgradelog_messages {
  294. my ( $args_hr ) = @_;
  295. my $child_exit;
  296. my $in_progress = -l "$dir/INSTALL_IN_PROGRESS";
  297. if(!$in_progress) {
  298. $child_exit = readlink("$dir/INSTALL_EXIT_CODE");
  299. }
  300. # XXX validate log arg? Don't want arbitrary file reads?
  301. # read from it using seek and tell to control
  302. open( my $rh, "<", $args_hr->{'log'} );
  303. seek( $rh, $args_hr->{'start'}, 0 ) if $args_hr->{'start'};
  304. my $content = '';
  305. while( my $line = <$rh> ) {
  306. $content .= $line;
  307. }
  308. my $pos = tell($rh);
  309. close($rh);
  310. return {
  311. 'in_progress' => $in_progress,
  312. 'child_exit' => $child_exit,
  313. 'next' => $pos,
  314. 'new_content' => $content,
  315. }
  316. }
  317. 1;