--- /dev/null
+<?php
+
+
+namespace App\Console\Commands;
+
+use App\Fluidbook\Farm;
+use App\Fluidbook\HostingLoadBalancer;
+use Cubist\Backpack\Console\Commands\CubistCommand;
+
+
+class FluidbookLoadbalancerPing extends CubistCommand
+{
+ protected $signature = 'fluidbook:loadbalancer:ping {--force}';
+ protected $description = 'Manage fluidbook loadbalanceer';
+
+ public function handle()
+ {
+ HostingLoadBalancer::ping(true, $this->option('force', false));
+ }
+}
namespace App\Fluidbook;
+use Cubist\Util\Files\Files;
+
class HostingLoadBalancer
{
protected static $_servers = [
- ['name' => 's1', 'host' => 's1.lb.hosting.fluidbook.com'],
- ['name' => 's2', 'host' => 's2.lb.hosting.fluidbook.com'],
+ ['name' => 's1', 'host' => 's1.lb.fluidbook.com'],
+ ['name' => 's2', 'host' => 's2.lb.fluidbook.com'],
];
+
+ protected static function _pingCache()
+ {
+ return Files::mkdir(storage_path('fluidbookhostingloadbalancer')) . '/pings';
+ }
+
+ public static function getServers()
+ {
+ return self::$_servers;
+ }
+
+ public static function ping($echo = true, $force = false)
+ {
+ $cache = self::_pingCache();
+ $servers = self::getServers();
+ $available = [];
+ $pings = [];
+ if (file_exists($cache)) {
+ $cached = json_decode(file_get_contents($cache));
+ if (is_countable($cached) && count($cached) === count($servers)) {
+ $pings = $cached;
+ }
+ }
+
+ foreach ($servers as $id => $server) {
+ if ($echo) {
+ echo $server['name'] . ' (' . $id . ') || ';
+ }
+ if (isset($pings[$id]) && !$pings[$id]) {
+ // If ping failed recently, we wait a bit before trying again.
+ if (!$force && rand(0, 9) != 5) {
+ if ($echo) {
+ echo 'Skipped, will try again soon' . "\n";
+ }
+ continue;
+ }
+ }
+ try {
+ $res = file_get_contents('https://' . $server['host'] . '/status');
+ $ok = $res == '1';
+ } catch (\Exception $e) {
+ $res = $e->getMessage();
+ $ok = false;
+ }
+
+ if ($echo) {
+ echo ($ok ? 'OK' : 'KO') . ' : ' . trim($res) . "\n";
+ }
+
+ $pings[$id] = $ok;
+ if ($ok) {
+ $available[] = $server['host'];
+ }
+ }
+ file_put_contents($cache, json_encode($pings));
+ file_put_contents(self::_serversCache(), json_encode($servers));
+ file_put_contents(public_path('lb.json'), json_encode($available));
+ }
+
+ protected static function _serversCache()
+ {
+ return Files::mkdir(storage_path('fluidbookhostingloadbalancer')) . '/servers';
+ }
}