> Markdown version of https://tuna.am/en/docs/monitors/examples/ping/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# Signals from scripts and CI

If tuna is installed on the machine, the easiest option is to wrap the job in [`tuna monitor exec`](https://tuna.am/en/docs/monitors/cli.md#monitor-exec): the CLI sends `start`, `finish` or `fail` itself and attaches the output. This page is for places without the CLI: a container, CI, application code, a server where nothing extra gets installed. A signal is a plain HTTP request, so anything can send it.

## URL and parameters

```text
https://monitor.tuna.am/<MONITOR_ID>

```

`MONITOR_ID` is the key of a [Job](https://tuna.am/en/docs/monitors/types/job.md) or [Heartbeat](https://tuna.am/en/docs/monitors/types/heartbeat.md) monitor. The dashboard shows the URL with the key in the monitor's usage examples. You can append any name after the key to make the URL readable in code: `https://monitor.tuna.am/<MONITOR_ID>/nightly-backup`.

| Parameter | What it does                                                                                                       |
| --------- | ------------------------------------------------------------------------------------------------------------------ |
| `state`   | Signal type: `ping` (default), `start`, `finish`, `fail`                                                           |
| `host`    | Where the signal came from, shown in the event history                                                             |
| `message` | A short message, shown in the event history                                                                        |
| `metric`  | A number in `name:value` format, shown in the event details. Can be repeated: `metric=rows:1520&metric=size_mb:84` |

Both GET and POST work. A POST body of up to 1 MB is stored with the event, which is how you send the tail of a log or a JSON result. The dashboard recognizes and highlights JSON, YAML and XML.

| Response | Meaning                                                                                   |
| -------- | ----------------------------------------------------------------------------------------- |
| `201`    | Signal accepted                                                                           |
| `404`    | No monitor with this key                                                                  |
| `403`    | The monitor doesn't accept signals: HTTP, TCP, DNS and ICMP monitors run their own checks |

Heartbeat only distinguishes `ping` and `fail`; it counts `start` and `finish` as `ping`.

> The request needs no authentication: anyone who knows the URL can send signals. Keep the key in an environment variable or in CI secrets, not in the repository code.

## Shell and curl

```bash
curl -fsS -m 10 --retry 5 -o /dev/null "https://monitor.tuna.am/$MONITOR_ID"

```

| Flag           | Why                                                                                                  |
| -------------- | ---------------------------------------------------------------------------------------------------- |
| `-f`           | Non-zero exit code when the server returns an error. Without it, curl treats even a `404` as success |
| `-s -S`        | No progress output, but errors are still printed, so cron mail only contains what broke              |
| `-m 10`        | Wait 10 seconds at most, so a stalled network doesn't hold up the job                                |
| `--retry 5`    | Retry on timeouts and on `408`, `429` and `5xx` responses                                            |
| `-o /dev/null` | Don't print the response body                                                                        |

A job that reports its start and result:

/scripts/backup-with-monitor.sh

```bash
#!/usr/bin/env bash
set -o pipefail

URL="https://monitor.tuna.am/$MONITOR_ID"
signal() { curl -fsS -m 10 --retry 5 -o /dev/null "$@" || true; }

signal "$URL?state=start"

{ pg_dump mydb | gzip > /backups/mydb.sql.gz; } 2> /tmp/backup.log
code=$?

if [ "$code" -eq 0 ]; then
  signal "$URL?state=finish"
else
  tail -c 100000 /tmp/backup.log | signal --data-binary @- "$URL?state=fail&message=exit+code+$code"
fi
exit "$code"

```

* `|| true` keeps the job running if monitoring is unreachable.
* `--data-binary @-` sends the tail of the log as the POST body; it shows up in the event details.
* `exit "$code"` returns the job's exit code, so cron and systemd see the failure too.
* Why `set -o pipefail` matters is explained under [Reliability](#reliability).

## Python

Standard library only:

job.py

```python
import os
import time
import urllib.error
import urllib.request

URL = "https://monitor.tuna.am/" + os.environ["MONITOR_ID"]


def signal(state="ping", body=None):
    for attempt in range(5):
        try:
            urllib.request.urlopen(f"{URL}?state={state}", data=body, timeout=10)
            return
        except urllib.error.HTTPError as e:
            if e.code < 500:
                return
        except OSError:
            pass
        time.sleep(2 ** attempt)


def run_job():
    ...  # your job


signal("start")
try:
    run_job()
except Exception as e:
    signal("fail", body=str(e).encode())
    raise
signal("finish")

```

With `data`, the request is sent as POST. `4xx` responses aren't retried: retrying won't make a `404` go away.

## Node.js

Node.js 18 or later:

job.mjs

```js
const URL = `https://monitor.tuna.am/${process.env.MONITOR_ID}`;

async function signal(state = "ping", body) {
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const res = await fetch(`${URL}?state=${state}`, {
        method: body ? "POST" : "GET",
        body,
        signal: AbortSignal.timeout(10_000),
      });
      if (res.status < 500) return;
    } catch {}
    await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
  }
}

async function runJob() {
  // your job
}

await signal("start");
try {
  await runJob();
  await signal("finish");
} catch (err) {
  await signal("fail", String(err));
  throw err;
}

```

## Go

main.go

```go
package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"
)

var client = &http.Client{Timeout: 10 * time.Second}

func signal(state, body string) {
	url := "https://monitor.tuna.am/" + os.Getenv("MONITOR_ID") + "?state=" + state
	for attempt := 0; attempt < 5; attempt++ {
		resp, err := client.Post(url, "text/plain", strings.NewReader(body))
		if err == nil {
			resp.Body.Close()
			if resp.StatusCode < 500 {
				return
			}
		}
		time.Sleep(time.Duration(1<<attempt) * time.Second)
	}
}

