Postgres.pm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. # Check for CCS. Temporarily disable it if so.
  88. my ( $ccs_installed, $err );
  89. {
  90. local $@;
  91. eval {
  92. require Cpanel::RPM;
  93. $ccs_installed = Cpanel::RPM->new()->get_version('cpanel-ccs-calendarserver');
  94. $ccs_installed = $ccs_installed->{'cpanel-ccs-calendarserver'};
  95. };
  96. $err = $@;
  97. }
  98. if($err) {
  99. print $lh "[ERROR] $err\n";
  100. return _cleanup('255');
  101. }
  102. print $lh "[DEBUG] CCS Installed? $ccs_installed\n";
  103. if($ccs_installed) {
  104. print $lh "\ncpanel-ccs-calendarserver is installed.\nDisabling the service while the upgrade is in process.\n\n";
  105. require Whostmgr::Services;
  106. Whostmgr::Services::disable('cpanel-ccs');
  107. my $rb = sub { Whostmgr::Services::enable('cpanel-ccs'); };
  108. push @ROLLBACKS, $rb;
  109. }
  110. require Cpanel::SafeRun::Object;
  111. my $exit = _saferun( $lh, 'yum', qw{install -y}, @RPMS );
  112. return _cleanup("$exit") if $exit;
  113. my $rollbck = sub { _saferun( $lh, 'yum', qw{remove -y}, @RPMS ) };
  114. push @ROLLBACKS, $rollbck;
  115. # Init the DB
  116. {
  117. local $@;
  118. eval {
  119. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  120. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '-D', "/var/lib/pgsql/$ver2install/data/" );
  121. };
  122. $err = $@;
  123. }
  124. if($err) {
  125. print $lh "[ERROR] $err\n";
  126. return _cleanup('255');
  127. }
  128. return _cleanup("$exit") if $exit;
  129. # probably shouldn't do it this way. Whatever
  130. my $rd_rllr = sub { _saferun( $lh, qw{rm -rf}, "/var/lib/pgsql/$ver2install/data" ) };
  131. push @ROLLBACKS, $rd_rllr;
  132. require File::Slurper;
  133. # Move some bullcrap out of the way if we're on old PGs
  134. require Cpanel::PostgresUtils;
  135. my @cur_ver = ( Cpanel::PostgresUtils::get_version() );
  136. my $str_ver = join( '.', @cur_ver );
  137. if( $str_ver + 0 < 9.4 ) {
  138. print $lh "\n\nInstalled version is less than 9.4 ($str_ver), Implementing workaround in pg_ctl to ensure pg_upgrade works...\n";
  139. require File::Copy;
  140. print $lh "Backing up /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig\n";
  141. File::Copy::copy('/usr/bin/pg_ctl','/usr/bin/pg_ctl.orig') or do {
  142. print $lh "Backup of /usr/bin/pg_ctl to /usr/bin/pg_ctl.orig failed: $!\n";
  143. return _cleanup("255");
  144. };
  145. my $rb = sub { File::Copy::move('/usr/bin/pg_ctl','/usr/bin/pg_ctl.orig'); };
  146. push @ROLLBACKS, $rb;
  147. print $lh "[DEBUG] Got to reading\n";
  148. local $@;
  149. my $pg_ctl_contents = eval { File::Slurper::read_binary("/usr/bin/pg_ctl") };
  150. if($@) {
  151. print $lh "[ERROR] Read from /usr/bin/pg_ctl failed: $@\n";
  152. return _cleanup('255');
  153. }
  154. print $lh "[DEBUG] READ IN\n";
  155. $pg_ctl_contents =~ s/unix_socket_directory/unix_socket_directories/g;
  156. eval { File::Slurper::write_binary( "/usr/bin/pg_ctl", $pg_ctl_contents ); };
  157. if($@) {
  158. print $lh "[ERROR] Write to /usr/bin/pg_ctl failed: $@\n";
  159. return _cleanup('255');
  160. }
  161. print $lh "Workaround should be in place now. Proceeding with pg_upgrade.\n\n";
  162. }
  163. require Cpanel::Chdir;
  164. print $lh "[DEBUG] Uprade cluster\n";
  165. # Upgrade the cluster
  166. # /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/
  167. 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/" );
  168. {
  169. local $@;
  170. eval {
  171. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('postgres');
  172. my $cd_obj = Cpanel::Chdir->new('/var/lib/pgsql');
  173. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  174. '--old-datadir', $old_datadir,
  175. '--new-datadir', "/var/lib/pgsql/$ver2install/data/",
  176. '--old-bindir', $old_bindir,
  177. '--new_bindir', "/usr/pgsql-$ver2install/bin/",
  178. );
  179. };
  180. $err = $@;
  181. }
  182. if($err) {
  183. print $lh "[ERROR] $err\n";
  184. return _cleanup('255');
  185. }
  186. return _cleanup("$exit") if $exit;
  187. # Start the server.
  188. $exit = _saferun( $lh, qw{systemctl start}, "postgresql-$ver2install" );
  189. return _cleanup("$exit") if $exit;
  190. if( $ccs_installed ) {
  191. print $lh "\n\nNow upgrading PG cluster for cpanel-ccs-calendarserver...\n";
  192. my $ccs_pg_datadir = '/opt/cpanel-ccs/data/Data/Database/cluster';
  193. print $lh "Old PG datadir is being moved to '$ccs_pg_datadir.old'...\n";
  194. File::Copy::move( $ccs_pg_datadir, "$ccs_pg_datadir.old" );
  195. mkdir($ccs_pg_datadir);
  196. my $rb = sub { File::Copy::move( "$ccs_pg_datadir.old", $ccs_pg_datadir ); };
  197. push @ROLLBACKS, $rb;
  198. # Init the DB
  199. {
  200. local $@;
  201. eval {
  202. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  203. local $ENV{'PGSETUP_INITDB_OPTIONS'} = "-U caldav --locale=C -E=UTF8";
  204. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/initdb", '-D', $ccs_pg_datadir );
  205. };
  206. $err = $@;
  207. }
  208. if($err) {
  209. print $lh "[ERROR] $err\n";
  210. return _cleanup('255');
  211. }
  212. return _cleanup("$exit") if $exit;
  213. # Upgrade the DB
  214. {
  215. local $@;
  216. eval {
  217. my $pants_on_the_ground = Cpanel::AccessIds::ReducedPrivileges->new('cpanel-ccs');
  218. my $cd_obj = Cpanel::Chdir->new('/opt/cpanel-ccs');
  219. $exit = _saferun( $lh, "/usr/pgsql-$ver2install/bin/pg_upgrade",
  220. '--old-datadir', "$ccs_pg_datadir.old",
  221. '--new-datadir', $ccs_pg_datadir,
  222. '--old-bindir', $old_bindir,
  223. '--new_bindir', "/usr/pgsql-$ver2install/bin/",
  224. qw{-c -U caldav},
  225. );
  226. };
  227. $err = $@;
  228. }
  229. if($err) {
  230. print $lh "[ERROR] $err\n";
  231. return _cleanup('255');
  232. }
  233. return _cleanup("$exit") if $exit;
  234. }
  235. # At this point we're at the point where we don't need to restore. Just clean up.
  236. @ROLLBACKS = ();
  237. if( $str_ver + 0 < 9.4 ) {
  238. print $lh "\n\nWorkaround resulted in successful start of the server. Reverting workaround changes to pg_ctl...\n\n";
  239. rename( '/usr/bin/pg_ctl.orig', '/usr/bin/pg_ctl' ) or do {
  240. print $lh "Restore of /usr/bin/pg_ctl.orig to /usr/bin/pg_ctl failed: $!\n";
  241. return _cleanup("255");
  242. };
  243. }
  244. print $lh "\n\nNow cleaning up old postgresql version...\n";
  245. my $svc2remove = ( $str_ver + 0 < 9.5 ) ? 'postgresql' : "postgresql-$str_ver";
  246. $exit = _saferun( $lh, qw{systemctl disable}, $svc2remove );
  247. return _cleanup("$exit") if $exit;
  248. $exit = _saferun( $lh, qw{yum -y remove}, $svc2remove );
  249. return _cleanup("$exit") if $exit;
  250. print $lh "\n\nNow enabling postgresql-$ver2install on startup...\n";
  251. $exit = _saferun( $lh, qw{systemctl enable}, "postgresql-$ver2install" );
  252. return _cleanup("$exit") if $exit;
  253. # Update alternatives. Should be fine to use --auto, as no other alternatives will exist for the installed version.
  254. # Create alternatives for pg_ctl, etc. as those don't get made by the RPM.
  255. print $lh "\n\nUpdating alternatives to ensure the newly installed version is considered canonical...\n";
  256. my @normie_alts = qw{pg_ctl initdb pg_config pg_upgrade};
  257. my @manual_alts = qw{clusterdb createdb createuser dropdb droplang dropuser pg_basebackup pg_dump pg_dumpall pg_restore psql psql-reindexdb vaccumdb};
  258. foreach my $alt ( @normie_alts ) {
  259. $exit = _saferun( $lh, qw{update-alternatives --install}, "/usr/bin/$alt", "pgsql-$alt", "/usr/pgsql-$ver2install/bin/$alt", "50" );
  260. return _cleanup("$exit") if $exit;
  261. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-$alt" );
  262. return _cleanup("$exit") if $exit;
  263. }
  264. foreach my $alt ( @manual_alts ) {
  265. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-$alt" );
  266. return _cleanup("$exit") if $exit;
  267. $exit = _saferun( $lh, qw{update-alternatives --auto}, "pgsql-${alt}man" );
  268. return _cleanup("$exit") if $exit;
  269. }
  270. print $lh "\n\nWriting new .bash_profile for the 'postgres' user...\n";
  271. my $bash_profile = "[ -f /etc/profile ] && source /etc/profile
  272. PGDATA=/var/lib/pgsql/$ver2install/data
  273. export PGDATA
  274. [ -f /var/lib/pgsql/.pgsql_profile ] && source /var/lib/pgsql/.pgsql_profile
  275. export PATH=\$PATH:/usr/pgsql-$ver2install/bin\n";
  276. File::Slurper::write_text( '/var/lib/pgsql/.bash_profile', $bash_profile );
  277. if($ccs_installed) {
  278. File::Slurper::write_text( '/opt/cpanel-ccs/.bash_profile', $bash_profile );
  279. print $lh "\nRe-Enabling cpanel-ccs-calendarserver...\n\n";
  280. require Whostmgr::Services;
  281. Whostmgr::Services::enable('cpanel-ccs');
  282. }
  283. return _cleanup("0");
  284. }
  285. sub _saferun {
  286. my ( $lh, $prog, @args ) = @_;
  287. my $run_result = Cpanel::SafeRun::Object->new(
  288. 'program' => $prog,
  289. 'args' => [ @args ],
  290. 'stdout' => $lh,
  291. 'stderr' => $lh,
  292. );
  293. my $exit = $run_result->error_code() || 0;
  294. return $exit;
  295. }
  296. sub _cleanup {
  297. my ( $code ) = @_;
  298. # Do rollbacks
  299. foreach my $rb ( @ROLLBACKS ) {
  300. local $@;
  301. eval { $rb->(); };
  302. my $exit = $@ ? 255 : 0;
  303. if($exit) {
  304. $code = $exit;
  305. last;
  306. }
  307. }
  308. # Signal completion
  309. eval { symlink( $code, "$dir/INSTALL_EXIT_CODE" ); };
  310. unlink("$dir/INSTALL_IN_PROGRESS");
  311. return;
  312. }
  313. # Elegance??? Websocket??? Nah. EZ mode actibated
  314. sub get_latest_upgradelog_messages {
  315. my ( $args_hr ) = @_;
  316. my $child_exit;
  317. my $in_progress = -l "$dir/INSTALL_IN_PROGRESS";
  318. if(!$in_progress) {
  319. $child_exit = readlink("$dir/INSTALL_EXIT_CODE");
  320. }
  321. # XXX validate log arg? Don't want arbitrary file reads?
  322. # read from it using seek and tell to control
  323. open( my $rh, "<", $args_hr->{'log'} );
  324. seek( $rh, $args_hr->{'start'}, 0 ) if $args_hr->{'start'};
  325. my $content = '';
  326. while( my $line = <$rh> ) {
  327. $content .= $line;
  328. }
  329. my $pos = tell($rh);
  330. close($rh);
  331. return {
  332. 'in_progress' => $in_progress,
  333. 'child_exit' => $child_exit,
  334. 'next' => $pos,
  335. 'new_content' => $content,
  336. }
  337. }
  338. 1;