4
0

health.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env php
  2. <?php
  3. declare(strict_types=1);
  4. if (php_sapi_name() !== 'cli') {
  5. echo 'Error: This script may only be invoked from command line!', PHP_EOL;
  6. die(3);
  7. }
  8. $options = getopt('', ['url::', 'connect_timeout::', 'timeout::']);
  9. $address = is_string($options['url'] ?? null) ? $options['url'] : 'http://localhost/api/';
  10. $ch = curl_init($address);
  11. if ($ch === false) {
  12. fwrite(STDERR, 'Error: Failed to initialize cURL!' . PHP_EOL);
  13. die(4);
  14. }
  15. curl_setopt_array($ch, [
  16. CURLOPT_CONNECTTIMEOUT => is_numeric($options['connect_timeout'] ?? null) ? (int)$options['connect_timeout'] : 3,
  17. CURLOPT_TIMEOUT => is_numeric($options['timeout'] ?? null) ? (int)$options['timeout'] : 5,
  18. CURLOPT_ACCEPT_ENCODING => '', //Enable all encodings
  19. CURLOPT_HTTPHEADER => [
  20. 'Connection: close',
  21. ],
  22. CURLOPT_RETURNTRANSFER => true,
  23. ]);
  24. $content = curl_exec($ch);
  25. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  26. if ($httpCode !== 200 || !is_string($content)) {
  27. $curlError = curl_error($ch);
  28. fwrite(STDERR, 'Error: Health check failed for ' . $address . ': ' .
  29. ($curlError !== '' ? $curlError : ('unexpected HTTP status ' . $httpCode)) . PHP_EOL);
  30. die(1);
  31. }
  32. $content = rtrim($content, "\n\r");
  33. if (!str_starts_with($content, '<!DOCTYPE html>') || !str_ends_with($content, '</html>') || !str_contains($content, '/scripts/api.js')) {
  34. fwrite(STDERR, 'Error: Health check failed for ' . $address .
  35. ': the response does not look like a FreshRSS page' .
  36. ' (check that the URL points to a working FreshRSS instance with the API enabled).' . PHP_EOL);
  37. die(2);
  38. }