Skip to content

Commit

Permalink
Healthcheck endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Lewiscowles1986 committed Nov 3, 2019
1 parent 3dc4c58 commit 2eab4dc
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 3 deletions.
48 changes: 48 additions & 0 deletions app/Healthcheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
namespace App;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Config;
use ORM;

class Healthcheck {
const ERROR = 'ERROR';
const OK = 'OK';
const REDIS_SUCCESSFUL_PING = 'PONG';

public function index(ServerRequestInterface $request, ResponseInterface $response) {
$userlog = make_logger('healthcheck');

$services = [
'mysql' => self::ERROR,
'redis' => self::ERROR,
];

// Redis
try {
if(redis()->ping() == self::REDIS_SUCCESSFUL_PING) {
$services['redis'] = self::OK;
}
} catch(\Predis\Connection\ConnectionException $e) {
$userlog->info(
'Redis connection healthcheck failure'
);
}

// MySQL
try {
ORM::raw_execute('SELECT version();');
$services['mysql'] = self::OK;
} catch(\Exception $e) {
$userlog->info(
'MySQL connection healthcheck failure'
);
}

// Always
$response->getBody()->write(json_encode($services));
return $response;
}
}

10 changes: 8 additions & 2 deletions lib/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

const LOCAL_FALLBACK_REDIS = 'tcp://127.0.0.1:6379';

date_default_timezone_set('UTC');

if(getenv('ENV')) {
Expand Down Expand Up @@ -61,10 +63,14 @@ function random_user_code() {
return $code;
}

function get_redis_url() {
return $redisURL = getenv('REDIS_URL') ?? LOCAL_FALLBACK_REDIS;
}
function redis() {
static $client = false;
if(!$client)
$client = new Predis\Client('tcp://127.0.0.1:6379');
if(!$client) {
$client = new Predis\Client(get_redis_url());
}
return $client;
}

Expand Down
2 changes: 1 addition & 1 deletion public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
$route = new League\Route\RouteCollection($container);

$route->map('GET', '/', 'App\\Controller::index');

$route->map('GET', '/health', 'App\\Healthcheck::index');
$route->map('GET', '/api', 'App\\Controller::api_docs');
$route->map('GET', '/setup', 'App\\Controller::setup_docs');
$route->map('GET', '/faq', 'App\\Controller::faq');
Expand Down

0 comments on commit 2eab4dc

Please sign in to comment.