func runJob() error {
	// your job
	return nil
}

func main() {
	signal("start", "")
	if err := runJob(); err != nil {
		signal("fail", err.Error())
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	signal("finish", "")
}

```

## PowerShell and Windows Task Scheduler

The script works in Windows PowerShell 5.1 and PowerShell 7:

C:\scripts\backup-with-monitor.ps1

```powershell
$Url = "https://monitor.tuna.am/$env:MONITOR_ID"

function Send-Signal([string]$State = "ping", [string]$Body) {
    $params = @{ Uri = "${Url}?state=$State"; TimeoutSec = 10; UseBasicParsing = $true }
    if ($Body) { $params.Method = "Post"; $params.Body = $Body }
    try { Invoke-WebRequest @params | Out-Null } catch { Write-Warning "Monitor signal failed: $_" }
}

Send-Signal start
& C:\scripts\backup.cmd
$code = $LASTEXITCODE
if ($code -eq 0) { Send-Signal finish } else { Send-Signal fail "exit code $code" }
exit $code

```

Set the key as a system-wide variable so a task running as SYSTEM can see it, then create the task in Task Scheduler:

```powershell
setx MONITOR_ID "<MONITOR_ID>" /M
schtasks /Create /TN "Nightly backup" /SC DAILY /ST 03:00 /RU SYSTEM `
  /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\scripts\backup-with-monitor.ps1"

```

If tuna is installed on the server, you don't need the wrapper: `/TR "tuna monitor exec <MONITOR_ID> -- C:\scripts\backup.cmd"`.

## GitHub Actions

Store the key in the `MONITOR_ID` repository secret:

.github/workflows/nightly-report.yml

```yaml
name: nightly-report
on:
  schedule:
    - cron: "0 3 * * *"

jobs:
  report:
    runs-on: ubuntu-latest
    env:
      MONITOR_URL: https://monitor.tuna.am/${{ secrets.MONITOR_ID }}
    steps:
      - run: curl -fsS -m 10 --retry 5 -o /dev/null "$MONITOR_URL?state=start"
      - uses: actions/checkout@v4
      - run: ./scripts/report.sh
      - if: always()
        run: |
          state=fail
          [ "${{ job.status }}" = "success" ] && state=finish
          curl -fsS -m 10 --retry 5 -o /dev/null "$MONITOR_URL?state=$state&host=github-actions"

```

The last step always runs and picks `finish` or `fail` based on `job.status`. GitHub may delay scheduled runs under high load and, in public repositories, disables them after 60 days without activity. The monitor's grace period covers the delay, and a disabled schedule shows up as a job that didn't run.

## GitLab CI

Store the key in a masked `MONITOR_ID` CI/CD variable and set the schedule in Build → Pipeline schedules. The job image needs curl.

.gitlab-ci.yml

```yaml
nightly-report:
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
  before_script:
    - curl -fsS -m 10 --retry 5 -o /dev/null "https://monitor.tuna.am/$MONITOR_ID?state=start"
  script:
    - ./scripts/report.sh
  after_script:
    - |
      state=fail
      [ "$CI_JOB_STATUS" = "success" ] && state=finish
      curl -fsS -m 10 --retry 5 -o /dev/null "https://monitor.tuna.am/$MONITOR_ID?state=$state&host=gitlab-ci"

```

`after_script` runs even after `script` fails, and `CI_JOB_STATUS` tells it how the job ended.

## Kubernetes CronJob

Store the key in a secret:

```bash
kubectl create secret generic tuna-monitor --from-literal=nightly-backup=<MONITOR_ID>

```

The job image needs curl:

cronjob.yaml

```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-backup
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: backup
              image: registry.example.com/backup:1.4
              env:
                - name: MONITOR_ID
                  valueFrom:
                    secretKeyRef:
                      name: tuna-monitor
                      key: nightly-backup
              command: ["/bin/sh", "-c"]
              args:
                - |
                  URL="https://monitor.tuna.am/$MONITOR_ID"
                  curl -fsS -m 10 --retry 5 -o /dev/null "$URL?state=start&host=$HOSTNAME"
                  if /app/backup; then
                    curl -fsS -m 10 --retry 5 -o /dev/null "$URL?state=finish&host=$HOSTNAME"
                  else
                    code=$?
                    curl -fsS -m 10 --retry 5 -o /dev/null "$URL?state=fail&host=$HOSTNAME&message=exit+code+$code"
                    exit $code
                  fi

```

`backoffLimit: 0` turns off retries of a failed job; otherwise every attempt sends its own `start` and `fail`. Inside a pod, `HOSTNAME` is the pod name, so the history shows which run sent the signal. If the CronJob doesn't start at all (the cluster is down, the job is suspended, a schedule was missed), the monitor alerts you once the grace period runs out.

## Reliability

* Set a timeout on every request. Without one, a stalled connection holds up the job until the OS drops it. The server gives up on a signal after 10 seconds, so a 10-second timeout is enough.
* Retry 3–5 times with a pause. Retries are safe: a second event appears in the history, but you get no extra alerts.
* Don't let monitoring break the job. Swallow errors from sending the signal (`|| true`, `try`), and return the job's own exit code unchanged.
* Use `set -o pipefail` in scripts with pipelines. Without it, the exit code of `pg_dump mydb | gzip > backup.gz` comes from `gzip`: a failed `pg_dump` looks like success, and the monitor gets `finish` for an empty backup.
* Send `fail` explicitly. A `fail` alert arrives immediately, while an alert about a job that didn't run waits for the grace period to run out.
* The clock on the job's machine doesn't matter: the Tuna server measures duration by when `start` and `finish` arrive.
* One job on several servers needs several monitors. A signal from any server keeps a shared monitor Up, so a failure on one of them goes unnoticed.
