Verified Commit 15128cce authored by Jakob Moser's avatar Jakob Moser
Browse files

Implement /status endpoint

parent 3bf16a48
Loading
Loading
Loading
Loading

api/v2/status.php

0 → 100644
+47 −0
Original line number Diff line number Diff line
<?php

$services = json_decode(file_get_contents("services.json"), true);

// The browser expects to see a Content-Type indication in the HTTP headers, so we
// send one. If we hadn't written this, the content type would be text/html.
header("Content-Type: application/json; charset=utf-8");

// A "curl multi handle". Can be filled with multiple "curl handles" (each corresponding to one HTTPS request)
// that can then be executed simultaneously.
$multi_handle = curl_multi_init();
$handles = [];

foreach($services as $service) {
  // Initialize a curl handle, i.e. prepare a single request. This will not yet make the request.
  $ch = curl_init("https://{$service['host']}");

  // We want curl to return the response (and not just echo it back to the requester). This is the
  // normal option you'd also expect when using e.g., Python's `requests` library.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // If the FS server is down on a network level, curl will wait until timeout before responding with a failure.
  // We set the timeout to 5s (maybe lower would be better), to still give a fast (albeit negative) response
  // when the FS server is down.
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  
  // Append the handle to the array of handles (we need it later to get the response code) and add
  // it to the multi handle (which we need to make the requests in batch).
  $handles[] = $ch;
  curl_multi_add_handle($multi_handle, $ch);
}

$active_requests = 0;
do {
  // Execute all requests simultaneously
  curl_multi_exec($multi_handle, $active_requests);
  // Wait until at least one request is finished
  curl_multi_select($multi_handle);
} while($active_requests > 0);  // Repeat until all requests are finished

// Get the response code from each request (accessed via the handles, and add it to the response JSON).
foreach($handles as $index => $handle) {
  $services[$index]["status"] = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
}

// Everything that is written using `echo` is sent to the client (i.e. the browser)
echo json_encode($services);