Skip to content

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) and webhooks: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"

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"

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):

EventWhat 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"
  ]
}'

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

CodeStatusWhat it meansWhat 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.

JavaScript
// 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.

Contact support

Popular

API docs