1use std::time::{Duration, Instant};
7
8use serde::Deserialize;
9use serde_json::{Value, json};
10
11use super::{args, caller_name, obj};
12use crate::app::{AppSpec, Apps, Source};
13use crate::backup::{BackupSpec, Backups, Destination, RestoreRequest};
14use crate::error::{Error, Result};
15use crate::jobs::{JobSpec, Jobs, RunStore};
16use crate::org::OrgId;
17use crate::server::{Caller, Registry, Tool};
18
19#[derive(Clone)]
21pub struct Ctx {
22 pub apps: Apps,
23 pub jobs: Jobs,
24 pub backups: Backups,
25}
26
27fn org_of(a: &Value) -> Result<OrgId> {
28 super::arg_org(a)
29}
30
31fn take(a: &mut Value, keys: &[&str]) -> serde_json::Map<String, Value> {
33 let mut out = serde_json::Map::new();
34 if let Some(o) = a.as_object_mut() {
35 for k in keys {
36 if let Some(v) = o.remove(*k) {
37 out.insert((*k).to_string(), v);
38 }
39 }
40 }
41 out
42}
43
44fn trusted(c: &Caller) -> bool {
47 c.is_trusted() || c.principal().is_some_and(|p| p.platform_admin)
48}
49
50pub(super) fn unix_rfc3339(t: Option<i64>) -> Value {
51 match t {
52 Some(t) => json!(crate::cron::rfc3339(t)),
53 None => Value::Null,
54 }
55}
56
57pub(super) fn wait_run(store: &RunStore, id: u64, timeout: Duration) -> Result<crate::jobs::Run> {
59 let started = Instant::now();
60 loop {
61 let r = store.get(id)?;
62 if r.status.finished() || started.elapsed() >= timeout {
63 return Ok(r);
64 }
65 std::thread::sleep(Duration::from_millis(500));
66 }
67}
68
69pub(super) fn timeout_arg(t: &Option<String>, default: Duration) -> Result<Duration> {
70 match t {
71 Some(t) => crate::flex::parse_duration(t)
72 .map_err(Error::invalid)
73 .map(|d| d.min(Duration::from_secs(3600))),
74 None => Ok(default),
75 }
76}
77
78fn volume_backup_admin(x: &Ctx, org: &OrgId, name: &str, c: &Caller) -> Result<()> {
80 if x.backups
81 .get(org, name)
82 .is_ok_and(|b| b.spec.volume.is_some())
83 {
84 super::volumes::require_admin(c, org, "changing or running a volume backup")?;
85 }
86 Ok(())
87}
88
89pub fn database_json(org: &OrgId, a: &crate::app::App, password: Option<&str>) -> Value {
92 let mut v = super::apps::app_json(org, a);
93 if let Source::Database(db) = &a.spec.source {
94 v["connection"] = crate::app::database::connection(&a.spec, db, org, password);
95 }
96 v
97}
98
99fn backup_props() -> Value {
101 json!({
102 "name": {"type": "string"},
103 "database": {"type": "string", "description": "The database app (or give `volume`)."},
104 "volume": {"type": "string", "description": "Or a named volume in the org: its snapshot is exported (incus' tar) and streamed to the bucket; restore with volume_restore."},
105 "destination": {"type": "string"},
106 "schedule": {"type": "string", "description": "Cron: five fields (minute hour day-of-month month day-of-week) or @hourly, @daily, @weekly, @monthly, @yearly."},
107 "timezone": {"type": "string", "description": "UTC (default) or a fixed offset such as +02:00."},
108 "keep": {"type": "integer", "minimum": 1, "maximum": 1000, "description": "Backups kept in the bucket (default 7)."},
109 "compression": {"type": "string", "enum": ["gzip", "zstd", "none"]},
110 "enabled": {"type": "boolean"},
111 "missed_grace": {"type": "string", "description": "How late a slot missed while the daemon was down still runs (default 1h)."}
112 })
113}
114
115fn job_props() -> Value {
117 json!({
118 "name": {"type": "string"},
119 "schedule": {"type": "string", "description": "Cron: five fields or @hourly, @daily, @weekly, @monthly, @yearly."},
120 "timezone": {"type": "string", "description": "UTC (default) or a fixed offset such as +02:00."},
121 "target": {"type": "object", "description": "{app: NAME}, or {stack: NAME, service: NAME}."},
122 "mode": {"type": "string", "enum": ["exec", "run"], "description": "exec (default): in a running replica. run: in a fresh one-off instance from the service's image, env and secrets, deleted after."},
123 "command": {"description": "argv (a list), or a line split like a shell would (no shell runs unless you run one)."},
124 "timeout": {"type": "string", "description": "Kill after this long (default 10m, at most 24h)."},
125 "concurrency": {"type": "string", "enum": ["skip", "allow"], "description": "skip (default): a run due while one is going is skipped."},
126 "keep": {"type": "integer", "minimum": 1, "maximum": 1000, "description": "Runs kept (default 20)."},
127 "enabled": {"type": "boolean"},
128 "user": {"type": "string"},
129 "cwd": {"type": "string"},
130 "env": {"type": "object", "additionalProperties": {"type": "string"}},
131 "missed_grace": {"type": "string", "description": "How late a slot missed while the daemon was down still runs (default 1h)."}
132 })
133}
134
135struct Ann {
137 ro: Value,
138 destructive: Value,
139 write: Value,
140 write_open: Value,
142 destructive_open: Value,
143}
144
145#[derive(Deserialize)]
146#[serde(deny_unknown_fields)]
147struct Named {
148 name: String,
149 #[serde(default)]
150 #[allow(dead_code)]
151 org: Option<String>,
152}
153
154fn argv(a: &mut Value) -> Result<()> {
156 if let Some(Value::String(line)) = a.get("command") {
157 let v =
158 crate::flex::split_words(line).map_err(|e| Error::invalid(format!("command: {e}")))?;
159 a["command"] = json!(v);
160 }
161 Ok(())
162}
163
164fn job_json(j: &Jobs, org: &OrgId, job: &crate::jobs::Job) -> Value {
165 json!({
166 "job": job.spec,
167 "created_at": job.created_at,
168 "updated_at": job.updated_at,
169 "next_run": unix_rfc3339(j.next_run(job)),
170 "last_run": j.runs(org, &job.spec.name).last(),
171 })
172}
173
174pub fn register(r: &mut Registry, ctx: Ctx) -> Result<()> {
175 let ann = Ann {
176 ro: json!({"readOnlyHint": true, "openWorldHint": false}),
177 destructive: json!({"destructiveHint": true, "openWorldHint": false}),
178 write: json!({"destructiveHint": false, "openWorldHint": false}),
179 write_open: json!({"destructiveHint": false, "openWorldHint": true}),
180 destructive_open: json!({"destructiveHint": true, "openWorldHint": true}),
181 };
182
183 database_create_tool(r, &ctx, &ann)?;
186 database_list_tool(r, &ctx, &ann)?;
187 database_get_tool(r, &ctx, &ann)?;
188
189 backup_destination_create_tool(r, &ctx, &ann)?;
192 backup_destination_list_tool(r, &ctx, &ann)?;
193 backup_destination_delete_tool(r, &ctx, &ann)?;
194 backup_destination_test_tool(r, &ctx, &ann)?;
195
196 backup_create_tool(r, &ctx, &ann)?;
199 backup_update_tool(r, &ctx, &ann)?;
200 backup_list_tool(r, &ctx, &ann)?;
201 backup_delete_tool(r, &ctx, &ann)?;
202 backup_run_tool(r, &ctx, &ann)?;
203 backup_runs_tool(r, &ctx, &ann)?;
204 backup_run_log_tool(r, &ctx, &ann)?;
205 backup_restore_tool(r, &ctx, &ann)?;
206
207 job_create_tool(r, &ctx, &ann)?;
210 job_list_tool(r, &ctx, &ann)?;
211 job_get_tool(r, &ctx, &ann)?;
212 job_update_tool(r, &ctx, &ann)?;
213 job_delete_tool(r, &ctx, &ann)?;
214 job_run_tool(r, &ctx, &ann)?;
215 job_runs_tool(r, &ctx, &ann)?;
216 job_run_log_tool(r, &ctx, &ann)?;
217 Ok(())
218}
219
220fn database_create_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
221 tool!(
222 r,
223 ctx,
224 "database_create",
225 "Create a database",
226 "Create a database in a project's environment: Postgres, MySQL, MariaDB, MongoDB or Redis from the official image at `version`, its data on a named volume, one replica rolled out stop-first, with a health check. Credentials are generated and kept as org secrets (db.<name>.password; db.<name>.root-password for MySQL/MariaDB; db.<name>.url, the internal connection URL for apps: DATABASE_URL=${{secret.db.<name>.url}}; `urls` keeps more such secrets with driver options). Setting db.<name>.password changes the password inside the running database first, then the URL secrets. Other apps reach it at <name>.<project>-<env>. Not published outside the org unless `publish` is set. A database is an app: deploy, update, roll back and delete it with the app_* tools.",
227 obj(
228 json!({
229 "name": {"type": "string"},
230 "project": {"type": "string"},
231 "environment": {"type": "string", "description": "Default production."},
232 "engine": {"type": "string", "enum": ["postgres", "mysql", "mariadb", "mongodb", "redis"]},
233 "version": {"type": "string", "description": "Image tag (default: 17, 8.4, 11.4, 8.0, 7.4)."},
234 "database": {"type": "string", "description": "Database created on first start (default: the name with - as _). Not Redis."},
235 "user": {"type": "string", "description": "User created on first start (default: as database). Not Redis."},
236 "urls": {"type": "object", "additionalProperties": {"type": "string"}, "description": "More secrets isb keeps holding the internal URL, each with a query string for a driver's options ({\"dsn.main-db.web\": \"sslmode=disable\"}, \"\" for none). Written at deploy and again whenever the password changes, so no app holds a stale copy of it."},
237 "publish": {"type": "string", "description": "Publish the port on the host: [IP:]PORT (default address 127.0.0.1). Off by default."},
238 "env": {"description": "Extra environment (.env text or a map), e.g. POSTGRES_INITDB_ARGS."},
239 "resources": {"type": "object", "description": "{cpus, memory}."},
240 "deploy": {"type": "boolean", "description": "Deploy right away (default true)."},
241 "wait": {"type": "boolean", "description": "Wait until it is up (default false)."}
242 }),
243 &["name", "project", "engine"]
244 ),
245 ann.write,
246 |x: &Ctx, mut a: Value, c: &Caller| -> Result<Value> {
247 let org = org_of(&a)?;
248 let t = take(
249 &mut a,
250 &[
251 "org", "engine", "version", "database", "user", "urls", "publish", "deploy",
252 "wait",
253 ],
254 );
255 let engine = crate::app::Engine::parse(
256 t.get("engine").and_then(Value::as_str).unwrap_or_default(),
257 )?;
258 let mut db = json!({"engine": engine});
259 for k in ["version", "database", "user", "urls"] {
260 if let Some(v) = t.get(k) {
261 db[k] = v.clone();
262 }
263 }
264 a["source"] = json!({"database": db});
265 if let Some(p) = t.get("publish").and_then(Value::as_str) {
266 let (ip, port) = match p.rsplit_once(':') {
267 Some((ip, port)) => (ip.to_string(), port.to_string()),
268 None => ("127.0.0.1".to_string(), p.to_string()),
269 };
270 port.parse::<u16>()
271 .map_err(|_| Error::invalid(format!("publish {p:?}: [IP:]PORT")))?;
272 a["ports"] = json!([format!("{ip}:{port}:{}", engine.port())]);
273 }
274 let spec: AppSpec = args(a)?;
275 let (app, _) = x.apps.create(&org, spec)?;
276 let mut out = json!({"database": database_json(&org, &app, None)});
277 if t.get("deploy").and_then(Value::as_bool).unwrap_or(true) {
278 let trigger = if c.is_local() {
279 crate::app::deploy::Trigger::Manual
280 } else {
281 crate::app::deploy::Trigger::Api
282 };
283 let d = x
284 .apps
285 .deploy(&org, &app.spec.name, trigger, &caller_name(c), None)?;
286 let d = if t.get("wait").and_then(Value::as_bool).unwrap_or(false) {
287 x.apps
288 .wait(&org, &app.spec.name, d.id, Duration::from_secs(900))?
289 } else {
290 d
291 };
292 out["deployment"] = d.summary();
293 }
294 Ok(out)
295 }
296 );
297 Ok(())
298}
299
300fn database_list_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
301 tool!(
302 r,
303 ctx,
304 "database_list",
305 "List databases",
306 "An org's databases (apps with a database source), each with its engine, version, stack and connection details (password as a secret reference).",
307 obj(json!({"project": {"type": "string"}}), &[]),
308 ann.ro,
309 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
310 let org = org_of(&a)?;
311 let project = a.get("project").and_then(Value::as_str).map(String::from);
312 let dbs: Vec<Value> = x
313 .apps
314 .list(&org)?
315 .into_iter()
316 .filter(|d| matches!(d.spec.source, Source::Database(_)))
317 .filter(|d| project.as_ref().is_none_or(|p| *p == d.spec.project))
318 .map(|d| database_json(&org, &d, None))
319 .collect();
320 Ok(json!({"databases": dbs}))
321 }
322 );
323 Ok(())
324}
325
326fn database_get_tool(r: &mut Registry, ctx: &Ctx, _ann: &Ann) -> Result<()> {
327 tool!(
328 r,
329 ctx,
330 "database_get",
331 "Get a database",
332 "A database's settings and connection details: host (service name), port, user, database, the password as a reference to its org secret, and a URL with that reference. `reveal: true` adds the password and URL values (org members may read org secrets).",
333 obj(
334 json!({"name": {"type": "string"}, "reveal": {"type": "boolean"}}),
335 &["name"]
336 ),
337 json!({"readOnlyHint": true, "openWorldHint": false, "isbSecretReadArg": "reveal"}),
340 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
341 #[derive(Deserialize)]
342 #[serde(deny_unknown_fields)]
343 struct A {
344 name: String,
345 #[serde(default)]
346 reveal: bool,
347 #[serde(default)]
348 #[allow(dead_code)]
349 org: Option<String>,
350 }
351 let org = org_of(&a)?;
352 let a: A = args(a)?;
353 let app = x.apps.get(&org, &a.name)?;
354 if !matches!(app.spec.source, Source::Database(_)) {
355 return Err(Error::invalid(format!("app {} is not a database", a.name)));
356 }
357 let pw = if a.reveal {
358 let (v, _) = x
359 .apps
360 .secrets()
361 .get(&org, &crate::app::database::password_secret(&a.name))?;
362 Some(String::from_utf8_lossy(&v).trim().to_string())
363 } else {
364 None
365 };
366 Ok(database_json(&org, &app, pw.as_deref()))
367 }
368 );
369 Ok(())
370}
371
372fn backup_destination_create_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
373 tool!(
374 r,
375 ctx,
376 "backup_destination_create",
377 "Create a backup destination",
378 "An S3-compatible bucket for backups: endpoint (https://s3.<region>.amazonaws.com, an R2/B2/MinIO URL), region (default us-east-1), bucket, key prefix, path_style (true for MinIO and most self-hosted stores). The key pair is given as access_key/secret_key (stored as the org secrets backup.<name>.access-key/.secret-key) or as the names of existing secrets. Endpoints on this host (loopback) are for the local CLI and platform admins. create_bucket=true creates the bucket; test=true writes, reads back and deletes a small object.",
379 obj(
380 json!({
381 "name": {"type": "string"},
382 "endpoint": {"type": "string"},
383 "region": {"type": "string"},
384 "bucket": {"type": "string"},
385 "prefix": {"type": "string"},
386 "path_style": {"type": "boolean"},
387 "access_key": {"type": "string"},
388 "secret_key": {"type": "string"},
389 "access_key_secret": {"type": "string"},
390 "secret_key_secret": {"type": "string"},
391 "test": {"type": "boolean"},
392 "create_bucket": {"type": "boolean", "description": "Create the bucket first (self-hosted stores)."}
393 }),
394 &["name", "endpoint", "bucket"]
395 ),
396 ann.write_open,
397 |x: &Ctx, mut a: Value, c: &Caller| -> Result<Value> {
398 let org = org_of(&a)?;
399 let t = take(
400 &mut a,
401 &["org", "access_key", "secret_key", "test", "create_bucket"],
402 );
403 let s = |k: &str| t.get(k).and_then(Value::as_str).map(String::from);
404 if let Some(o) = a.as_object_mut() {
405 o.entry("access_key_secret").or_insert(json!(""));
406 o.entry("secret_key_secret").or_insert(json!(""));
407 }
408 let d: Destination = args(a)?;
409 let d = x.backups.destination_create(
410 &org,
411 d,
412 s("access_key"),
413 s("secret_key"),
414 trusted(c),
415 )?;
416 let mut out = json!({"destination": d});
417 if t.get("create_bucket")
418 .and_then(Value::as_bool)
419 .unwrap_or(false)
420 {
421 x.backups.destination_create_bucket(&org, &d.name)?;
422 out["bucket_created"] = json!(true);
423 }
424 if t.get("test").and_then(Value::as_bool).unwrap_or(false) {
425 out["test"] = match x.backups.destination_test(&org, &d.name) {
426 Ok(v) => v,
427 Err(e) => json!({"ok": false, "error": e.to_string()}),
428 };
429 }
430 Ok(out)
431 }
432 );
433 Ok(())
434}
435
436fn backup_destination_list_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
437 tool!(
438 r,
439 ctx,
440 "backup_destination_list",
441 "List backup destinations",
442 "An org's backup destinations (key pairs as secret names).",
443 obj(json!({}), &[]),
444 ann.ro,
445 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
446 let org = org_of(&a)?;
447 Ok(json!({"destinations": x.backups.destination_list(&org)?}))
448 }
449 );
450 Ok(())
451}
452
453fn backup_destination_delete_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
454 tool!(
455 r,
456 ctx,
457 "backup_destination_delete",
458 "Delete a backup destination",
459 "Delete a destination no backup uses, with the key secrets isb stored for it. Objects in the bucket are kept.",
460 obj(json!({"name": {"type": "string"}}), &["name"]),
461 ann.destructive,
462 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
463 let org = org_of(&a)?;
464 let a: Named = args(a)?;
465 x.backups.destination_delete(&org, &a.name)?;
466 Ok(json!({"ok": true}))
467 }
468 );
469 Ok(())
470}
471
472fn backup_destination_test_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
473 tool!(
474 r,
475 ctx,
476 "backup_destination_test",
477 "Test a backup destination",
478 "Write a small object under the destination's prefix, check it with HEAD and delete it.",
479 obj(json!({"name": {"type": "string"}}), &["name"]),
480 ann.write_open,
481 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
482 let org = org_of(&a)?;
483 let a: Named = args(a)?;
484 x.backups.destination_test(&org, &a.name)
485 }
486 );
487 Ok(())
488}
489
490fn backup_create_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
491 tool!(
492 r,
493 ctx,
494 "backup_create",
495 "Schedule a backup",
496 "Back a database (or a named `volume`) up on a cron schedule to a destination. A database: the engine's own dump (pg_dump, mysqldump, mariadb-dump, mongodump, a Redis RDB) runs in the database's instance, is compressed and streamed to the bucket by the daemon, checked with HEAD, and the oldest beyond `keep` are deleted. Emits backup.succeeded / backup.failed events.",
497 obj(backup_props(), &["name", "destination", "schedule"]),
498 ann.write,
499 |x: &Ctx, mut a: Value, c: &Caller| -> Result<Value> {
500 let org = org_of(&a)?;
501 take(&mut a, &["org"]);
502 let spec: BackupSpec = args(a)?;
503 if spec.volume.is_some() {
504 super::volumes::require_admin(c, &org, "backing up a volume")?;
505 }
506 let b = x.backups.create(&org, spec)?;
507 let next = x.backups.next_run(&b);
508 Ok(json!({"backup": b, "next_run": unix_rfc3339(next)}))
509 }
510 );
511 Ok(())
512}
513
514fn backup_update_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
515 tool!(
516 r,
517 ctx,
518 "backup_update",
519 "Update a backup",
520 "Change a backup's settings (a merge patch: schedule, timezone, destination, keep, compression, enabled, missed_grace). A changed schedule counts from now.",
521 obj(backup_props(), &["name"]),
522 ann.write,
523 |x: &Ctx, mut a: Value, c: &Caller| -> Result<Value> {
524 let org = org_of(&a)?;
525 let name = a
526 .get("name")
527 .and_then(Value::as_str)
528 .unwrap_or_default()
529 .to_string();
530 volume_backup_admin(x, &org, &name, c)?;
531 take(&mut a, &["org", "name"]);
532 let b = x.backups.update(&org, &name, &a)?;
533 let next = x.backups.next_run(&b);
534 Ok(json!({"backup": b, "next_run": unix_rfc3339(next)}))
535 }
536 );
537 Ok(())
538}
539
540fn backup_list_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
541 tool!(
542 r,
543 ctx,
544 "backup_list",
545 "List backups",
546 "An org's backup schedules with their last run and next run. With `name`, that backup only, plus the backup files in its bucket (newest first): what backup_restore takes.",
547 obj(
548 json!({"name": {"type": "string"}, "database": {"type": "string"}}),
549 &[]
550 ),
551 ann.ro,
552 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
553 let org = org_of(&a)?;
554 let name = a.get("name").and_then(Value::as_str);
555 let database = a.get("database").and_then(Value::as_str);
556 let mut out = Vec::new();
557 for b in x.backups.list(&org)? {
558 if name.is_some_and(|n| n != b.spec.name)
559 || database.is_some_and(|d| d != b.spec.database)
560 {
561 continue;
562 }
563 let last = x.backups.runs(&org, &b.spec.name).last();
564 let next = x.backups.next_run(&b);
565 let mut v =
566 json!({"backup": b.spec, "last_run": last, "next_run": unix_rfc3339(next)});
567 if name.is_some() {
568 v["files"] = match x.backups.files(&org, &b.spec.name) {
569 Ok(f) => json!(f),
570 Err(e) => json!({"error": e.to_string()}),
571 };
572 }
573 out.push(v);
574 }
575 if let (Some(n), true) = (name, out.is_empty()) {
576 return Err(Error::NotFound(format!("backup {n} in org {org}")));
577 }
578 Ok(json!({"backups": out}))
579 }
580 );
581 Ok(())
582}
583
584fn backup_delete_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
585 tool!(
586 r,
587 ctx,
588 "backup_delete",
589 "Delete a backup",
590 "Delete a backup schedule and its run records. Its files stay in the bucket (restore them with destination and key).",
591 obj(json!({"name": {"type": "string"}}), &["name"]),
592 ann.destructive,
593 |x: &Ctx, a: Value, c: &Caller| -> Result<Value> {
594 let org = org_of(&a)?;
595 let a: Named = args(a)?;
596 volume_backup_admin(x, &org, &a.name, c)?;
597 x.backups.delete(&org, &a.name)?;
598 Ok(json!({"ok": true}))
599 }
600 );
601 Ok(())
602}
603
604fn backup_run_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
605 tool!(
606 r,
607 ctx,
608 "backup_run",
609 "Run a backup now",
610 "Back up now, outside the schedule. Returns the run; wait=true returns when it finishes (at most `timeout`, default 10m).",
611 obj(
612 json!({"name": {"type": "string"}, "wait": {"type": "boolean"}, "timeout": {"type": "string"}}),
613 &["name"]
614 ),
615 ann.write_open,
616 |x: &Ctx, a: Value, c: &Caller| -> Result<Value> {
617 #[derive(Deserialize)]
618 #[serde(deny_unknown_fields)]
619 struct A {
620 name: String,
621 #[serde(default)]
622 wait: bool,
623 #[serde(default)]
624 timeout: Option<String>,
625 #[serde(default)]
626 #[allow(dead_code)]
627 org: Option<String>,
628 }
629 let org = org_of(&a)?;
630 let a: A = args(a)?;
631 volume_backup_admin(x, &org, &a.name, c)?;
632 let r = x.backups.run_now(&org, &a.name, &caller_name(c))?;
633 let r = if a.wait {
634 wait_run(
635 &x.backups.runs(&org, &a.name),
636 r.id,
637 timeout_arg(&a.timeout, Duration::from_secs(600))?,
638 )?
639 } else {
640 r
641 };
642 Ok(json!({"run": r}))
643 }
644 );
645 Ok(())
646}
647
648fn backup_runs_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
649 tool!(
650 r,
651 ctx,
652 "backup_runs",
653 "Backup runs",
654 "A backup's runs, newest first (status, trigger, duration, object key and size). With restores=true instead, the org's restore runs.",
655 obj(
656 json!({"name": {"type": "string"}, "restores": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 1, "maximum": 1000}}),
657 &[]
658 ),
659 ann.ro,
660 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
661 let org = org_of(&a)?;
662 let limit = a.get("limit").and_then(Value::as_u64).unwrap_or(50) as usize;
663 let store = if a.get("restores").and_then(Value::as_bool).unwrap_or(false) {
664 x.backups.restore_runs(&org)
665 } else {
666 let name = a
667 .get("name")
668 .and_then(Value::as_str)
669 .ok_or_else(|| Error::invalid("name (or restores: true) is required"))?;
670 x.backups.get(&org, name)?;
671 x.backups.runs(&org, name)
672 };
673 Ok(json!({"runs": store.list(limit)}))
674 }
675 );
676 Ok(())
677}
678
679fn backup_run_log_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
680 tool!(
681 r,
682 ctx,
683 "backup_run_log",
684 "Backup run log",
685 "One backup (or restore) run's log from byte `offset`; poll with the returned offset until finished.",
686 obj(
687 json!({
688 "name": {"type": "string", "description": "The backup (omit with restore=true)."},
689 "restore": {"type": "boolean"},
690 "run": {"type": "integer", "minimum": 1},
691 "offset": {"type": "integer", "minimum": 0}
692 }),
693 &["run"]
694 ),
695 ann.ro,
696 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
697 let org = org_of(&a)?;
698 let run = a.get("run").and_then(Value::as_u64).unwrap_or(0);
699 let offset = a.get("offset").and_then(Value::as_u64).unwrap_or(0);
700 let store = if a.get("restore").and_then(Value::as_bool).unwrap_or(false) {
701 x.backups.restore_runs(&org)
702 } else {
703 let name = a
704 .get("name")
705 .and_then(Value::as_str)
706 .ok_or_else(|| Error::invalid("name is required"))?;
707 x.backups.get(&org, name)?;
708 x.backups.runs(&org, name)
709 };
710 let (text, offset, finished) = store.log(run, offset)?;
711 Ok(
712 json!({"text": text, "offset": offset, "finished": finished, "run": store.get(run)?}),
713 )
714 }
715 );
716 Ok(())
717}
718
719fn backup_restore_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
720 tool!(
721 r,
722 ctx,
723 "backup_restore",
724 "Restore a backup",
725 "Restore a backup file into a database: `backup` (its newest file, or `key`) or `destination` + `key`; into `target`, an existing database of the same engine whose data is REPLACED (needs confirm: true), or `new`: {name, project?, environment?, version?}, a database created for it (by default beside the backed-up one). The file streams from the bucket through the daemon into the engine's restore tool (pg_restore --clean, mysql, mongorestore --drop, a Redis RDB swap). Emits restore.succeeded / restore.failed.",
726 obj(
727 json!({
728 "backup": {"type": "string"},
729 "destination": {"type": "string"},
730 "key": {"type": "string"},
731 "target": {"type": "string"},
732 "new": {"type": "object", "properties": {"name": {"type": "string"}, "project": {"type": "string"}, "environment": {"type": "string"}, "version": {"type": "string"}}, "required": ["name"]},
733 "confirm": {"type": "boolean"},
734 "wait": {"type": "boolean"},
735 "timeout": {"type": "string"}
736 }),
737 &[]
738 ),
739 ann.destructive_open,
740 |x: &Ctx, mut a: Value, c: &Caller| -> Result<Value> {
741 let org = org_of(&a)?;
742 let t = take(&mut a, &["org", "wait", "timeout"]);
743 let req: RestoreRequest = args(a)?;
744 let r = x.backups.restore(&org, req, &caller_name(c))?;
745 let r = if t.get("wait").and_then(Value::as_bool).unwrap_or(false) {
746 let timeout = t.get("timeout").and_then(Value::as_str).map(String::from);
747 wait_run(
748 &x.backups.restore_runs(&org),
749 r.id,
750 timeout_arg(&timeout, Duration::from_secs(1800))?,
751 )?
752 } else {
753 r
754 };
755 Ok(json!({"run": r}))
756 }
757 );
758 Ok(())
759}
760
761fn job_create_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
762 tool!(
763 r,
764 ctx,
765 "job_create",
766 "Create a scheduled job",
767 "Run a command on a cron schedule against an app or a stack service: in a running replica (mode exec) or a fresh one-off instance from its image (mode run). Each run keeps its exit code, duration and output (bounded); job.succeeded / job.failed events.",
768 obj(job_props(), &["name", "schedule", "target", "command"]),
769 ann.write,
770 |x: &Ctx, mut a: Value, _c: &Caller| -> Result<Value> {
771 let org = org_of(&a)?;
772 take(&mut a, &["org"]);
773 argv(&mut a)?;
774 let spec: JobSpec = args(a)?;
775 let j = x.jobs.create(&org, spec)?;
776 Ok(job_json(&x.jobs, &org, &j))
777 }
778 );
779 Ok(())
780}
781
782fn job_list_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
783 tool!(
784 r,
785 ctx,
786 "job_list",
787 "List jobs",
788 "An org's jobs with their next and last run.",
789 obj(json!({}), &[]),
790 ann.ro,
791 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
792 let org = org_of(&a)?;
793 let jobs: Vec<Value> = x
794 .jobs
795 .list(&org)?
796 .iter()
797 .map(|j| job_json(&x.jobs, &org, j))
798 .collect();
799 Ok(json!({"jobs": jobs}))
800 }
801 );
802 Ok(())
803}
804
805fn job_get_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
806 tool!(
807 r,
808 ctx,
809 "job_get",
810 "Get a job",
811 "A job's settings, next run and last run.",
812 obj(json!({"name": {"type": "string"}}), &["name"]),
813 ann.ro,
814 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
815 let org = org_of(&a)?;
816 let a: Named = args(a)?;
817 Ok(job_json(&x.jobs, &org, &x.jobs.get(&org, &a.name)?))
818 }
819 );
820 Ok(())
821}
822
823fn job_update_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
824 tool!(
825 r,
826 ctx,
827 "job_update",
828 "Update a job",
829 "Change a job's settings (a merge patch; the name is fixed). A changed schedule counts from now.",
830 obj(job_props(), &["name"]),
831 ann.write,
832 |x: &Ctx, mut a: Value, _c: &Caller| -> Result<Value> {
833 let org = org_of(&a)?;
834 let name = a
835 .get("name")
836 .and_then(Value::as_str)
837 .unwrap_or_default()
838 .to_string();
839 take(&mut a, &["org", "name"]);
840 argv(&mut a)?;
841 let j = x.jobs.update(&org, &name, &a)?;
842 Ok(job_json(&x.jobs, &org, &j))
843 }
844 );
845 Ok(())
846}
847
848fn job_delete_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
849 tool!(
850 r,
851 ctx,
852 "job_delete",
853 "Delete a job",
854 "Delete a job and its run records.",
855 obj(json!({"name": {"type": "string"}}), &["name"]),
856 ann.destructive,
857 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
858 let org = org_of(&a)?;
859 let a: Named = args(a)?;
860 x.jobs.delete(&org, &a.name)?;
861 Ok(json!({"ok": true}))
862 }
863 );
864 Ok(())
865}
866
867fn job_run_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
868 tool!(
869 r,
870 ctx,
871 "job_run",
872 "Run a job now",
873 "Run a job now, outside its schedule (refused while a run is going under concurrency skip). wait=true returns when it finishes (at most `timeout`, default 10m).",
874 obj(
875 json!({"name": {"type": "string"}, "wait": {"type": "boolean"}, "timeout": {"type": "string"}}),
876 &["name"]
877 ),
878 ann.write,
879 |x: &Ctx, a: Value, c: &Caller| -> Result<Value> {
880 #[derive(Deserialize)]
881 #[serde(deny_unknown_fields)]
882 struct A {
883 name: String,
884 #[serde(default)]
885 wait: bool,
886 #[serde(default)]
887 timeout: Option<String>,
888 #[serde(default)]
889 #[allow(dead_code)]
890 org: Option<String>,
891 }
892 let org = org_of(&a)?;
893 let a: A = args(a)?;
894 let r = x.jobs.run_now(&org, &a.name, &caller_name(c))?;
895 let r = if a.wait {
896 wait_run(
897 &x.jobs.runs(&org, &a.name),
898 r.id,
899 timeout_arg(&a.timeout, Duration::from_secs(600))?,
900 )?
901 } else {
902 r
903 };
904 Ok(json!({"run": r}))
905 }
906 );
907 Ok(())
908}
909
910fn job_runs_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
911 tool!(
912 r,
913 ctx,
914 "job_runs",
915 "Job runs",
916 "A job's runs, newest first: trigger (schedule, missed, manual), status (running, succeeded, failed, skipped), exit code, duration, output size.",
917 obj(
918 json!({"name": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 1000}}),
919 &["name"]
920 ),
921 ann.ro,
922 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
923 let org = org_of(&a)?;
924 let name = a
925 .get("name")
926 .and_then(Value::as_str)
927 .unwrap_or_default()
928 .to_string();
929 x.jobs.get(&org, &name)?;
930 let limit = a.get("limit").and_then(Value::as_u64).unwrap_or(50) as usize;
931 Ok(json!({"runs": x.jobs.runs(&org, &name).list(limit)}))
932 }
933 );
934 Ok(())
935}
936
937fn job_run_log_tool(r: &mut Registry, ctx: &Ctx, ann: &Ann) -> Result<()> {
938 tool!(
939 r,
940 ctx,
941 "job_run_log",
942 "Job run log",
943 "One run's output from byte `offset` (the first 192 KiB and the last 64 KiB are kept); poll with the returned offset until finished.",
944 obj(
945 json!({"name": {"type": "string"}, "run": {"type": "integer", "minimum": 1}, "offset": {"type": "integer", "minimum": 0}}),
946 &["name", "run"]
947 ),
948 ann.ro,
949 |x: &Ctx, a: Value, _c: &Caller| -> Result<Value> {
950 let org = org_of(&a)?;
951 let name = a
952 .get("name")
953 .and_then(Value::as_str)
954 .unwrap_or_default()
955 .to_string();
956 x.jobs.get(&org, &name)?;
957 let run = a.get("run").and_then(Value::as_u64).unwrap_or(0);
958 let offset = a.get("offset").and_then(Value::as_u64).unwrap_or(0);
959 let store = x.jobs.runs(&org, &name);
960 let (text, offset, finished) = store.log(run, offset)?;
961 Ok(
962 json!({"text": text, "offset": offset, "finished": finished, "run": store.get(run)?}),
963 )
964 }
965 );
966 Ok(())
967}