Jobs: dispatch, poll, stream
Nội dung này hiện chưa có sẵn bằng ngôn ngữ của bạn.
Every change on a server, and many live reads, runs as a job: a named, whitelisted
action (site.create, stack.deploy, ssl.issue, …) that the control plane sends to
the server’s agent over its WebSocket. The agent runs it in its native engine and
reports back. You never send a shell command. You pick a job kind, and the control plane
builds the exact argv from your fields.
Dispatch
Section titled “Dispatch”| MCP | REST | |
|---|---|---|
| Body schema of a kind | jobs_schema {type: "site.create"} | GET /v1/api/job-kinds/site.create |
| Dispatch | jobs_create {id: <server UUID>, body: {type: "site.create", …fields}} | POST /v1/servers/{id}/jobs with the body |
| Status | jobs_get {id: <job_id>} | GET /v1/jobs/{job_id} |
| Recent jobs on a server | jobs_list {id: <server UUID>} | GET /v1/servers/{id}/jobs?limit=10 |
| Output (persisted lines) | jobs_output {id: <job_id>, query: {tail: "200"}} | GET /v1/jobs/{job_id}/output?tail=200 |
| Live output | not available | GET /v1/jobs/{job_id}/stream (server-sent events) |
The body is flat: type plus that kind’s fields at the top level. Unknown keys are
rejected with 400 bad_request, along with a did-you-mean hint and accepted_keys.
A successful dispatch answers 202:
{ "job_id": "8b1d…", "status": "running", "stream_url": "/v1/jobs/8b1d…/stream" }Before the job is accepted, the control plane checks the token (level, scope and server
allowlist for this kind), the owner’s team role, and the plan (tier_required). It also
validates every field. Most errors therefore arrive synchronously on dispatch, before
anything reaches the box.
Wait for the result in one call
Section titled “Wait for the result in one call”Add wait (1–90 seconds) to hold the answer until the job ends. Over MCP it is an
argument of jobs_create. Over REST it is the query parameter ?wait=N:
jobs_create {id: <server UUID>, wait: 60, body: {type: "wp.content", domain: "example.com", method: "GET", path: "/wp/v2/posts"}}POST /v1/servers/{id}/jobs?wait=60A job that finishes in time answers 200 with its final state and the tail of its
output (the same lines, caps and masking as jobs_output; ?tail= 1–500, default 100):
{ "job_id": "8b1d…", "status": "completed", "exitCode": 0, "errorMessage": null, "output": { "lines": [ { "stream": "stdout", "seq": 1, "line": "{\"ok\":true}" } ], "truncated": false } }A failed job with a known cause also carries the failure block. That makes short
actions and content reads such as wp.content, php.switch or cron.add a single call
instead of dispatch, poll and read output.
- Still running after N seconds: the usual
202 {job_id, status, stream_url}pluswaited: N. The job keeps running; continue withjobs_getas below. - Offline server: never waited on. You get the usual
202withstatus: "queued"(or409 server_offlinefor kinds that are never queued). - Cap: 90 s, because the Cloudflare edge ends a request at 100 s. Larger values are
treated as 90. Use
waitfor jobs that usually take seconds, and poll for long ones (provisioning, image builds). - Limit: a token holds at most 5 waiting requests at once. The 6th answers
429 wait_limitwithRetry-After. A value that isn’t a number answers400 invalid_wait.
Statuses
Section titled “Statuses”| Status | Meaning | Terminal? |
|---|---|---|
pending | Accepted, being sent to the agent | no |
queued | The agent is offline; the job waits for it to reconnect | no |
running | The agent is running it | no |
completed | Finished with exit code 0 | yes |
failed | Finished with a non-zero exit code or an error (errorMessage) | yes |
timeout | Ran past its time budget (default 600 s; long kinds such as provisioning get more) | yes |
cancelled | Stopped before it finished | yes |
jobs_get returns:
{ "job": { "id": "…", "type": "site.create", "status": "completed", "exitCode": 0, "errorMessage": null, "dispatchedAt": "…", "completedAt": "…", "durationMs": 41250 } }When a job ends failed or timeout and the end of its log matches a known cause, both
jobs_get and jobs_output add a failure block with a stable code, a hint that
names the next step (usually a tool), and sometimes a docs link:
"failure": { "code": "apt_locked", "hint": "Another package operation (usually unattended upgrades) holds the apt/dpkg lock. Wait a few minutes and run the same job again; do not loop. …" }Codes: apt_locked, acme_rate_limited, dns_not_pointing, acme_unreachable, disk_full, nginx_config_invalid, out_of_memory, image_not_found, registry_auth_failed, registry_rate_limited, port_in_use, restore_snapshot_failed, restore_rolled_back, restore_rollback_failed, cron_not_found, agent_outdated. Follow the hint
instead of retrying blindly; a job with no failure block failed for a reason MZPanel does
not recognise, so read jobs_output.
It does not return the job’s output; read that with jobs_output (below). To confirm
the effect, re-read the state the job changed. Use servers_inventory_refresh {id, kind} or servers_sites_refresh {id},
wait a few seconds, then call servers_inventory {id, kind} / servers_sites {id}. If
you need a result inline, prefer a synchronous read: the core tools (ssl_list,
db_list, docker_ps, logs_tail, site_get, …) or a cached inventory kind.
Polling cadence
Section titled “Polling cadence”Poll jobs_get every 2–5 seconds and stop at a terminal status (or dispatch with
wait to skip polling for short jobs, see above). Most jobs finish in
seconds. Site creation, stack deploys and image pulls take one to several minutes, and
server provisioning can take up to 30 minutes. Every poll counts against the token’s
rate limit.
Offline servers: the durable queue
Section titled “Offline servers: the durable queue”If the server’s agent is disconnected when you dispatch:
- Durable by default. The job is stored as
queuedand runs automatically when the agent reconnects, in the order it was created. A queued job that has waited more than 24 hours is failed witherrorMessage: "expired_offline"instead of running late. - Opt out with
?durable=0. Add it to the dispatch URL (over MCP, passquery: {durable: "0"}) when “run it now or not at all” is what you want. The row then endsexpired_offlineon the next reconnect rather than running hours later. - Never queued: kinds that carry secrets or environment values, such as env writes or
app.db-attach, which prints a new password. They answer409 server_offlinestraight away. Retry once the server is online.
Check online in servers_list before dispatching anything that must run now.
Reading the output
Section titled “Reading the output”jobs_output {id: <job_id>} (REST GET /v1/jobs/{job_id}/output) returns the lines the
job has logged so far, oldest first, while it runs and after it ends:
{ "jobId": "8b1d…", "status": "failed", "exitCode": 1, "lines": [ { "stream": "stderr", "seq": 41, "line": "nginx: [emerg] unknown directive" } ], "totalLines": 42, "truncated": true }tail(query, 1–500, default 100) picks how many of the last lines to return.- Lines longer than 4 KB are cut, and the whole result is capped at 64 KB, keeping the
newest lines.
truncated: truemeans some lines were cut or left out; comparetotalLineswithlines. - Same visibility as
jobs_get: a job you cannot see answers404 not_found. - Kinds that print a credential (
app.db-attach,db.user-create,db.user-passwd,pg.db-create,mongo.db-create,site.wp-admin-passwd,pgadmin.creds,db.pma) never store their output, so theirlinesare always empty. Where the kind takes apassfield, set your own password when you need to know it; over REST you can also read the result from the live stream. - Secrets that tools print in plain text (private keys, passwords in URLs,
Bearertokens,PASSWORD=…-style pairs, cloud and git tokens) are stored as[REDACTED]. The live stream shows them unmasked while the job runs. - The generated passwords in the result of
site.create(database and wp-admin) andsite.clone(database) are stored as[REDACTED]as well. Read them from the live stream, or set a new wp-admin password afterwards withsite.wp-admin-passwd. - Output is kept for 30 days. For an older job,
jobs_getstill answers butlinesis empty.
Read it when a job ends failed or timeout: the last stderr lines usually name the cause.
Live output (REST only)
Section titled “Live output (REST only)”curl -N -s https://api.mzpanel.com/v1/jobs/$JOB/stream -H "Authorization: Bearer $TOKEN"The stream first replays the lines already logged, then sends live frames:
event: logdata: {"stream":"stdout","seq":12,"line":"Issuing certificate for example.com"}
event: donedata: {"exit_code":0,"duration_ms":18240}done may carry "error". Kinds that print a credential stream their output to the
caller but never store it, so a later replay shows nothing for them. MCP has no stream
tool: poll jobs_get, then read jobs_output.
Safe retries
Section titled “Safe retries”There is no generic cancel, and without an idempotency key each jobs_create is a
new job.
Idempotency keys. Send an Idempotency-Key header (1–128 printable characters; over
MCP the idempotencyKey argument of jobs_create) with any API-token
POST/PUT/PATCH/DELETE. When you repeat the request with the same key, method, path,
query and body within 24 hours, you get the first 2xx answer back, with the header
Idempotent-Replayed: true, and nothing is dispatched again. Use a fresh key (a UUID) for
each new action, and reuse it only for retries of that action.
422 idempotency_key_reused: the key was already used for a different request.409 idempotency_in_progress: the first request with this key is still running (for example awaitthat has not returned yet). Retry with the same key afterRetry-After.- Only
2xxanswers are kept. A4xxor5xxfrees the key, so you can fix the request and send it again with the same key. - An answer that carries a secret (for example a new token or password) is not stored.
The replay is then
{"replayed": true, "body_withheld": true, "job_id": "…"}; read the job’s state withjobs_get.
- Never re-dispatch a mutation blindly. After a timeout, a network error or a
queuedanswer, calljobs_get(orjobs_list {id}) first, or repeat the call with the same idempotency key. Aqueuedjob will run when the agent returns. Sending it again without the key would run it twice. - Retry only after a terminal
failed/timeout, and only once you’ve fixed the cause (errorMessage,jobs_output, logs, state). - Read jobs are cheap to repeat. Mutations are not.
site.createon an existing domain fails.db.createtwice fails.stack.deploytwice redeploys. - Exit code 127 means the agent on that box has no native handler for the kind,
which happens with an old agent. Update it with
agent_update {id}(operate), wait for it to reconnect, then retry.
jobs_list hides high-volume read kinds (inventory polls, server.*, metrics.*), so
the list shows real actions.
Backups are not generic jobs
Section titled “Backups are not generic jobs”Backup runs, snapshot verification and restores use dedicated operations
(backup_jobs_run, backups_run_once, backup_snapshots_restore, …), not
jobs_create. See Backups and restore.
Related
Section titled “Related”- Job kinds: domains, risk classes and plan gates.
- Safe operating rules
- Troubleshooting