diff --git a/features/COVERAGE.md b/features/COVERAGE.md index 3993435a..20421a14 100644 --- a/features/COVERAGE.md +++ b/features/COVERAGE.md @@ -1,12 +1,12 @@ # site-command Behat coverage -Suite for `easyengine/site-command` (the `ee site` command and the html site type, plus `ee site php-compat` on php and wp sites). 19 features, 200 scenarios (240 with outlines expanded): main lane 214, `@wp` 15, `@le` 11. Run it the CI way (`.github/workflows/behat.yml`): the files are copied into a core checkout's `features/` and core's `vendor/bin/behat` runs from the core root as root. +Suite for `easyengine/site-command` (the `ee site` command and the html site type, plus `ee site php-compat` on php and wp sites). 19 features, 205 scenarios (245 with outlines expanded): main lane 219, `@wp` 15, `@le` 11. Run it the CI way (`.github/workflows/behat.yml`): the files are copied into a core checkout's `features/` and core's `vendor/bin/behat` runs from the core root as root. ## Tags | Tag | Scenarios | Meaning | |---|---|---| -| (none of the tags below) | 187 | Local only: `*.test` sites, no public DNS, no remote storage, no global restarts. This is the default safe run. The php-compat scenarios pull the scanner image from Docker Hub when it isn't present. | +| (none of the tags below) | 192 | Local only: `*.test` sites, no public DNS, no remote storage, no global restarts. This is the default safe run. The php-compat scenarios pull the scanner image from Docker Hub when it isn't present. | | `@known-bug` | 0 | Scenarios that expose open bugs are kept outside this suite and come back with their fixes. The CI lanes still exclude the tag. | | `@destructive` | 12 | Restarts the GLOBAL nginx-proxy (proxy cache) or runs `ssl-renew --all` (refuses to start when an enabled LE site that isn't the suite's exists). Every scenario leaves the proxy running. | | `@remote` | 10 | Uses the REAL rclone remote (`rclone-path` in config.yml). Touches only `/bh-site-command-*`: the rclone path is listed first and only listed suite directories are purged (per site before a scenario, all of them after the feature). | @@ -225,7 +225,7 @@ Every scan scenario needs core's `img-versions.json` to pin `easyengine/compat-s | Item | Status | Scenarios | |---|---|---| | `--format=json` on a wp and a php site: one-line summary, exit 0, no findings | covered (wp part @wp) | compat: The JSON summary of a WordPress site; The JSON summary of a php site | -| Table: verdict line first ("Not safe", or "No PHP problems found in …" scoped to what was checked; never "Safe to upgrade"), every error with file, line and sniff, static-analysis line last | covered ("Not safe" part @wp) | compat: The table starts with the verdict line...; The table of a php site without errors says what was checked, never "safe" | +| Table: the estimate first ("Estimating …", the estimate, "Checking …"), then the verdict line ("Not safe", or "No PHP problems found in …" scoped to what was checked; never "Safe to upgrade"), every error with file, line and sniff, static-analysis line last | covered ("Not safe" part @wp) | compat: The table says how long the check should take, then starts with the verdict line...; The table of a php site without errors says what was checked, never "safe" | | WordPress core gate: version.php read, too-old core is "Not safe", undeclared PHP (8.6) is "Can't confirm", JSON `wordpress` object | covered @wp | compat: A WordPress site's verdict covers what was checked, and core by its version | | "Can't confirm" verdict line from unchecked files | not covered | needs a file uid 33 can't read; the scanner side is in the dockerfiles fixture test | | "Can't confirm" from the php container a user compose file changes: a PHP config directory mounted over /usr/local/etc/php with a prepend in its conf.d, `group_add`, and a `user:` with another group | covered @wp | compat: PHP config, extra groups and another group a user compose file gives the php container make the verdict "can't confirm" | @@ -240,6 +240,11 @@ Every scan scenario needs core's `img-versions.json` to pin `easyengine/compat-s | html site refused, bad or missing `--php` (dispatcher and command checks), flags `--cancel` doesn't take | covered | compat: An html site is refused; A bad --php value, a missing one, or a flag --cancel does not take is rejected (outline) | | `busy` while a scan of the same site runs (json and table) | covered | compat: A second check while one of the same site runs reports busy | | `--estimate` while a check of the same site runs: `busy` with `estimate: true` | covered | compat: An estimate while a check of the same site runs is busy, and --cancel stops that check | +| Table check whose estimate fails: one line, then the check runs | covered | compat: A table check whose estimate fails says so and checks anyway | +| Table check whose estimate times out: its container is removed before the check starts | covered | compat: A table check whose estimate times out removes the estimate container, then checks | +| `ee site delete` during the estimate a table check runs first: the check reports `cancelled` | covered | compat: Deleting a site during the estimate a table check runs first stops the check | +| `--cancel` during the estimate a table check runs first: `cancelled`, no estimate container left | covered | compat: --cancel during the estimate a table check runs first stops the check | +| On a terminal: the self-updating elapsed-time line, cleared before the result | covered | compat: On a terminal a table check shows the time elapsed, and clears that line before the result | | `--timeout`: `tool_error`, exit 0, no temporary directory or container left | covered | compat: No temporary directory or container is left behind... | | Leftover temporary directory and stopped container of a killed run removed | covered | compat: A leftover of a killed check is removed by the next check | | `--cancel`: `not_running` with nothing running (json and table); `cancelled` for a running scan container, which is removed with the temporary directory, and a normal check afterwards; a stopped leftover removed; a missing site refused ("Could not find the site…") | covered | compat: --cancel with nothing running says so; --cancel stops the container of a check and removes its temporary directory; --cancel removes the stopped container and directory of a killed check; --cancel of a site that doesn't exist is refused | @@ -254,7 +259,7 @@ DB and container migrations under `migrations/` (core upgrade flow), the AcmePhp ## Coverage estimate -Counting the rows above as items: 144 items, 109 covered, 1 partial, 34 not covered (8 of them, marked "not covered yet", are open bugs whose scenarios come back with their fixes), i.e. about 76% of the inventory. Every user-facing subcommand and option of the html type has at least one scenario except `ssl-renew --force`, `clone --ssl/--wildcard` and a live `share`. +Counting the rows above as items: 149 items, 114 covered, 1 partial, 34 not covered (8 of them, marked "not covered yet", are open bugs whose scenarios come back with their fixes), i.e. about 76% of the inventory. Every user-facing subcommand and option of the html type has at least one scenario except `ssl-renew --force`, `clone --ssl/--wildcard` and a live `share`. ## Known bugs left out diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 65ccfb4e..b021dcc5 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -1833,6 +1833,14 @@ private static function purge_compat_leftovers() EE::launch( 'docker rm -f ' . escapeshellarg( $name ), false, true ); } } + // Estimate containers have no name: a killed run can leave one, even paused, which the next pause step would trip over. + $estimates = EE::launch( "docker ps -a --format '{{.ID}} {{.Label \"ee-php-compat-estimate-site\"}}' --filter label=ee-php-compat-estimate-site", false, true ); + foreach ( array_filter( explode( "\n", trim( $estimates->stdout ) ) ) as $line ) { + list( $id, $site ) = explode( ' ', "$line ", 2 ); + if ( 0 === strpos( trim( $site ), self::SITE_PREFIX ) ) { + EE::launch( 'docker rm -f ' . escapeshellarg( $id ), false, true ); + } + } // A directory whose container is still there may still be in use: keep it and say so. $ps = EE::launch( "docker ps -a --format '{{.Names}}'", false, true ); if ( 0 !== $ps->return_code ) { diff --git a/features/php-compat.feature b/features/php-compat.feature index 8019a321..aff23a78 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -9,10 +9,15 @@ Feature: Check the PHP compatibility of a site's code And the site "bh-site-command-180.test" exists, created with "--type=wp" And I write " wp-cli.yml' @@ -587,6 +601,104 @@ Feature: Check the PHP compatibility of a site's code And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-183.test" should not exist And the docker container "ee-php-compat-bh-site-command-183.test" should not exist + # Paused, the estimate a table check runs first can't end before the step after it. + Scenario: A table check whose estimate fails says so and checks anyway + Given the compat-scanner image is available + And the site "bh-site-command-184.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-184.test/app/htdocs/bulk" holds 5000 generated PHP files + When I start 'bin/ee site php-compat bh-site-command-184.test --php=8.4' in the background + And I wait up to 120 seconds until the command "docker pause $(docker ps -q --filter label=ee-php-compat-estimate-site=bh-site-command-184.test)" succeeds + And I run 'docker rm -f $(docker ps -aq --filter label=ee-php-compat-estimate-site=bh-site-command-184.test)' + Then the command should succeed + When I wait up to 900 seconds for the background command to finish + Then the command should succeed + And STDERR should match "/Estimating how long the check of bh-site-command-184\.test for PHP 8\.4 will take\. [^\n]+\nCouldn't estimate how long it will take \(the scanner [^\n]+\); checking anyway\.\nChecking bh-site-command-184\.test for PHP 8\.4\. [^\n]+\n/" + And STDOUT should match "/^(No PHP 8\.4|Can't confirm|Not safe) /" + And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-184.test" should not exist + And the docker container "ee-php-compat-bh-site-command-184.test" should not exist + + # Paused, the estimate never answers: the client gives up after ESTIMATE_TIMEOUT plus the process margin (3 minutes). + Scenario: A table check whose estimate times out removes the estimate container, then checks + Given the compat-scanner image is available + And the site "bh-site-command-184.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-184.test/app/htdocs/bulk" holds 5000 generated PHP files + When I start 'bin/ee site php-compat bh-site-command-184.test --php=8.4' in the background + And I wait up to 120 seconds until the command "docker pause $(docker ps -q --filter label=ee-php-compat-estimate-site=bh-site-command-184.test)" succeeds + And I wait up to 300 seconds until the command "docker inspect -f '{{.State.Running}}' ee-php-compat-bh-site-command-184.test | grep -qx true" succeeds + # The check runs alone: the timed-out estimate is gone before it starts. + And I run 'docker ps -aq --filter label=ee-php-compat-estimate-site=bh-site-command-184.test' + Then STDOUT should be empty + When I wait up to 900 seconds for the background command to finish + Then the command should succeed + And STDERR should match "/Estimating how long the check of bh-site-command-184\.test for PHP 8\.4 will take\. [^\n]+\nCouldn't estimate how long it will take \(timed out after 120 s\); checking anyway\.\nChecking bh-site-command-184\.test for PHP 8\.4\. [^\n]+\n/" + And STDOUT should match "/^(No PHP 8\.4|Can't confirm|Not safe) /" + And the docker container "ee-php-compat-bh-site-command-184.test" should not exist + + Scenario: Deleting a site during the estimate a table check runs first stops the check + Given the compat-scanner image is available + And the site "bh-site-command-191.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-191.test/app/htdocs/bulk" holds 5000 generated PHP files + When I start 'bin/ee site php-compat bh-site-command-191.test --php=8.4' in the background + And I wait up to 120 seconds until the command "docker pause $(docker ps -q --filter label=ee-php-compat-estimate-site=bh-site-command-191.test)" succeeds + And I run 'bin/ee site delete bh-site-command-191.test --yes' + Then the command should succeed + And the site "bh-site-command-191.test" should not exist + When I run 'docker ps -aq --filter label=ee-php-compat-estimate-site=bh-site-command-191.test' + Then STDOUT should be empty + When I wait up to 120 seconds for the background command to finish + Then the command should succeed + And STDOUT should be exactly: + """ + The check of bh-site-command-191.test for PHP 8.4 was cancelled. + """ + And STDERR should contain "Estimating how long the check of bh-site-command-191.test for PHP 8.4 will take." + And STDERR should not contain "Checking" + And the docker container "ee-php-compat-bh-site-command-191.test" should not exist + And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-191.test" should not exist + + Scenario: --cancel during the estimate a table check runs first stops the check + Given the compat-scanner image is available + And the site "bh-site-command-183.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-183.test/app/htdocs/bulk" holds 5000 generated PHP files + When I start 'bin/ee site php-compat bh-site-command-183.test --php=8.4' in the background + And I wait up to 120 seconds until the command "docker pause $(docker ps -q --filter label=ee-php-compat-estimate-site=bh-site-command-183.test)" succeeds + # The estimate runs under the check's site lock: a second check is busy before it prints anything. + And I run 'bin/ee site php-compat bh-site-command-183.test --php=8.4' + Then the command should succeed + And STDOUT should be exactly: + """ + A check or an estimate of bh-site-command-183.test is already running. + """ + And STDERR should not contain "Estimating" + When I run 'bin/ee site php-compat bh-site-command-183.test --cancel' + Then the command should succeed + And STDOUT should be exactly: + """ + Cancelled the check of bh-site-command-183.test. + """ + When I wait up to 120 seconds for the background command to finish + Then the command should succeed + And STDOUT should be exactly: + """ + The check of bh-site-command-183.test for PHP 8.4 was cancelled. + """ + And STDERR should contain "Estimating how long the check of bh-site-command-183.test for PHP 8.4 will take." + And STDERR should not contain "Checking" + When I run 'docker ps -aq --filter label=ee-php-compat-estimate-site=bh-site-command-183.test' + Then STDOUT should be empty + And the docker container "ee-php-compat-bh-site-command-183.test" should not exist + + Scenario: On a terminal a table check shows the time elapsed, and clears that line before the result + Given the compat-scanner image is available + And the site "bh-site-command-183.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-183.test/app/htdocs/bulk" holds 5000 generated PHP files + When I run 'script -qec "bin/ee site php-compat bh-site-command-183.test --php=8.4" /dev/null > {TMP}/tty.out' + Then the command should succeed + # cat -v keeps the escape sequences, which the STDOUT steps strip. + When I run 'cat -v {TMP}/tty.out' + And STDOUT should match "/\^MChecking: \d+s elapsed of about \d+ (seconds?|minutes?) \(\d+ to \d+\)\^\[\[K/" + And STDOUT should match "/\^\[\[K\^M\^\[\[K(\^M)?\n(No PHP 8\.4|Can't confirm|Not safe) /" + Scenario: No temporary directory or container is left behind, also when the check times out Given the compat-scanner image is available And the site "bh-site-command-183.test" exists, created with "--type=php" @@ -598,6 +710,13 @@ Feature: Check the PHP compatibility of a site's code And the JSON field "detail" in STDOUT should contain "timed out after 1 s" And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-183.test" should not exist And the docker container "ee-php-compat-bh-site-command-183.test" should not exist + # In the table format the estimate runs first and doesn't count against --timeout. + When I run 'bin/ee site php-compat bh-site-command-183.test --php=8.4 --timeout=1' + Then the command should succeed + And STDERR should match "/It should take about [^\n]+\nChecking bh-site-command-183\.test for PHP 8\.4\. /" + And STDOUT should match "/^The check of bh-site-command-183\.test for PHP 8\.4 didn't finish: timed out after 1 s/" + And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-183.test" should not exist + And the docker container "ee-php-compat-bh-site-command-183.test" should not exist Scenario: A leftover of a killed check is removed by the next check Given the compat-scanner image is available diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 87839117..9803e2be 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -13,7 +13,8 @@ /** * `ee site php-compat`: runs the compat-scanner image against a site's code and prints its verdict or estimate. * - * Output goes through `echo` only: EE::exec(), EE::launch() and EE::log() would put findings into ee.log. + * Results go to stdout through `echo`, progress to stderr through fwrite(); never EE::exec(), EE::launch() or EE::log(), which would put + * findings into ee.log. */ class Site_PHP_Compat { @@ -35,6 +36,8 @@ class Site_PHP_Compat { const CONTRACT = '2'; // How long --cancel and delete wait for a stopped check to let go of the site lock; a request twice as old has no --cancel waiting. const CANCEL_WAIT = 60; + // `docker rm -f` of a container that is gone, or that another process (a --cancel, a check's cleanup) is removing right now. + const RM_GONE = '/no such container|removal of container .* is already in progress/i'; const STDOUT_MAX = 1048576; const STDERR_MAX = 65536; const REPORT_MAX = 134217728; @@ -287,6 +290,15 @@ class Site_PHP_Compat { /** @var bool Set during cleanup(), so a second signal can't interrupt it. */ protected $cleaning = false; + /** @var bool Whether a person reads the output (table format): they see the steps of a long run. */ + protected $announce = false; + + /** @var float|null When the scan container started, while a terminal shows its progress line. */ + protected $progress_since; + + /** @var string|null How long the implicit estimate says the check takes, for the progress line. */ + protected $expected; + /** @var bool Whether the shutdown cleanup is registered. */ private $cleanup_registered = false; @@ -365,7 +377,8 @@ public function run( $site_data, array $assoc_args, $dispatch = null ) { } else { EE::debug( sprintf( 'php-compat: site %s, PHP %s, %s', $this->site, $this->target, $this->estimate ? 'estimate' : "scan, timeout $timeout s" ) ); } - $started = microtime( true ); + $started = microtime( true ); + $this->announce = 'table' === $format; try { if ( $this->cancel ) { @@ -487,7 +500,13 @@ protected function run_scan( $site_data, $timeout, $output ) { return $started; } list( $image, $code ) = $started; - $out = $this->make_temp_dir(); + if ( $this->announce ) { + $early = $this->estimate_first( $site_data, $image, $code ); + if ( null !== $early ) { + return $early; + } + } + $out = $this->make_temp_dir(); if ( null === $out ) { return $this->doc( 'tool_error', 'could not create the temporary directory' ); } @@ -501,7 +520,12 @@ protected function run_scan( $site_data, $timeout, $output ) { // From here until cleanup() confirms it is gone, /out may be in use by this container. $name = $this->container_name(); $this->active_container = $name; + // phpcs:ignore PHPCompatibility.PHP.NewFunctions.stream_isattyFound -- PHP 7.2+; EE needs 7.4. + $this->progress_since = $this->announce && stream_isatty( STDERR ) ? microtime( true ) : null; $run = $this->docker( $this->docker_run_args( 'scan', $image, $site_data, $code, $out, $timeout ), $timeout + self::PROCESS_MARGIN, true ); + if ( $this->announce ) { + self::say( '' ); + } if ( $run['timed_out'] ) { return $this->doc( 'tool_error', "timed out after $timeout s" . self::TIMEOUT_HINT ); } @@ -635,12 +659,68 @@ protected function run_estimate( $site_data ) { if ( $this->cancel_requested() ) { return $this->cancelled(); } + + return $this->estimate( $site_data, $image, $code ); + } + + /** + * Before a table check: say how long it should take, so a long check doesn't look stuck. Under the check's own site lock. + * + * @param object $site_data Site record. + * @param string $image Scanner image with its tag. + * @param string $code Real path of the site's code. + * + * @return array|null The no_code_found or cancelled result, or null to go on with the check. + */ + protected function estimate_first( $site_data, $image, $code ) { + $site = $this->site; + $target = $this->target; + self::say( "Estimating how long the check of $site for PHP $target will take. This can take a minute or two." ); + $started = microtime( true ); + $result = $this->estimate( $site_data, $image, $code ); + // A cancelled estimate reads as a failed one. + if ( $this->cancel_requested() ) { + return $this->cancelled(); + } + $doc = $result['doc']; + $this->log_result( $doc, microtime( true ) - $started, true ); + // The estimate lists the files as the check does. + if ( 'no_code_found' === $doc['status'] ) { + return $result; + } + // With only this check's own entries to report there is nothing to time. + if ( 'ok' === $doc['status'] && $doc['php_files'] > 0 ) { + $this->expected = self::duration( $doc['estimated_seconds'], $doc['estimated_seconds_low'], $doc['estimated_seconds_high'] ); + $files = self::count_of( $doc['php_files'], 'PHP file', true ); + $components = self::count_of( $doc['components'], 'component', true ); + self::say( "It should take {$this->expected}: $files, " . self::size( $doc['php_bytes'] ) . ", $components." ); + } elseif ( 'ok' !== $doc['status'] ) { + self::say( "Couldn't estimate how long it will take (" . self::clean( $doc['detail'] ) . '); checking anyway.' ); + } + self::say( "Checking $site for PHP $target. To stop it, run: ee site php-compat $site --cancel" ); + + return null; + } + + /** + * Run the estimate container on what start() prepared. + * + * @param object $site_data Site record. + * @param string $image Scanner image with its tag. + * @param string $code Real path of the site's code. + * + * @return array 'doc' (estimate to print) and 'report' (always null). + */ + protected function estimate( $site_data, $image, $code ) { // The client ignores signals (no --sig-proxy) and a timeout stops only the client: cleanup() removes the container by label. $this->estimate_label = bin2hex( random_bytes( 8 ) ); $run = $this->docker( $this->docker_run_args( 'estimate', $image, $site_data, $code ), self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN, true ); if ( null !== $run['code'] ) { // Ended on its own: --rm removed it. $this->estimate_label = null; + } elseif ( ! $this->cancel_requested() ) { + // A check may follow: it shouldn't share the CPU with an estimate still running. A cancel leaves this to cleanup(). + $this->remove_estimate_container(); } if ( $run['timed_out'] ) { return $this->doc( 'tool_error', 'timed out after ' . self::ESTIMATE_TIMEOUT . ' s' ); @@ -2168,8 +2248,7 @@ protected function stop_containers() { foreach ( preg_split( '/\n/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) as $line ) { list( $id, $state ) = explode( ' ', "$line ", 2 ); $rm = $this->docker( [ 'docker', 'rm', '-f', $id ], 60 ); - // --rm may have removed it in the meantime. - if ( 0 !== $rm['code'] && ! preg_match( '/no such container/i', $rm['stderr'] ) ) { + if ( 0 !== $rm['code'] && ! preg_match( self::RM_GONE, $rm['stderr'] ) ) { return 'could not remove the estimate container ' . self::clean( $id ); } $running = $running || 'running' === trim( $state ); @@ -2661,6 +2740,9 @@ protected function ensure_image( $image ) { $mismatch = "the scanner image doesn't match this EasyEngine; run `docker pull $image` and try again"; $timeout = null === $contract ? self::PULL_TIMEOUT : self::REPULL_TIMEOUT; EE::debug( "Pulling $image." ); + if ( $this->announce ) { + self::say( 'Getting the ' . self::IMAGE . ' image. This can take a few minutes.' ); + } $pull = $this->docker( [ 'docker', 'pull', '--quiet', $image ], $timeout, true ); if ( 0 !== $pull['code'] || $pull['timed_out'] ) { $why = $pull['timed_out'] ? "timed out after $timeout s" : self::first_line( $pull['stderr'] ); @@ -2940,6 +3022,8 @@ protected function temp_base() { protected function docker( array $argv, $timeout, $bounded = false ) { EE::debug( 'COMMAND: ' . implode( ' ', array_map( 'escapeshellarg', $argv ) ) ); $run = $this->run_process( $argv, $timeout, $bounded ); + // Before the debug line, which would land on the progress line. + $this->end_progress(); EE::debug( 'RETURN CODE: ' . var_export( $run['code'], true ) ); return $run; @@ -2993,6 +3077,9 @@ function ( $type, $buffer ) use ( &$result ) { return $result; } + if ( null !== $this->progress_since && 0 === $tick % 50 ) { + $this->show_progress(); + } $process->checkTimeout(); if ( $bounded && $result['overflow'] ) { $process->stop( 0 ); @@ -3014,6 +3101,43 @@ function ( $type, $buffer ) use ( &$result ) { return $result; } + /** + * Rewrite the terminal's last line with the time the check has run, and how long it should take. + */ + protected function show_progress() { + $line = 'Checking: ' . self::clock( microtime( true ) - $this->progress_since ) . ' elapsed'; + if ( null !== $this->expected ) { + $line .= " of {$this->expected}"; + } + self::say( "\r$line\033[K", '' ); + } + + /** + * @return string "45s", "12m 05s", "1h 02m 05s". + */ + protected static function clock( $seconds ) { + $s = (int) $seconds; + if ( $s < 60 ) { + return "{$s}s"; + } + if ( $s < 3600 ) { + return sprintf( '%dm %02ds', intdiv( $s, 60 ), $s % 60 ); + } + + return sprintf( '%dh %02dm %02ds', intdiv( $s, 3600 ), intdiv( $s, 60 ) % 60, $s % 60 ); + } + + /** + * Print a progress line on stderr, so stdout holds only the result. Not echo: PHP stops at an echo to a terminal that is gone, + * and a check outlives its terminal. + * + * @param string $text Text. + * @param string $end Line end. + */ + protected static function say( $text, $end = "\n" ) { + @fwrite( STDERR, $text . $end ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- nobody may read it any more. + } + /** * @param string $stdout Container stdout. * @@ -4170,17 +4294,22 @@ function ( $char ) { /** * Command, target, duration, verdict and counts only; findings and details never reach ee.log. * - * @param array $doc Printed document. - * @param float $elapsed Seconds. + * @param array $doc Printed document. + * @param float $elapsed Seconds. + * @param bool $estimate The estimate a table check runs first. */ - protected function log_result( array $doc, $elapsed ) { + protected function log_result( array $doc, $elapsed, $estimate = false ) { if ( $this->cancel ) { EE::debug( sprintf( 'php-compat cancel of %s: status %s, %d s.', $this->site, $doc['status'], (int) round( $elapsed ) ) ); return; } - $counts = ''; - $keys = $this->estimate ? [ 'php_files', 'php_bytes', 'components', 'estimated_seconds' ] : [ 'errors', 'warnings', 'files_checked', 'files_not_checked', 'components_with_errors' ]; + $estimate = $estimate || $this->estimate; + $counts = ''; + $keys = [ 'errors', 'warnings', 'files_checked', 'files_not_checked', 'components_with_errors' ]; + if ( $estimate ) { + $keys = [ 'php_files', 'php_bytes', 'components', 'estimated_seconds' ]; + } foreach ( $keys as $key ) { if ( isset( $doc[ $key ] ) && is_int( $doc[ $key ] ) ) { $counts .= ", $key {$doc[ $key ]}"; @@ -4189,7 +4318,7 @@ protected function log_result( array $doc, $elapsed ) { EE::debug( sprintf( 'php-compat %s of %s for PHP %s: status %s, safe_to_upgrade %s%s, %d s.', - $this->estimate ? 'estimate' : 'scan', + $estimate ? 'estimate' : 'scan', $this->site, $this->target, $doc['status'], @@ -4333,11 +4462,43 @@ function () use ( $files ) { return null; } + /** + * Remove this run's estimate container, which a timeout or a cancel leaves running. The label stays until that worked, so a + * removal a signal or a cancel cuts short is retried by cleanup(). + */ + protected function remove_estimate_container() { + if ( null === $this->estimate_label ) { + return; + } + $ids = $this->docker( [ 'docker', 'ps', '-aq', '--filter', 'label=ee-php-compat-estimate=' . $this->estimate_label ], 60 ); + if ( 0 !== $ids['code'] ) { + return; + } + foreach ( preg_split( '/\s+/', trim( $ids['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) as $id ) { + $rm = $this->docker( [ 'docker', 'rm', '-f', $id ], 60 ); + if ( 0 !== $rm['code'] && ! preg_match( self::RM_GONE, $rm['stderr'] ) ) { + return; + } + } + $this->estimate_label = null; + } + + /** + * Clear the progress line, so what follows starts on an empty line. + */ + public function end_progress() { + if ( null !== $this->progress_since ) { + $this->progress_since = null; + self::say( "\r\033[K", '' ); + } + } + /** * Remove a scan container that may still exist, then, once it is gone, the temporary directory; release the lock. Safe to call twice. */ public function cleanup() { $this->cleaning = true; + $this->end_progress(); if ( null !== $this->active_container ) { $name = $this->active_container; $this->active_container = null; @@ -4347,14 +4508,7 @@ public function cleanup() { $this->temp_dir = null; } } - if ( null !== $this->estimate_label ) { - $label = 'label=ee-php-compat-estimate=' . $this->estimate_label; - $this->estimate_label = null; - $ids = $this->docker( [ 'docker', 'ps', '-aq', '--filter', $label ], 60 ); - foreach ( preg_split( '/\s+/', trim( $ids['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) as $id ) { - $this->docker( [ 'docker', 'rm', '-f', $id ], 60 ); - } - } + $this->remove_estimate_container(); if ( null !== $this->temp_dir ) { $dir = $this->temp_dir; $this->temp_dir = null; diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 9eab50ad..1a9ab13d 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3337,6 +3337,8 @@ protected function delete_stopped( $site ) { * * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: all of the site's app/ and the directories its php container mounts, except WordPress core (judged by its version), old releases nginx doesn't serve (a current/ release link) and backup-named files (such as .bak and .orig). It ends with a verdict: no problems found in what was checked (no errors, nothing left unchecked, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (something couldn't be checked, such as a file the scanner couldn't read, another WordPress install whose version doesn't support the target, phar archives when the site's code names a phar, a php container mount this check can't reproduce or PHP settings it can't follow; or WordPress hasn't declared support for the target). A phar archive no scanned code names is listed under `ignored` and doesn't change the verdict. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the site's php container runs an EasyEngine image and the target is PHP 7.0 or newer: its config then loads the redis extension, so nginx-helper doesn't load Predis. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so, only when the PHP the site runs now is known and the target isn't below it; otherwise the result is can't confirm). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * + * With the default table format, the command first estimates how long the check will take and prints that, then shows the time elapsed while the check runs (on a terminal), then the result. These progress lines go to stderr and the result to stdout. --format=json prints only the JSON result, with no estimate. + * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * * ## OPTIONS @@ -3378,7 +3380,7 @@ protected function delete_stopped( $site ) { * : Also write the full report, with every error and warning, as JSON to this absolute path: the JSON summary's fields (the same verdict) plus every component and its findings. A finding left out of the verdict stays in its component, marked `"ignored": true`, and its file is listed under `ignored`. The file is owned by root with mode 0600 and replaces an existing one. It is written only when the check finishes with a result (status ok); otherwise an existing file is left as it was. Its directory must exist and be writable, and can't be in /dev, /proc or /sys or be writable by everyone without the sticky bit (/tmp is fine). Not with --estimate. * * [--timeout=] - * : Time limit for the scan itself, in seconds. A scan that hits it reports tool_error and no verdict. Pulling the scanner image on first use isn't counted. Default: 14400 (4 hours). Not with --estimate. + * : Time limit for the scan itself, in seconds. A scan that hits it reports tool_error and no verdict. Pulling the scanner image on first use and the estimate the table format runs first aren't counted. Default: 14400 (4 hours). Not with --estimate. * * [--cancel] * : Stop the site's running check or estimate, then exit. Prints cancelled when one was stopped (it then reports cancelled, with no verdict and no --output file) and not_running when none was running. Waits up to 60 seconds for the stopped check to clean up. Not with --php, --estimate, --output or --timeout. @@ -3406,6 +3408,7 @@ public function php_compat( $args, $assoc_args ) { // A check changes nothing to roll back: on a signal, say what happens and exit; the shutdown handler stops the check. if ( function_exists( 'pcntl_signal' ) ) { $stop = function () { + $this->php_compat_check->end_progress(); \EE::warning( 'Stopping the check: removing its container and temporary files.' ); exit( 1 ); };