Watch your servers
Read your servers' use from code, and hear when one needs a look.
2 min read Updated
Read your servers' state and use from your own code, point out the ones that need a look, and have a webhook tell you as soon as one stops.
What you need
-
A token with
servers:read(View servers): it only reads. -
For the webhook, a token with
servers:read(View servers) andwebhooks:write(Manage webhooks), or the panel.
1. List your servers
GET /v1/servers gives each server's status: active while it runs, and
lastError when something went wrong.
curl "https://api.rabbitflare.com/v1/servers?status=active" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/servers?status=active", {
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data, pagination } = await res.json();
console.log(data, pagination.nextCursor); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
for await (const item of rf.servers.list({ status: "active" })) {
console.log(item);
} <?php
$ch = curl_init('https://api.rabbitflare.com/v1/servers?status=active');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
$answer = json_decode($body, true);
print_r($answer['data']);
echo $answer['pagination']['nextCursor'] ?? 'Last page', PHP_EOL; import os
import requests
response = requests.get(
"https://api.rabbitflare.com/v1/servers",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
params={
"status": "active",
},
timeout=120,
)
response.raise_for_status()
answer = response.json()
print(answer["data"], answer["pagination"]["nextCursor"]) 2. Read their graphs
GET /v1/servers/{serverId}/metrics gives a server's graphs over the last hour, 6 hours, day or week:
processor, memory and disk use in percent, load, and bandwidth. Each graph is a list of readings, the newest last. They're empty while the server isn't
running.
curl "https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/metrics?range=1h" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/metrics?range=1h", {
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.servers.metrics.get({
serverId: "3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d",
range: "1h",
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/metrics?range=1h');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.get(
"https://api.rabbitflare.com/v1/servers/3f6c1a2b-8d4e-4b7a-9c2d-1e5f7a8b9c0d/metrics",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
params={
"range": "1h",
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"])
Graphs are a heavy request: a token can make 20 a minute (see Rate limits).
Read one server at a time: over the limit, the answer is 429, with a Retry-After header that says how long to wait.
3. Hear when one needs a look
Rather than reading in a loop, add a webhook endpoint for the server events that mean something's wrong (see Webhooks):
| Event | What happened |
|---|---|
server.unreachable | Your own server couldn't be reached. |
server.missing | A server can no longer be found at its cloud. Support has been told. |
server.powered_off | A server was powered off, or was found powered off. |
server.suspended | A server and its sites were suspended because its billing stopped. |
server.provisioning_failed | A server couldn't be set up, or connecting your own server stopped. |
curl -X POST "https://api.rabbitflare.com/v1/webhooks/endpoints" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"url": "https://status.example.com/rabbitflare",
"description": "Server alerts",
"events": [
"server.unreachable",
"server.missing",
"server.powered_off",
"server.suspended",
"server.provisioning_failed"
]
}' const res = await fetch("https://api.rabbitflare.com/v1/webhooks/endpoints", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
"url": "https://status.example.com/rabbitflare",
"description": "Server alerts",
"events": [
"server.unreachable",
"server.missing",
"server.powered_off",
"server.suspended",
"server.provisioning_failed"
]
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.webhooks.endpoints.create({
url: "https://status.example.com/rabbitflare",
description: "Server alerts",
events: [
"server.unreachable",
"server.missing",
"server.powered_off",
"server.suspended",
"server.provisioning_failed",
],
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/webhooks/endpoints');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://status.example.com/rabbitflare',
'description' => 'Server alerts',
'events' => [
'server.unreachable',
'server.missing',
'server.powered_off',
'server.suspended',
'server.provisioning_failed',
],
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.post(
"https://api.rabbitflare.com/v1/webhooks/endpoints",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
json={
"url": "https://status.example.com/rabbitflare",
"description": "Server alerts",
"events": [
"server.unreachable",
"server.missing",
"server.powered_off",
"server.suspended",
"server.provisioning_failed",
],
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) Your endpoint then gets a signed call within seconds of each one (see Verify signatures). On a WordPress site, a small plugin can email you about them.
What can go wrong
| Code | Status | What it means | What to do |
|---|---|---|---|
rate_limited | 429 | Too many requests. scope says which limit: token, account, create, operation or network. | Wait for Retry-After seconds, then go on more slowly. |
server_unreachable | 502 | The server didn't answer, or didn't finish the request. | Check that the server is running, then try again in a minute. |
not_found | 404 | The resource doesn't exist, or isn't this account's. | Check the id. Ids of other accounts' resources answer the same way. |
The whole script
Steps 1 and 2 in JavaScript (Node.js 18 or later; save it as an .mjs file): each server's latest processor, memory and disk use, and a note
when one is at 90% processor or memory, or 85% disk. Run it from cron, or on a status screen.
// Prints each server's state and its latest processor, memory and disk use, and points out those that need a look.
const API = "https://api.rabbitflare.com/v1";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Sends a request and gives back its data. Over a rate limit (429) it waits as long as Retry-After says, then sends
// the same request again; any other error is thrown with the API's code.
async function rabbitflare(method, path, body, headers = {}) {
for (;;) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
...(body ? { "Content-Type": "application/json" } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 429) {
await sleep((Number(res.headers.get("Retry-After")) || 1) * 1000);
continue;
}
const answer = res.status === 204 ? null : await res.json().catch(() => null);
if (!res.ok) throw Object.assign(new Error(answer?.error?.message ?? `HTTP ${res.status}`), { code: answer?.error?.code });
return answer?.data ?? null;
}
}
const WARN_AT = { cpu: 90, memory: 90, disk: 85 }; // percent
const latest = (graph) => (graph.length ? graph[graph.length - 1].v : null);
const servers = await rabbitflare("GET", "/servers?limit=100");
for (const server of servers) {
if (server.status !== "active") {
console.log(`${server.name}: ${server.status}${server.lastError ? ` (${server.lastError})` : ""}`);
continue;
}
// Graphs are heavy requests: one server at a time, and rabbitflare() waits if the limit is reached.
const graphs = await rabbitflare("GET", `/servers/${server.id}/metrics?range=1h`);
const use = { cpu: latest(graphs.cpu), memory: latest(graphs.memory), disk: latest(graphs.disk) };
const high = Object.keys(WARN_AT).filter((k) => use[k] !== null && use[k] >= WARN_AT[k]);
const shown = Object.entries(use).map(([k, v]) => `${k} ${v === null ? "–" : `${Math.round(v)}%`}`);
console.log(`${server.name}: ${shown.join(", ")}${high.length ? ` (high: ${high.join(", ")})` : ""}`);
} Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.