Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
1,986 linesCodeBlameRaw
1//! Self-hosted runners: registering them, handing them work, hearing back,
2//! and the people's side (listing, removing, groups, settings). See
3//! `g1t_contracts::runners` for the model and the wire.
4//!
5//! Work reaches a runner only when it asks for it (`runner_poll`), so a
6//! runner never needs an open port. A workflow job is taken by flipping its
7//! row from `queued` to `in_progress` in one statement, exactly as g1t's
8//! own sandboxes take one, and the harness on the machine then fetches it
9//! and reports with the job's own token through the same API. Agent work
10//! from the runner service is kept as a task with its environment sealed,
11//! and handed over once.
12
13use g1t_contracts::access::Capability;
14use g1t_contracts::audit::{AuditActor, AuditOutcome, AuditTarget, NewAuditEntry, RecordAuditArgs, Surface};
15use g1t_contracts::billing::{ComputeKind, RecordSandboxArgs};
16use g1t_contracts::repos::{Repo, RepoPath};
17use g1t_contracts::runners::{
18 self as model, ACTIVITY_LIMIT, CloudJob, DesktopCapability, DesktopDiagnosis, DesktopJob, DesktopRunner, DesktopUpdate, DesktopRunnersArgs, ReportDesktopArgs, HandedOverTask, RunnerActivity, RunnerActivityArgs, StuckJob, StuckJobsArgs, Assignment, CancelTaskArgs, CreateRegistrationTokenArgs, DeleteRunnerGroupArgs, EnqueueTaskArgs, FinishedArgs,
19 ListRunnersArgs, Poll, PollArgs, RegisterArgs, Registered, RegistrationToken, RemoveRunnerArgs, RemoveSelfArgs, RouteArgs, Runner,
20 RunnerAuth, RunnerGroup, RunnerGroupsArgs, RunnerSettings, RunnerSettingsArgs, RunnerWork, RunnersOwner, SetRunnerGroupArgs,
21 SetRunnerSettingsArgs, Wanted,
22};
23use g1t_contracts::time::rfc3339;
24use g1t_contracts::{FailureCode, Outcome, PrincipalKind, Role, User, new_id};
25use g1t_kit::now_ms;
26use g1t_secrets::{random_hex, sha256_hex};
27use serde::Deserialize;
28use serde_json::{Map, Value, json};
29use worker::Result;
30use worker::wasm_bindgen::JsValue;
31
32use crate::plan::JobRow;
33use crate::{Actions, Count, SILENT_MS, check, fail, optional};
34
35/// What one poll has learned while it looks for work, so its looks again
36/// do not ask again: each repository's visibility, and the jobs it already
37/// said wait for a sandboxed runner.
38#[derive(Default)]
39struct Looked {
40 visibilities: std::collections::HashMap<String, Option<String>>,
41 noted: std::collections::HashSet<String>,
42}
43
44/// How often a poll looks again for work while it waits.
45const POLL_EVERY_MS: u64 = 2_500;
46/// A runner that has been offline this long is removed, as on GitHub.
47const FORGET_OFFLINE_MS: u64 = 14 * 24 * 60 * 60 * 1000;
48/// How often a poll writes down that a runner, or the work it holds, is
49/// still there. Polls come every twenty seconds or so; a write each time
50/// would be most of the service's writes for nothing. Well inside
51/// [`model::ONLINE_WITHIN_MS`] and [`crate::SILENT_MS`].
52const SEEN_RESOLUTION_MS: u64 = 60 * 1000;
53
54/// Whether `seen` is old enough, at `at`, to be written down again.
55fn seen_is_stale(seen: Option<&str>, at: u64) -> bool {
56 seen.is_none_or(|seen| seen < rfc3339(at.saturating_sub(SEEN_RESOLUTION_MS)).as_str())
57}
58
59#[derive(Clone, Debug, Deserialize)]
60pub struct RunnerRow {
61 pub id: String,
62 pub workspace: String,
63 pub repo_id: Option<String>,
64 pub repo: Option<String>,
65 pub group_id: Option<String>,
66 pub name: String,
67 pub labels: String,
68 pub os: String,
69 pub arch: String,
70 pub version: String,
71 pub ephemeral: u32,
72 pub credential_hash: String,
73 pub previous_hash: Option<String>,
74 pub rotated_at: String,
75 pub work_id: Option<String>,
76 pub work_kind: Option<String>,
77 pub spent: u32,
78 pub last_seen_at: Option<String>,
79 pub created_at: String,
80 pub created_by: Option<String>,
81 /// `nested-container`, `container` or `host` (migration 0015); none
82 /// for a runner that never said.
83 #[serde(default)]
84 pub isolation: Option<String>,
85}
86
87impl RunnerRow {
88 fn labels(&self) -> Vec<String> {
89 serde_json::from_str(&self.labels).unwrap_or_default()
90 }
91
92 fn online(&self, now: u64) -> bool {
93 self.last_seen_at.as_deref().is_some_and(|seen| seen >= rfc3339(now.saturating_sub(model::ONLINE_WITHIN_MS)).as_str())
94 }
95}
96
97#[derive(Clone, Debug, Deserialize)]
98struct GroupRow {
99 id: String,
100 name: String,
101 is_default: u32,
102 repositories: String,
103 updated_at: String,
104}
105
106impl GroupRow {
107 fn repositories(&self) -> Vec<String> {
108 serde_json::from_str(&self.repositories).unwrap_or_default()
109 }
110
111 /// Whether `repo` (`owner/name`, or a bare name) may use the group.
112 fn allows(&self, repo: &str) -> bool {
113 let name = repo.rsplit('/').next().unwrap_or(repo);
114 let listed = self.repositories();
115 listed.is_empty() || listed.iter().any(|r| r.eq_ignore_ascii_case(name))
116 }
117}
118
119#[derive(Clone, Debug, Deserialize)]
120struct RegistrationRow {
121 workspace: String,
122 repo_id: Option<String>,
123 repo: Option<String>,
124 group_id: Option<String>,
125 expires_at: String,
126 /// Who made the token: the runners it registers are theirs.
127 #[serde(default)]
128 created_by: Option<String>,
129}
130
131#[derive(Clone, Debug, Deserialize)]
132struct SettingsRow {
133 agents: u32,
134 agent_labels: String,
135 fork_pulls: u32,
136}
137
138#[derive(Clone, Debug, Deserialize)]
139pub struct TaskRow {
140 pub id: String,
141 pub sandbox: String,
142 pub repo_id: Option<String>,
143 pub repo: String,
144 pub kind: String,
145 pub title: String,
146 pub labels: String,
147 pub env: Option<String>,
148 pub timeout_minutes: u32,
149 pub status: String,
150 pub runner_id: Option<String>,
151 pub runner_name: Option<String>,
152 pub started_at: Option<String>,
153 #[serde(default)]
154 pub seen_at: Option<String>,
155 /// The agent run it belongs to (migration 0012); none for older tasks.
156 #[serde(default)]
157 pub run_id: Option<String>,
158}
159
160/// Who may do what with a set of runners: the workspace, and the
161/// repository when they are a repository's own.
162struct Place {
163 workspace: String,
164 repo: Option<Repo>,
165}
166
167fn now() -> String {
168 rfc3339(now_ms())
169}
170
171fn valid_name(name: &str) -> std::result::Result<String, String> {
172 let name = name.trim();
173 let ok = !name.is_empty()
174 && name.len() <= 64
175 && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
176 if ok {
177 Ok(name.to_owned())
178 } else {
179 Err("A runner's name is 1 to 64 letters, digits, `-`, `_` and `.`.".to_owned())
180 }
181}
182
183fn valid_group_name(name: &str) -> std::result::Result<String, String> {
184 let name = name.trim();
185 if name.is_empty() || name.len() > 64 || name.chars().any(|c| c.is_control()) {
186 return Err("A group's name is 1 to 64 characters.".to_owned());
187 }
188 Ok(name.to_owned())
189}
190
191/// What a runner's credential is checked against, and what a registration
192/// token is found by.
193fn hash(secret: &str) -> String {
194 sha256_hex(secret)
195}
196
197/// The actor of a runner's own entries in the audit log.
198fn runner_actor(runner: &RunnerRow) -> AuditActor {
199 AuditActor {
200 actor_kind: Some(g1t_contracts::audit::ActorKind::Runner),
201 actor: runner.name.clone(),
202 actor_id: runner.id.clone(),
203 ..AuditActor::default()
204 }
205}
206
207fn entry(actor: AuditActor, action: &str, workspace: &str, repo: Option<String>, path: Option<String>, message: String) -> NewAuditEntry {
208 NewAuditEntry {
209 actor,
210 action: action.to_owned(),
211 surface: Surface::Rest,
212 target: AuditTarget {
213 workspace: workspace.to_owned(),
214 repo,
215 path,
216 ..AuditTarget::default()
217 },
218 outcome: AuditOutcome::Allowed,
219 rule: "runner".to_owned(),
220 result: Some("ok".to_owned()),
221 message: Some(message),
222 request_id: new_id("req", now_ms()),
223 }
224}
225
226impl Actions {
227 // --- Shared ------------------------------------------------------------
228
229 pub(crate) async fn audit(&self, entries: Vec<NewAuditEntry>) {
230 let recorded: Result<u32> = g1t_kit::call(&self.events, "audit_record", &RecordAuditArgs { entries }).await;
231 if let Err(error) = recorded {
232 worker::console_error!("actions: audit entries not recorded: {error}");
233 }
234 }
235
236 /// Where `owner` points, if `actor` may see it (`manage` false) or
237 /// change it (`manage` true): a workspace's runners are seen by its
238 /// members and changed by its owners; a repository's own, by its
239 /// admins. Agents and workspace tokens never change them, so a
240 /// workflow's `G1T_TOKEN` cannot add a machine to run its own jobs.
241 async fn runner_place(&self, actor: &User, owner: &RunnersOwner, manage: bool) -> Result<Outcome<Place>> {
242 if actor.kind == PrincipalKind::Agent {
243 return Ok(fail(FailureCode::Forbidden, "Agents cannot see or change self-hosted runners."));
244 }
245 if manage && actor.kind == PrincipalKind::Workspace {
246 return Ok(fail(
247 FailureCode::Forbidden,
248 "A workspace's tokens, G1T_TOKEN included, cannot change self-hosted runners. Use a person's token with the runners:admin scope.",
249 ));
250 }
251 match (&owner.repo, &owner.workspace) {
252 (Some(path), _) => {
253 let repo = check!(self.may(actor, path, Capability::ManageIntegrations).await?);
254 Ok(Outcome::Ok(Place { workspace: repo.namespace.to_lowercase(), repo: Some(repo) }))
255 }
256 (None, Some(slug)) => {
257 let slug = slug.to_lowercase();
258 let role = actor.workspaces.iter().find(|m| m.slug.eq_ignore_ascii_case(&slug)).map(|m| m.role);
259 match role {
260 None => Ok(fail(FailureCode::NotFound, "There is no such workspace, or you are not a member of it.")),
261 // A workspace's machines and their tokens are its owners' alone, to see as well as change.
262 Some(Role::Member) => Ok(fail(
263 FailureCode::Forbidden,
264 format!("Only owners of {slug} can {} its self-hosted runners.", if manage { "change" } else { "see" }),
265 )),
266 Some(_) => Ok(Outcome::Ok(Place { workspace: slug, repo: None })),
267 }
268 }
269 (None, None) => Ok(fail(FailureCode::Invalid, "Give `repo` or `workspace`.")),
270 }
271 }
272
273 async fn group_rows(&self, workspace: &str) -> Result<Vec<GroupRow>> {
274 self.db
275 .prepare("SELECT * FROM runner_groups WHERE workspace = ? ORDER BY is_default DESC, name")
276 .bind(&[workspace.into()])?
277 .all()
278 .await?
279 .results::<GroupRow>()
280 }
281
282 /// The workspace's default group, made the first time it is needed.
283 async fn default_group(&self, workspace: &str) -> Result<GroupRow> {
284 let at = now();
285 self.db
286 .prepare(
287 "INSERT OR IGNORE INTO runner_groups (id, workspace, name, is_default, repositories, created_at, updated_at)
288 VALUES (?, ?, 'Default', 1, '[]', ?, ?)",
289 )
290 .bind(&[new_id("rng", now_ms()).into(), workspace.into(), at.as_str().into(), at.as_str().into()])?
291 .run()
292 .await?;
293 let row = self
294 .db
295 .prepare("SELECT * FROM runner_groups WHERE workspace = ? AND is_default = 1 LIMIT 1")
296 .bind(&[workspace.into()])?
297 .first::<GroupRow>(None)
298 .await?;
299 row.ok_or_else(|| worker::Error::RustError("the default runner group could not be made".into()))
300 }
301
302 /// A group of the workspace by id or name.
303 async fn find_group(&self, workspace: &str, wanted: &str) -> Result<Option<GroupRow>> {
304 self.default_group(workspace).await?;
305 Ok(self
306 .group_rows(workspace)
307 .await?
308 .into_iter()
309 .find(|g| g.id == wanted || g.name.eq_ignore_ascii_case(wanted.trim())))
310 }
311
312 async fn runner_rows(&self, workspace: &str) -> Result<Vec<RunnerRow>> {
313 self.db
314 .prepare("SELECT * FROM runners WHERE workspace = ? ORDER BY name")
315 .bind(&[workspace.into()])?
316 .all()
317 .await?
318 .results::<RunnerRow>()
319 }
320
321 async fn runner_by_id(&self, id: &str) -> Result<Option<RunnerRow>> {
322 self.db.prepare("SELECT * FROM runners WHERE id = ?").bind(&[id.into()])?.first::<RunnerRow>(None).await
323 }
324
325 /// What a runner is doing, for people.
326 async fn work_of(&self, row: &RunnerRow) -> Result<Option<RunnerWork>> {
327 let Some(id) = &row.work_id else { return Ok(None) };
328 if row.work_kind.as_deref() == Some("agent") {
329 let task = self.db.prepare("SELECT * FROM runner_tasks WHERE id = ?").bind(&[id.as_str().into()])?.first::<TaskRow>(None).await?;
330 return Ok(task.filter(|t| t.status == "in_progress").map(|t| RunnerWork {
331 kind: "agent".into(),
332 id: t.id,
333 name: t.title,
334 repo: Some(t.repo),
335 run_id: t.run_id,
336 started_at: t.started_at,
337 }));
338 }
339 #[derive(Deserialize)]
340 struct Found {
341 id: String,
342 name: String,
343 run_id: String,
344 status: String,
345 started_at: Option<String>,
346 repo: String,
347 }
348 let job = self
349 .db
350 .prepare("SELECT jobs.id, jobs.name, jobs.run_id, jobs.status, jobs.started_at, runs.repo FROM jobs JOIN runs ON runs.id = jobs.run_id WHERE jobs.id = ?")
351 .bind(&[id.as_str().into()])?
352 .first::<Found>(None)
353 .await?;
354 Ok(job.filter(|j| j.status == "in_progress").map(|j| RunnerWork {
355 kind: "workflow".into(),
356 id: j.id,
357 name: j.name,
358 repo: Some(j.repo),
359 run_id: Some(j.run_id),
360 started_at: j.started_at,
361 }))
362 }
363
364 async fn runner_view(&self, row: &RunnerRow, groups: &[GroupRow], at: u64) -> Result<Runner> {
365 let online = row.online(at);
366 let work = if online { self.work_of(row).await? } else { None };
367 Ok(Runner {
368 id: row.id.clone(),
369 name: row.name.clone(),
370 workspace: row.workspace.clone(),
371 repo: row.repo.clone(),
372 group: row
373 .group_id
374 .as_ref()
375 .and_then(|id| groups.iter().find(|g| &g.id == id))
376 .map(|g| g.name.clone()),
377 labels: row.labels(),
378 os: row.os.clone(),
379 arch: row.arch.clone(),
380 version: row.version.clone(),
381 ephemeral: row.ephemeral != 0,
382 status: if !online {
383 "offline"
384 } else if work.is_some() {
385 "busy"
386 } else {
387 "online"
388 }
389 .to_owned(),
390 work,
391 last_seen_at: row.last_seen_at.clone(),
392 created_at: row.created_at.clone(),
393 created_by: row.created_by.clone(),
394 isolation: row.isolation.clone(),
395 })
396 }
397
398 // --- People's side -----------------------------------------------------
399
400 /// `runners`: a workspace's runners, or a repository's: its own and
401 /// the workspace's that its group lets it use.
402 pub async fn runners(&self, a: ListRunnersArgs) -> Result<Outcome<Vec<Runner>>> {
403 let place = check!(self.runner_place(&a.actor, &a.owner, false).await?);
404 self.default_group(&place.workspace).await?;
405 let groups = self.group_rows(&place.workspace).await?;
406 let at = now_ms();
407 let mut out = Vec::new();
408 for row in self.runner_rows(&place.workspace).await? {
409 let shown = match &place.repo {
410 None => row.repo_id.is_none(),
411 Some(repo) => match &row.repo_id {
412 Some(id) => id == &repo.id,
413 None => groups.iter().find(|g| Some(&g.id) == row.group_id.as_ref()).is_none_or(|g| g.allows(&repo.name)),
414 },
415 };
416 if shown {
417 out.push(self.runner_view(&row, &groups, at).await?);
418 }
419 }
420 Ok(Outcome::Ok(out))
421 }
422
423 /// `create_registration_token`.
424 pub async fn create_registration_token(&self, a: CreateRegistrationTokenArgs) -> Result<Outcome<RegistrationToken>> {
425 let place = check!(self.runner_place(&a.actor, &a.owner, true).await?);
426 // A workspace g1t staff put a hold on registers no new runners.
427 if self.standing(&place.workspace).await.is_some_and(|standing| standing.held) {
428 return Ok(fail(
429 FailureCode::Paused,
430 "g1t staff put a hold on this workspace, so it cannot register new runners. Write to hey@flagon.io if you think this is a mistake.",
431 ));
432 }
433 let made = self
434 .db
435 .prepare("SELECT COUNT(*) AS n FROM runner_registrations WHERE workspace = ? AND created_at > ?")
436 .bind(&[place.workspace.as_str().into(), rfc3339(now_ms().saturating_sub(60 * 60 * 1000)).into()])?
437 .first::<Count>(None)
438 .await?
439 .map_or(0, |c| c.n);
440 if made >= model::MAX_TOKENS_PER_HOUR {
441 return Ok(fail(FailureCode::Conflict, "Too many registration tokens in the last hour. Each lasts an hour and registers any number of runners."));
442 }
443 let group = match (&place.repo, a.group.as_deref().map(str::trim).filter(|g| !g.is_empty())) {
444 (Some(_), Some(_)) => return Ok(fail(FailureCode::Invalid, "A repository's own runners are in no group.")),
445 (Some(_), None) => None,
446 (None, Some(wanted)) => match self.find_group(&place.workspace, wanted).await? {
447 Some(group) => Some(group),
448 None => return Ok(fail(FailureCode::NotFound, format!("There is no runner group called {wanted}."))),
449 },
450 (None, None) => Some(self.default_group(&place.workspace).await?),
451 };
452 let token = format!("{}{}", model::REGISTRATION_PREFIX, random_hex(24));
453 let at = now_ms();
454 let expires_at = rfc3339(at + model::REGISTRATION_TTL_SECONDS * 1000);
455 let repo_name = place.repo.as_ref().map(|r| format!("{}/{}", r.namespace, r.name));
456 self.db
457 .prepare(
458 "INSERT INTO runner_registrations (token_hash, workspace, repo_id, repo, group_id, created_by, created_at, expires_at)
459 VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
460 )
461 .bind(&[
462 hash(&token).into(),
463 place.workspace.as_str().into(),
464 optional(place.repo.as_ref().map(|r| r.id.as_str())),
465 optional(repo_name.as_deref()),
466 optional(group.as_ref().map(|g| g.id.as_str())),
467 a.actor.username.as_str().into(),
468 rfc3339(at).into(),
469 expires_at.as_str().into(),
470 ])?
471 .run()
472 .await?;
473 self.audit(vec![entry(
474 AuditActor::of(&a.actor),
475 "create_runner_registration_token",
476 &place.workspace,
477 repo_name.clone(),
478 None,
479 format!("Made a runner registration token{}.", group.as_ref().map(|g| format!(" for group {}", g.name)).unwrap_or_default()),
480 )])
481 .await;
482 Ok(Outcome::Ok(RegistrationToken {
483 token,
484 expires_at,
485 workspace: place.workspace,
486 repo: repo_name,
487 group: group.map(|g| g.name),
488 url: crate::SITE.to_owned(),
489 }))
490 }
491
492 /// `remove_runner`: a person removing one.
493 pub async fn remove_runner(&self, a: RemoveRunnerArgs) -> Result<Outcome<bool>> {
494 let place = check!(self.runner_place(&a.actor, &a.owner, true).await?);
495 let Some(row) = self.runner_by_id(&a.id).await? else {
496 return Ok(fail(FailureCode::NotFound, "There is no such runner."));
497 };
498 let ours = row.workspace == place.workspace
499 && match &place.repo {
500 Some(repo) => row.repo_id.as_deref() == Some(repo.id.as_str()),
501 None => row.repo_id.is_none(),
502 };
503 if !ours {
504 return Ok(fail(FailureCode::NotFound, "There is no such runner."));
505 }
506 self.forget_runner(&row, &format!("{} removed the runner {}.", a.actor.username, row.name)).await?;
507 self.audit(vec![entry(
508 AuditActor::of(&a.actor),
509 "remove_runner",
510 &row.workspace,
511 row.repo.clone(),
512 Some(row.name.clone()),
513 format!("Removed the self-hosted runner {}.", row.name),
514 )])
515 .await;
516 Ok(Outcome::Ok(true))
517 }
518
519 /// Removes a runner: what it was running fails, and its credential
520 /// stops working at once.
521 async fn forget_runner(&self, row: &RunnerRow, why: &str) -> Result<()> {
522 self.db.prepare("DELETE FROM runners WHERE id = ?").bind(&[row.id.as_str().into()])?.run().await?;
523 self.abandon_work(&row.id, why).await
524 }
525
526 /// Fails whatever a runner was running.
527 async fn abandon_work(&self, runner_id: &str, why: &str) -> Result<()> {
528 let jobs = self
529 .db
530 .prepare("SELECT id FROM jobs WHERE runner_id = ? AND status = 'in_progress'")
531 .bind(&[runner_id.into()])?
532 .all()
533 .await?
534 .results::<IdRow>()?;
535 for job in jobs {
536 self.finish_job(&job.id, "failure", Some(why), None).await?;
537 }
538 let tasks = self
539 .db
540 .prepare("SELECT * FROM runner_tasks WHERE runner_id = ? AND status = 'in_progress'")
541 .bind(&[runner_id.into()])?
542 .all()
543 .await?
544 .results::<TaskRow>()?;
545 for task in tasks {
546 self.end_task(&task, 1, why).await?;
547 }
548 Ok(())
549 }
550
551 /// `runner_groups`.
552 pub async fn runner_groups(&self, a: RunnerGroupsArgs) -> Result<Outcome<Vec<RunnerGroup>>> {
553 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
554 let place = check!(self.runner_place(&a.actor, &owner, false).await?);
555 self.default_group(&place.workspace).await?;
556 let groups = self.group_rows(&place.workspace).await?;
557 let runners = self.runner_rows(&place.workspace).await?;
558 Ok(Outcome::Ok(groups.iter().map(|g| group_view(g, &runners)).collect()))
559 }
560
561 /// `set_runner_group`.
562 pub async fn set_runner_group(&self, a: SetRunnerGroupArgs) -> Result<Outcome<RunnerGroup>> {
563 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
564 let place = check!(self.runner_place(&a.actor, &owner, true).await?);
565 self.default_group(&place.workspace).await?;
566 let groups = self.group_rows(&place.workspace).await?;
567 let name = match a.name.as_deref().map(valid_group_name).transpose() {
568 Ok(name) => name,
569 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
570 };
571 let repositories: Option<Vec<String>> = a.repositories.map(|list| {
572 let mut out: Vec<String> = Vec::new();
573 for repo in list {
574 let name = repo.trim().rsplit('/').next().unwrap_or_default().to_owned();
575 if !name.is_empty() && !out.iter().any(|r: &String| r.eq_ignore_ascii_case(&name)) {
576 out.push(name);
577 }
578 }
579 out
580 });
581 if let Some(name) = &name
582 && groups.iter().any(|g| g.name.eq_ignore_ascii_case(name) && Some(&g.id) != a.id.as_ref())
583 {
584 return Ok(fail(FailureCode::Conflict, format!("There is already a group called {name}.")));
585 }
586 let at = now();
587 let id = match &a.id {
588 Some(id) => {
589 let Some(group) = groups.iter().find(|g| &g.id == id) else {
590 return Ok(fail(FailureCode::NotFound, "There is no such runner group."));
591 };
592 self.db
593 .prepare("UPDATE runner_groups SET name = ?, repositories = ?, updated_at = ? WHERE id = ?")
594 .bind(&[
595 name.clone().unwrap_or(group.name.clone()).into(),
596 serde_json::to_string(&repositories.clone().unwrap_or(group.repositories()))?.into(),
597 at.as_str().into(),
598 id.as_str().into(),
599 ])?
600 .run()
601 .await?;
602 id.clone()
603 }
604 None => {
605 let Some(name) = name.clone() else {
606 return Ok(fail(FailureCode::Invalid, "A new group needs a name."));
607 };
608 if groups.len() >= 50 {
609 return Ok(fail(FailureCode::Conflict, "A workspace has at most 50 runner groups."));
610 }
611 let id = new_id("rng", now_ms());
612 self.db
613 .prepare(
614 "INSERT INTO runner_groups (id, workspace, name, is_default, repositories, created_at, updated_at) VALUES (?, ?, ?, 0, ?, ?, ?)",
615 )
616 .bind(&[
617 id.as_str().into(),
618 place.workspace.as_str().into(),
619 name.into(),
620 serde_json::to_string(&repositories.clone().unwrap_or_default())?.into(),
621 at.as_str().into(),
622 at.as_str().into(),
623 ])?
624 .run()
625 .await?;
626 id
627 }
628 };
629 let groups = self.group_rows(&place.workspace).await?;
630 let runners = self.runner_rows(&place.workspace).await?;
631 let Some(group) = groups.iter().find(|g| g.id == id) else {
632 return Ok(fail(FailureCode::NotFound, "There is no such runner group."));
633 };
634 self.audit(vec![entry(
635 AuditActor::of(&a.actor),
636 if a.id.is_some() { "update_runner_group" } else { "create_runner_group" },
637 &place.workspace,
638 None,
639 Some(group.name.clone()),
640 format!(
641 "Runner group {}: {}.",
642 group.name,
643 if group.repositories().is_empty() { "every repository".to_owned() } else { group.repositories().join(", ") }
644 ),
645 )])
646 .await;
647 Ok(Outcome::Ok(group_view(group, &runners)))
648 }
649
650 /// `delete_runner_group`.
651 pub async fn delete_runner_group(&self, a: DeleteRunnerGroupArgs) -> Result<Outcome<bool>> {
652 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
653 let place = check!(self.runner_place(&a.actor, &owner, true).await?);
654 let default = self.default_group(&place.workspace).await?;
655 let Some(group) = self.group_rows(&place.workspace).await?.into_iter().find(|g| g.id == a.id) else {
656 return Ok(fail(FailureCode::NotFound, "There is no such runner group."));
657 };
658 if group.is_default != 0 {
659 return Ok(fail(FailureCode::Conflict, "The default group cannot be deleted."));
660 }
661 self.db
662 .batch(vec![
663 self.db.prepare("UPDATE runners SET group_id = ? WHERE group_id = ?").bind(&[default.id.as_str().into(), group.id.as_str().into()])?,
664 self.db.prepare("DELETE FROM runner_groups WHERE id = ?").bind(&[group.id.as_str().into()])?,
665 ])
666 .await?;
667 self.audit(vec![entry(
668 AuditActor::of(&a.actor),
669 "delete_runner_group",
670 &place.workspace,
671 None,
672 Some(group.name.clone()),
673 format!("Deleted the runner group {}; its runners joined {}.", group.name, default.name),
674 )])
675 .await;
676 Ok(Outcome::Ok(true))
677 }
678
679 async fn settings_row(&self, owner: &str) -> Result<Option<SettingsRow>> {
680 self.db.prepare("SELECT * FROM runner_settings WHERE owner = ?").bind(&[owner.into()])?.first::<SettingsRow>(None).await
681 }
682
683 fn settings_of(row: Option<SettingsRow>, inherited: bool) -> RunnerSettings {
684 match row {
685 Some(row) => RunnerSettings {
686 agents_on_self_hosted: row.agents != 0,
687 agent_labels: serde_json::from_str(&row.agent_labels).unwrap_or_else(|_| vec![model::SELF_HOSTED.to_owned()]),
688 fork_pull_requests: row.fork_pulls != 0,
689 inherited,
690 },
691 None => RunnerSettings {
692 agent_labels: vec![model::SELF_HOSTED.to_owned()],
693 inherited,
694 ..RunnerSettings::default()
695 },
696 }
697 }
698
699 /// The settings that apply in a workspace, or in one of its
700 /// repositories: the repository's own if it has them.
701 pub async fn effective_runner_settings(&self, workspace: &str, repo_id: Option<&str>) -> Result<RunnerSettings> {
702 if let Some(repo_id) = repo_id
703 && let Some(own) = self.settings_row(repo_id).await?
704 {
705 return Ok(Self::settings_of(Some(own), false));
706 }
707 let inherited = repo_id.is_some();
708 Ok(Self::settings_of(self.settings_row(&workspace.to_lowercase()).await?, inherited))
709 }
710
711 /// `runner_settings`.
712 pub async fn runner_settings(&self, a: RunnerSettingsArgs) -> Result<Outcome<RunnerSettings>> {
713 let place = check!(self.runner_place(&a.actor, &a.owner, false).await?);
714 Ok(Outcome::Ok(self.effective_runner_settings(&place.workspace, place.repo.as_ref().map(|r| r.id.as_str())).await?))
715 }
716
717 /// `report_desktop`: what a person's desktop app says of its runner,
718 /// in a workspace they own. Kept per computer, replaced each time.
719 pub async fn report_desktop(&self, a: ReportDesktopArgs) -> Result<Outcome<bool>> {
720 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
721 let place = check!(self.runner_place(&a.actor, &owner, true).await?);
722 let machine = match valid_name(&a.machine) {
723 Ok(name) => name,
724 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
725 };
726 if !matches!(a.backend.as_str(), "sandboxed" | "docker" | "host") {
727 return Ok(fail(FailureCode::Invalid, "A desktop runs jobs sandboxed, in Docker or on the host."));
728 }
729 let clip = |text: &str, most: usize| text.chars().take(most).collect::<String>();
730 let tidy = |d: &DesktopDiagnosis| DesktopDiagnosis {
731 code: clip(&d.code, 40),
732 tone: clip(&d.tone, 20),
733 title: clip(&d.title, 200),
734 cause: d.cause.as_deref().map(|t| clip(t, 1000)),
735 fix: d.fix.as_deref().map(|t| clip(t, 1000)),
736 capabilities: d
737 .capabilities
738 .iter()
739 .take(model::MAX_DESKTOP_CAPABILITIES)
740 .map(|c| DesktopCapability {
741 id: clip(&c.id, 20),
742 label: clip(&c.label, 60),
743 tone: clip(&c.tone, 20),
744 title: clip(&c.title, 200),
745 cause: c.cause.as_deref().map(|t| clip(t, 1000)),
746 fix: c.fix.as_deref().map(|t| clip(t, 1000)),
747 state: c.state.as_deref().map(|t| clip(t, 20)),
748 headline: c.headline.as_deref().map(|t| clip(t, 200)),
749 about: c.about.as_deref().map(|t| clip(t, 200)),
750 enabled: c.enabled,
751 job: c.job.as_ref().map(|j| DesktopJob { kind: clip(&j.kind, 20), name: clip(&j.name, 200), repo: clip(&j.repo, 200) }),
752 runner: c.runner.as_deref().map(|t| clip(t, 80)),
753 isolation: c.isolation.as_deref().map(|t| clip(t, 40)),
754 version: c.version.as_deref().map(|t| clip(t, 40)),
755 update: c.update.as_deref().map(|t| clip(t, 200)),
756 })
757 .collect(),
758 in_capabilities: d.in_capabilities && !d.capabilities.is_empty(),
759 update: d.update.as_ref().map(|u| DesktopUpdate {
760 checked_at: u.checked_at.as_deref().map(|t| clip(t, 40)),
761 ready: u.ready.as_deref().map(|t| clip(t, 40)),
762 note: u.note.as_deref().map(|t| clip(t, 200)),
763 }),
764 };
765 let at = now_ms();
766 let known = self
767 .db
768 .prepare("SELECT COUNT(*) AS n FROM desktop_runners WHERE workspace = ? AND lower(machine) <> lower(?)")
769 .bind(&[place.workspace.as_str().into(), machine.as_str().into()])?
770 .first::<Count>(None)
771 .await?
772 .map_or(0, |c| c.n);
773 if known >= model::MAX_DESKTOPS {
774 // The oldest report makes room: a computer long gone.
775 self.db
776 .prepare("DELETE FROM desktop_runners WHERE rowid IN (SELECT rowid FROM desktop_runners WHERE workspace = ? ORDER BY reported_at LIMIT 1)")
777 .bind(&[place.workspace.as_str().into()])?
778 .run()
779 .await?;
780 }
781 self.db
782 .prepare(
783 "INSERT INTO desktop_runners (workspace, machine, person, backend, version, diagnosis, closed, reported_at)
784 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
785 ON CONFLICT (workspace, machine) DO UPDATE SET person = ?3, backend = ?4, version = ?5, diagnosis = ?6, closed = ?7, reported_at = ?8",
786 )
787 .bind(&[
788 place.workspace.as_str().into(),
789 machine.as_str().into(),
790 a.actor.username.as_str().into(),
791 a.backend.as_str().into(),
792 optional(a.version.as_deref().map(|v| clip(v, 40)).as_deref()),
793 serde_json::to_string(&tidy(&a.diagnosis))?.into(),
794 serde_json::to_string(&tidy(&a.closed))?.into(),
795 rfc3339(at).into(),
796 ])?
797 .run()
798 .await?;
799 Ok(Outcome::Ok(true))
800 }
801
802 /// `desktop_runners`: the workspace's desktops, as each app last said.
803 pub async fn desktop_runners(&self, a: DesktopRunnersArgs) -> Result<Outcome<Vec<DesktopRunner>>> {
804 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
805 let place = check!(self.runner_place(&a.actor, &owner, false).await?);
806 #[derive(Deserialize)]
807 struct Row {
808 workspace: String,
809 machine: String,
810 person: String,
811 backend: String,
812 version: Option<String>,
813 diagnosis: String,
814 closed: String,
815 reported_at: String,
816 }
817 let rows = self
818 .db
819 .prepare("SELECT * FROM desktop_runners WHERE workspace = ? ORDER BY lower(machine)")
820 .bind(&[place.workspace.as_str().into()])?
821 .all()
822 .await?
823 .results::<Row>()?;
824 let open_since = rfc3339(now_ms().saturating_sub(model::DESKTOP_OPEN_WITHIN_MS));
825 Ok(Outcome::Ok(
826 rows.into_iter()
827 .map(|row| DesktopRunner {
828 open: row.reported_at.as_str() > open_since.as_str(),
829 diagnosis: serde_json::from_str(&row.diagnosis).unwrap_or_default(),
830 closed: serde_json::from_str(&row.closed).unwrap_or_default(),
831 workspace: row.workspace,
832 machine: row.machine,
833 person: row.person,
834 backend: row.backend,
835 version: row.version,
836 reported_at: row.reported_at,
837 })
838 .collect(),
839 ))
840 }
841
842 /// `set_runner_settings`.
843 pub async fn set_runner_settings(&self, a: SetRunnerSettingsArgs) -> Result<Outcome<RunnerSettings>> {
844 let place = check!(self.runner_place(&a.actor, &a.owner, true).await?);
845 let (owner, scope) = match &place.repo {
846 Some(repo) => (repo.id.clone(), "repository"),
847 None => (place.workspace.clone(), "workspace"),
848 };
849 if a.inherit && place.repo.is_some() {
850 self.db.prepare("DELETE FROM runner_settings WHERE owner = ?").bind(&[owner.as_str().into()])?.run().await?;
851 } else {
852 let current = self.effective_runner_settings(&place.workspace, place.repo.as_ref().map(|r| r.id.as_str())).await?;
853 let labels = match &a.agent_labels {
854 Some(given) => match model::runner_labels(given, model::SELF_HOSTED, model::SELF_HOSTED) {
855 Ok(labels) => labels,
856 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
857 },
858 None => current.agent_labels.clone(),
859 };
860 let agents = a.agents_on_self_hosted.unwrap_or(current.agents_on_self_hosted);
861 let forks = a.fork_pull_requests.unwrap_or(current.fork_pull_requests);
862 self.db
863 .prepare(
864 "INSERT INTO runner_settings (owner, scope, agents, agent_labels, fork_pulls, updated_at, updated_by)
865 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
866 ON CONFLICT (owner) DO UPDATE SET agents = ?3, agent_labels = ?4, fork_pulls = ?5, updated_at = ?6, updated_by = ?7",
867 )
868 .bind(&[
869 owner.as_str().into(),
870 scope.into(),
871 u32::from(agents).into(),
872 serde_json::to_string(&labels)?.into(),
873 u32::from(forks).into(),
874 now().into(),
875 a.actor.username.as_str().into(),
876 ])?
877 .run()
878 .await?;
879 }
880 let settings = self.effective_runner_settings(&place.workspace, place.repo.as_ref().map(|r| r.id.as_str())).await?;
881 self.audit(vec![entry(
882 AuditActor::of(&a.actor),
883 "update_runner_settings",
884 &place.workspace,
885 place.repo.as_ref().map(|r| format!("{}/{}", r.namespace, r.name)),
886 None,
887 format!(
888 "Agents on self-hosted runners: {}; labels {}; pull requests from forks: {}.",
889 if settings.agents_on_self_hosted { "on" } else { "off" },
890 settings.agent_labels.join(", "),
891 if settings.fork_pull_requests { "allowed" } else { "not allowed" }
892 ),
893 )])
894 .await;
895 Ok(Outcome::Ok(settings))
896 }
897
898 // --- The runner's side ---------------------------------------------------
899
900 /// `runner_register`.
901 pub async fn runner_register(&self, a: RegisterArgs) -> Result<Outcome<Registered>> {
902 let refused = || fail(FailureCode::Unauthenticated, "That registration token is not valid, or it expired. Make a new one under Settings, Runners.");
903 if !a.token.starts_with(model::REGISTRATION_PREFIX) {
904 return Ok(refused());
905 }
906 let registration = self
907 .db
908 .prepare("SELECT * FROM runner_registrations WHERE token_hash = ?")
909 .bind(&[hash(&a.token).into()])?
910 .first::<RegistrationRow>(None)
911 .await?;
912 let at = now_ms();
913 let Some(registration) = registration.filter(|r| r.expires_at.as_str() > rfc3339(at).as_str()) else {
914 return Ok(refused());
915 };
916 let name = match valid_name(&a.name) {
917 Ok(name) => name,
918 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
919 };
920 let (Some(os), Some(arch)) = (model::os_label(&a.os), model::arch_label(&a.arch)) else {
921 return Ok(fail(FailureCode::Invalid, "A runner's os is linux, macos or windows, and its arch x64 or arm64."));
922 };
923 let labels = match model::runner_labels(&a.labels, os, arch) {
924 Ok(labels) => labels,
925 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
926 };
927 let workspace = registration.workspace.clone();
928 // Abuse: so many machines, so fast, are not a team's.
929 let recent = self
930 .db
931 .prepare("SELECT COUNT(*) AS n FROM runners WHERE workspace = ? AND created_at > ?")
932 .bind(&[workspace.as_str().into(), rfc3339(at.saturating_sub(60 * 1000)).into()])?
933 .first::<Count>(None)
934 .await?
935 .map_or(0, |c| c.n);
936 if recent >= model::MAX_REGISTRATIONS_PER_MINUTE {
937 return Ok(fail(FailureCode::Conflict, "Too many runners registered in the last minute. Wait a moment and try again."));
938 }
939 let total = self
940 .db
941 .prepare("SELECT COUNT(*) AS n FROM runners WHERE workspace = ?")
942 .bind(&[workspace.as_str().into()])?
943 .first::<Count>(None)
944 .await?
945 .map_or(0, |c| c.n);
946 // A group: the one asked for, the token's, or the default.
947 let group = if registration.repo_id.is_some() {
948 None
949 } else {
950 match a.group.as_deref().map(str::trim).filter(|g| !g.is_empty()) {
951 Some(wanted) => match self.find_group(&workspace, wanted).await? {
952 Some(group) => Some(group.id),
953 None => return Ok(fail(FailureCode::NotFound, format!("There is no runner group called {wanted}."))),
954 },
955 None => match registration.group_id.clone() {
956 Some(id) => Some(id),
957 None => Some(self.default_group(&workspace).await?.id),
958 },
959 }
960 };
961 let existing = self
962 .db
963 .prepare("SELECT * FROM runners WHERE workspace = ? AND COALESCE(repo_id, '') = ? AND lower(name) = lower(?)")
964 .bind(&[workspace.as_str().into(), registration.repo_id.clone().unwrap_or_default().into(), name.as_str().into()])?
965 .first::<RunnerRow>(None)
966 .await?;
967 if let Some(existing) = &existing {
968 if !a.replace {
969 return Ok(fail(
970 FailureCode::Conflict,
971 format!("A runner called {name} is already registered here. Register with --replace to take its place, or choose another --name."),
972 ));
973 }
974 self.forget_runner(existing, &format!("The runner {name} was replaced by a new registration.")).await?;
975 } else if total >= model::MAX_RUNNERS {
976 return Ok(fail(FailureCode::Conflict, format!("A workspace has at most {} self-hosted runners.", model::MAX_RUNNERS)));
977 }
978 // How it keeps work from its machine, if it said (older runners do not).
979 let isolation = a.isolation.as_deref().filter(|level| model::ISOLATIONS.contains(level));
980 let id = new_id("rnr", at);
981 let credential = format!("{}{}", model::CREDENTIAL_PREFIX, random_hex(32));
982 let created = rfc3339(at);
983 self.db
984 .prepare(
985 "INSERT INTO runners (id, workspace, repo_id, repo, group_id, name, labels, os, arch, version, ephemeral, credential_hash,
986 rotated_at, last_seen_at, created_at, created_by, isolation)
987 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
988 )
989 .bind(&[
990 id.as_str().into(),
991 workspace.as_str().into(),
992 optional(registration.repo_id.as_deref()),
993 optional(registration.repo.as_deref()),
994 optional(group.as_deref()),
995 name.as_str().into(),
996 serde_json::to_string(&labels)?.into(),
997 os.into(),
998 arch.into(),
999 a.version.chars().take(40).collect::<String>().into(),
1000 u32::from(a.ephemeral).into(),
1001 hash(&credential).into(),
1002 created.as_str().into(),
1003 created.as_str().into(),
1004 created.as_str().into(),
1005 // The person who made the token: a desktop's runner is theirs.
1006 optional(registration.created_by.as_deref()),
1007 optional(isolation),
1008 ])?
1009 .run()
1010 .await?;
1011 self.db
1012 .prepare("UPDATE runner_registrations SET used = used + 1 WHERE token_hash = ?")
1013 .bind(&[hash(&a.token).into()])?
1014 .run()
1015 .await?;
1016 let row = self.runner_by_id(&id).await?.ok_or_else(|| worker::Error::RustError("the runner was not kept".into()))?;
1017 self.audit(vec![entry(
1018 runner_actor(&row),
1019 "register_runner",
1020 &workspace,
1021 row.repo.clone(),
1022 Some(name.clone()),
1023 format!("Registered the self-hosted runner {name} ({os}, {arch}; labels {}).", labels.join(", ")),
1024 )])
1025 .await;
1026 let groups = self.group_rows(&workspace).await?;
1027 Ok(Outcome::Ok(Registered {
1028 runner: self.runner_view(&row, &groups, at).await?,
1029 credential,
1030 }))
1031 }
1032
1033 /// The runner a call is from, if its credential is that runner's (or
1034 /// the one before a rotation, until the new one is used).
1035 async fn authenticated(&self, auth: &RunnerAuth) -> Result<Option<(RunnerRow, bool)>> {
1036 if !auth.credential.starts_with(model::CREDENTIAL_PREFIX) {
1037 return Ok(None);
1038 }
1039 let Some(row) = self.runner_by_id(&auth.runner).await? else { return Ok(None) };
1040 let given = hash(&auth.credential);
1041 if g1t_secrets::same(&row.credential_hash, &given) {
1042 if row.previous_hash.is_some() {
1043 self.db.prepare("UPDATE runners SET previous_hash = NULL WHERE id = ?").bind(&[row.id.as_str().into()])?.run().await?;
1044 }
1045 return Ok(Some((row, true)));
1046 }
1047 if row.previous_hash.as_deref().is_some_and(|previous| g1t_secrets::same(previous, &given)) {
1048 return Ok(Some((row, false)));
1049 }
1050 Ok(None)
1051 }
1052
1053 fn unknown_runner<T>() -> Outcome<T> {
1054 fail(FailureCode::Unauthenticated, "This runner is not registered, or its credential is not valid. Register it again.")
1055 }
1056
1057 /// `runner_poll`.
1058 pub async fn runner_poll(&self, a: PollArgs) -> Result<Outcome<Poll>> {
1059 let Some((row, current)) = self.authenticated(&a.auth).await? else {
1060 return Ok(Self::unknown_runner());
1061 };
1062 let at = now_ms();
1063 let seen = rfc3339(at);
1064 // A new credential every day, handed over on a poll that used the
1065 // current one.
1066 let mut credential = None;
1067 let rotate_after = rfc3339(at.saturating_sub(model::ROTATE_AFTER_MS));
1068 if current && row.rotated_at.as_str() < rotate_after.as_str() {
1069 let fresh = format!("{}{}", model::CREDENTIAL_PREFIX, random_hex(32));
1070 self.db
1071 .prepare("UPDATE runners SET previous_hash = credential_hash, credential_hash = ?, rotated_at = ? WHERE id = ?")
1072 .bind(&[hash(&fresh).into(), seen.as_str().into(), row.id.as_str().into()])?
1073 .run()
1074 .await?;
1075 credential = Some(fresh);
1076 }
1077 // What it holds that it should stop, and the heartbeat for the rest.
1078 let mut cancel = Vec::new();
1079 let mut active: Option<(String, &'static str)> = None;
1080 for id in a.running.iter().take(10) {
1081 if let Some(job) = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[id.as_str().into()])?.first::<JobRow>(None).await? {
1082 if job.status == "in_progress" && job.runner_id.as_deref() == Some(row.id.as_str()) {
1083 if seen_is_stale(job.seen_at.as_deref(), at) {
1084 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[seen.as_str().into(), id.as_str().into()])?.run().await?;
1085 }
1086 active = Some((id.clone(), "workflow"));
1087 } else {
1088 cancel.push(id.clone());
1089 }
1090 continue;
1091 }
1092 match self.db.prepare("SELECT * FROM runner_tasks WHERE id = ?").bind(&[id.as_str().into()])?.first::<TaskRow>(None).await? {
1093 Some(task) if task.status == "in_progress" && task.runner_id.as_deref() == Some(row.id.as_str()) => {
1094 if seen_is_stale(task.seen_at.as_deref(), at) {
1095 self.db.prepare("UPDATE runner_tasks SET seen_at = ? WHERE id = ?").bind(&[seen.as_str().into(), id.as_str().into()])?.run().await?;
1096 }
1097 active = Some((id.clone(), "agent"));
1098 }
1099 _ => cancel.push(id.clone()),
1100 }
1101 }
1102 // Written when something changed, or once a minute to keep it online.
1103 let version: String = if a.version.is_empty() { row.version.clone() } else { a.version.chars().take(40).collect() };
1104 let work_id = active.as_ref().map(|(id, _)| id.as_str());
1105 let work_kind = active.as_ref().map(|(_, kind)| *kind);
1106 // How it is isolated, as it says now: a runner re-registered or
1107 // restarted with or without Docker says so on its next poll.
1108 let isolation = a
1109 .isolation
1110 .as_deref()
1111 .filter(|level| model::ISOLATIONS.contains(level))
1112 .map(str::to_owned)
1113 .or_else(|| row.isolation.clone());
1114 let changed = version != row.version
1115 || work_id != row.work_id.as_deref()
1116 || work_kind != row.work_kind.as_deref()
1117 || isolation != row.isolation;
1118 if changed || seen_is_stale(row.last_seen_at.as_deref(), at) {
1119 self.db
1120 .prepare("UPDATE runners SET last_seen_at = ?, version = ?, work_id = ?, work_kind = ?, isolation = ? WHERE id = ?")
1121 .bind(&[
1122 seen.as_str().into(),
1123 version.into(),
1124 optional(work_id),
1125 optional(work_kind),
1126 optional(isolation.as_deref()),
1127 row.id.as_str().into(),
1128 ])?
1129 .run()
1130 .await?;
1131 }
1132 let row = RunnerRow { isolation, ..row };
1133 let mut poll = Poll { assignment: None, cancel, credential, removed: false };
1134 // Busy, or an ephemeral runner that has had its one job.
1135 if active.is_some() || !a.running.is_empty() {
1136 return Ok(Outcome::Ok(poll));
1137 }
1138 if row.ephemeral != 0 && row.spent != 0 {
1139 self.forget_runner(&row, "The ephemeral runner finished its job.").await?;
1140 poll.removed = true;
1141 return Ok(Outcome::Ok(poll));
1142 }
1143 let groups = self.group_rows(&row.workspace).await?;
1144 let group = row.group_id.as_ref().and_then(|id| groups.iter().find(|g| &g.id == id)).cloned();
1145 let deadline = at + a.wait_ms.min(model::MAX_POLL_WAIT_MS);
1146 let mut looked = Looked::default();
1147 loop {
1148 if let Some(assignment) = self.claim(&row, group.as_ref(), &mut looked).await? {
1149 poll.assignment = Some(assignment);
1150 return Ok(Outcome::Ok(poll));
1151 }
1152 if now_ms() + POLL_EVERY_MS > deadline {
1153 return Ok(Outcome::Ok(poll));
1154 }
1155 worker::Delay::from(std::time::Duration::from_millis(POLL_EVERY_MS)).await;
1156 }
1157 }
1158
1159 /// Takes the oldest work this runner can do, if there is any.
1160 async fn claim(&self, runner: &RunnerRow, group: Option<&GroupRow>, looked: &mut Looked) -> Result<Option<Assignment>> {
1161 let labels = runner.labels();
1162 let group_name = group.map(|g| g.name.clone());
1163 // Workflow jobs.
1164 let mut sql = "SELECT jobs.*, runs.repo AS run_repo FROM jobs JOIN runs ON runs.id = jobs.run_id
1165 WHERE jobs.status = 'queued' AND jobs.labels IS NOT NULL AND lower(jobs.namespace) = ?"
1166 .to_owned();
1167 let mut binds: Vec<JsValue> = vec![runner.workspace.as_str().into()];
1168 if let Some(repo_id) = &runner.repo_id {
1169 sql.push_str(" AND jobs.repo_id = ?");
1170 binds.push(repo_id.as_str().into());
1171 }
1172 // One job of a concurrency group runs at a time.
1173 sql.push_str(
1174 " AND (jobs.concurrency_group IS NULL OR NOT EXISTS (SELECT 1 FROM jobs o WHERE o.repo_id = jobs.repo_id
1175 AND o.concurrency_group = jobs.concurrency_group AND o.status IN ('in_progress', 'calling')))",
1176 );
1177 sql.push_str(" ORDER BY jobs.rowid LIMIT 50");
1178 #[derive(Deserialize)]
1179 struct Queued {
1180 #[serde(flatten)]
1181 job: JobRow,
1182 run_repo: String,
1183 }
1184 let mut queued = self.db.prepare(sql).bind(&binds)?.all().await?.results::<Queued>()?;
1185 // A workspace without the plan runs FREE_SELF_HOSTED_JOBS of its jobs
1186 // on its own runners at once (limits.rs). Billing is asked only once
1187 // that many are going, so a runner's poll stays cheap.
1188 if !queued.is_empty() && self.limits.free_self_hosted_jobs > 0 {
1189 let running = self
1190 .db
1191 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE status = 'in_progress' AND runner_id IS NOT NULL AND lower(namespace) = ?")
1192 .bind(&[runner.workspace.as_str().into()])?
1193 .first::<Count>(None)
1194 .await?
1195 .map_or(0, |c| c.n);
1196 if !crate::limits::self_hosted_room(running as u64, self.limits.free_self_hosted_jobs)
1197 && self.standing(&runner.workspace).await.is_some_and(|standing| !standing.has_plan)
1198 {
1199 // Its workflow jobs wait for one to finish; anything else the
1200 // runner takes (below) is not held back.
1201 queued.clear();
1202 }
1203 }
1204 for Queued { job, run_repo } in queued {
1205 let stored: Vec<String> = job.labels.as_deref().and_then(|l| serde_json::from_str(l).ok()).unwrap_or_default();
1206 let wanted = Wanted::from_stored(&stored);
1207 if !wanted.matches(&labels, group_name.as_deref()) {
1208 continue;
1209 }
1210 if runner.repo_id.is_none() && !group.is_none_or(|g| g.allows(&run_repo)) {
1211 continue;
1212 }
1213 // A host-mode runner takes no public repository's job: it waits
1214 // for a sandboxed runner, and says so when none could take it.
1215 if runner.isolation.as_deref() == Some("host") {
1216 let visibility = self.visibility_once(looked, &job.repo_id).await;
1217 if !model::isolation_allows(runner.isolation.as_deref(), visibility.as_deref()) {
1218 if looked.noted.insert(job.id.clone()) {
1219 self.wait_for_sandbox(&job, &run_repo, &wanted).await?;
1220 }
1221 continue;
1222 }
1223 }
1224 if let Some(max) = job.max_parallel {
1225 let siblings = self
1226 .db
1227 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE run_id = ? AND key = ? AND status = 'in_progress'")
1228 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
1229 .first::<Count>(None)
1230 .await?
1231 .map_or(0, |c| c.n);
1232 if siblings >= max {
1233 continue;
1234 }
1235 }
1236 let token = random_hex(24);
1237 let at = now();
1238 let claimed = self
1239 .db
1240 .prepare(
1241 "UPDATE jobs SET status = 'in_progress', token_hash = ?, first_token_hash = NULL, runner_id = ?, runner_name = ?, reason = NULL, started_at = ?, seen_at = ?
1242 WHERE id = ? AND status = 'queued' RETURNING id",
1243 )
1244 .bind(&[
1245 sha256_hex(&token).into(),
1246 runner.id.as_str().into(),
1247 runner.name.as_str().into(),
1248 at.as_str().into(),
1249 at.as_str().into(),
1250 job.id.as_str().into(),
1251 ])?
1252 .first::<Value>(None)
1253 .await?;
1254 if claimed.is_none() {
1255 continue;
1256 }
1257 self.db
1258 .batch(vec![
1259 self.db
1260 .prepare("UPDATE runs SET status = 'in_progress', started_at = COALESCE(started_at, ?) WHERE id = ? AND status = 'queued'")
1261 .bind(&[at.as_str().into(), job.run_id.as_str().into()])?,
1262 self.db
1263 .prepare("UPDATE runners SET work_id = ?, work_kind = 'workflow', spent = ephemeral WHERE id = ?")
1264 .bind(&[job.id.as_str().into(), runner.id.as_str().into()])?,
1265 ])
1266 .await?;
1267 self.audit(vec![entry(
1268 runner_actor(runner),
1269 "runner.take_job",
1270 &runner.workspace,
1271 Some(run_repo.clone()),
1272 Some(job.name.clone()),
1273 format!("The self-hosted runner {} took the job {}.", runner.name, job.name),
1274 )])
1275 .await;
1276 // A job that deploys: its run's deployment is under way.
1277 self.job_started(&job.id).await?;
1278 let image = self.job_image(&job).await?;
1279 let visibility = self.visibility(&job.repo_id).await;
1280 return Ok(Some(Assignment {
1281 kind: "workflow".into(),
1282 id: job.id.clone(),
1283 name: job.name.clone(),
1284 repo: run_repo,
1285 timeout_minutes: job.timeout_minutes,
1286 image,
1287 token: Some(token),
1288 env: None,
1289 visibility,
1290 }));
1291 }
1292
1293 // Agent work.
1294 let tasks = self
1295 .db
1296 .prepare("SELECT * FROM runner_tasks WHERE status = 'queued' AND workspace = ? ORDER BY created_at LIMIT 20")
1297 .bind(&[runner.workspace.as_str().into()])?
1298 .all()
1299 .await?
1300 .results::<TaskRow>()?;
1301 for task in tasks {
1302 let wanted = Wanted::of(&serde_json::from_str::<Vec<String>>(&task.labels).unwrap_or_default(), None);
1303 if !wanted.matches(&labels, None) {
1304 continue;
1305 }
1306 // Nor a public repository's agent work.
1307 if runner.isolation.as_deref() == Some("host")
1308 && let Some(repo_id) = &task.repo_id
1309 {
1310 let visibility = self.visibility_once(looked, repo_id).await;
1311 if !model::isolation_allows(runner.isolation.as_deref(), visibility.as_deref()) {
1312 continue;
1313 }
1314 }
1315 if let Some(repo_id) = &runner.repo_id
1316 && task.repo_id.as_deref() != Some(repo_id.as_str())
1317 {
1318 continue;
1319 }
1320 if runner.repo_id.is_none() && !group.is_none_or(|g| g.allows(&task.repo)) {
1321 continue;
1322 }
1323 let Some(sealed) = task.env.clone() else { continue };
1324 let at = now();
1325 let claimed = self
1326 .db
1327 .prepare(
1328 "UPDATE runner_tasks SET status = 'in_progress', runner_id = ?, runner_name = ?, env = NULL, started_at = ?, seen_at = ?
1329 WHERE id = ? AND status = 'queued' RETURNING id",
1330 )
1331 .bind(&[runner.id.as_str().into(), runner.name.as_str().into(), at.as_str().into(), at.as_str().into(), task.id.as_str().into()])?
1332 .first::<Value>(None)
1333 .await?;
1334 if claimed.is_none() {
1335 continue;
1336 }
1337 self.db
1338 .prepare("UPDATE runners SET work_id = ?, work_kind = 'agent', spent = ephemeral WHERE id = ?")
1339 .bind(&[task.id.as_str().into(), runner.id.as_str().into()])?
1340 .run()
1341 .await?;
1342 let env: Map<String, Value> = self
1343 .sealer
1344 .as_ref()
1345 .and_then(|sealer| sealer.open(&sealed, &task.id))
1346 .and_then(|text| serde_json::from_str(&text).ok())
1347 .unwrap_or_default();
1348 if env.is_empty() {
1349 self.end_task(&TaskRow { status: "in_progress".into(), ..task.clone() }, 1, "The work's environment could not be opened.").await?;
1350 continue;
1351 }
1352 self.audit(vec![entry(
1353 runner_actor(runner),
1354 "runner.take_task",
1355 &runner.workspace,
1356 Some(task.repo.clone()),
1357 Some(task.kind.clone()),
1358 format!("The self-hosted runner {} took agent work: {}.", runner.name, task.title),
1359 )])
1360 .await;
1361 let visibility = match &task.repo_id {
1362 Some(repo_id) => self.visibility(repo_id).await,
1363 None => None,
1364 };
1365 return Ok(Some(Assignment {
1366 kind: "agent".into(),
1367 id: task.id.clone(),
1368 name: task.title.clone(),
1369 repo: task.repo.clone(),
1370 timeout_minutes: task.timeout_minutes,
1371 image: None,
1372 token: None,
1373 env: Some(env),
1374 visibility,
1375 }));
1376 }
1377 Ok(None)
1378 }
1379
1380 /// [`Self::visibility`], asked once per repository in a poll.
1381 async fn visibility_once(&self, looked: &mut Looked, repo_id: &str) -> Option<String> {
1382 if let Some(known) = looked.visibilities.get(repo_id) {
1383 return known.clone();
1384 }
1385 let found = self.visibility(repo_id).await;
1386 looked.visibilities.insert(repo_id.to_owned(), found.clone());
1387 found
1388 }
1389
1390 /// A public repository's job that a host-mode runner passed over: when
1391 /// no online runner that may take it could (its labels, group,
1392 /// repository, and isolation), its page says it waits for a sandboxed
1393 /// one. Written only when that changes what it says.
1394 async fn wait_for_sandbox(&self, job: &JobRow, run_repo: &str, wanted: &Wanted) -> Result<()> {
1395 let at = now_ms();
1396 let groups = self.group_rows(&job.namespace.to_lowercase()).await?;
1397 let runners = self.runner_rows(&job.namespace.to_lowercase()).await?;
1398 let sandboxed = runners.iter().any(|other| takes_public_job(other, &groups, &job.repo_id, run_repo, wanted, at));
1399 if sandboxed {
1400 return Ok(());
1401 }
1402 self.db
1403 .prepare("UPDATE jobs SET reason = ? WHERE id = ? AND status = 'queued' AND reason IS NOT ?")
1404 .bind(&[model::WAITING_FOR_SANDBOX.into(), job.id.as_str().into(), model::WAITING_FOR_SANDBOX.into()])?
1405 .run()
1406 .await?;
1407 Ok(())
1408 }
1409
1410 /// A repository's visibility for a runner, `public` or `private`; none
1411 /// when it cannot be read, and the runner decides without it.
1412 async fn visibility(&self, repo_id: &str) -> Option<String> {
1413 match self.repo_by_id(repo_id).await {
1414 Ok(Some((repo, _))) => Some(if repo.is_private { "private" } else { "public" }.to_owned()),
1415 _ => None,
1416 }
1417 }
1418
1419 /// The image a job's `container:` names, when it names one plainly.
1420 async fn job_image(&self, job: &JobRow) -> Result<Option<String>> {
1421 let Some(run) = self.run_row(&job.run_id).await? else { return Ok(None) };
1422 let raw = match job.callee() {
1423 Some((_, spec, _)) => spec.raw,
1424 None => match g1t_actions::workflow::parse(&run.source) {
1425 Ok(workflow) => match workflow.jobs.into_iter().find(|j| j.id == job.key) {
1426 Some(spec) => spec.raw,
1427 None => return Ok(None),
1428 },
1429 Err(_) => return Ok(None),
1430 },
1431 };
1432 let image = match raw.get("container") {
1433 Some(Value::String(image)) => Some(image.clone()),
1434 Some(Value::Object(container)) => container.get("image").and_then(Value::as_str).map(str::to_owned),
1435 _ => None,
1436 };
1437 Ok(image.filter(|image| !image.contains("${{") && !image.trim().is_empty()))
1438 }
1439
1440 /// `runner_finished`.
1441 pub async fn runner_finished(&self, a: FinishedArgs) -> Result<Outcome<bool>> {
1442 let Some((row, _)) = self.authenticated(&a.auth).await? else {
1443 return Ok(Self::unknown_runner());
1444 };
1445 let reason = a.reason.clone().filter(|r| !r.trim().is_empty()).map(|r| r.chars().take(2000).collect::<String>());
1446 let mut changed = false;
1447 if let Some(job) = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[a.id.as_str().into()])?.first::<JobRow>(None).await? {
1448 if job.runner_id.as_deref() == Some(row.id.as_str()) && job.status == "in_progress" {
1449 let why = reason.unwrap_or_else(|| format!("The job's process on {} exited with code {} before it reported how the job went.", row.name, a.exit_code));
1450 self.finish_job(&job.id, "failure", Some(&why), None).await?;
1451 changed = true;
1452 }
1453 } else if let Some(task) = self.db.prepare("SELECT * FROM runner_tasks WHERE id = ?").bind(&[a.id.as_str().into()])?.first::<TaskRow>(None).await?
1454 && task.runner_id.as_deref() == Some(row.id.as_str())
1455 && task.status == "in_progress"
1456 {
1457 let why = reason.unwrap_or_else(|| if a.exit_code == 0 { String::new() } else { format!("The work exited with code {} on {}.", a.exit_code, row.name) });
1458 self.end_task(&task, a.exit_code, &why).await?;
1459 changed = true;
1460 }
1461 self.db
1462 .prepare("UPDATE runners SET work_id = NULL, work_kind = NULL, last_seen_at = ? WHERE id = ? AND work_id = ?")
1463 .bind(&[now().into(), row.id.as_str().into(), a.id.as_str().into()])?
1464 .run()
1465 .await?;
1466 Ok(Outcome::Ok(changed))
1467 }
1468
1469 /// `runner_remove_self`.
1470 pub async fn runner_remove_self(&self, a: RemoveSelfArgs) -> Result<Outcome<bool>> {
1471 let Some((row, _)) = self.authenticated(&a.auth).await? else {
1472 return Ok(Self::unknown_runner());
1473 };
1474 self.forget_runner(&row, &format!("The runner {} was removed from its machine.", row.name)).await?;
1475 self.audit(vec![entry(
1476 runner_actor(&row),
1477 "remove_runner",
1478 &row.workspace,
1479 row.repo.clone(),
1480 Some(row.name.clone()),
1481 format!("The self-hosted runner {} removed itself.", row.name),
1482 )])
1483 .await;
1484 Ok(Outcome::Ok(true))
1485 }
1486
1487 /// A self-hosted job finished, however it did: its runner is free, and
1488 /// its time goes on the workspace's usage as self-hosted, at $0.
1489 pub async fn released(&self, job: &JobRow) -> Result<()> {
1490 let Some(runner_id) = &job.runner_id else { return Ok(()) };
1491 self.db
1492 .prepare("UPDATE runners SET work_id = NULL, work_kind = NULL WHERE id = ? AND work_id = ?")
1493 .bind(&[runner_id.as_str().into(), job.id.as_str().into()])?
1494 .run()
1495 .await?;
1496 let (Some(started), Some(finished)) = (job.started_at.as_deref(), job.finished_at.as_deref().map(str::to_owned).or_else(|| Some(now()))) else {
1497 return Ok(());
1498 };
1499 let seconds = match (g1t_contracts::time::parse_rfc3339(started), g1t_contracts::time::parse_rfc3339(&finished)) {
1500 (Some(a), Some(b)) if b > a => ((b - a) / 1000).max(1),
1501 _ => 1,
1502 };
1503 let run = self.run_row(&job.run_id).await?;
1504 let repo = run.as_ref().map(|r| r.repo.clone());
1505 let recorded: Result<Outcome<bool>> = g1t_kit::call(
1506 &self.billing,
1507 "record_sandbox",
1508 &RecordSandboxArgs {
1509 workspace: job.namespace.to_lowercase(),
1510 seconds: u32::try_from(seconds).unwrap_or(u32::MAX),
1511 description: format!(
1512 "{} in {} on the self-hosted runner {}",
1513 job.name,
1514 repo.clone().unwrap_or_default(),
1515 job.runner_name.clone().unwrap_or_default()
1516 ),
1517 repo,
1518 reference: format!("selfhosted/{}/{}", job.id, started),
1519 kind: Some(ComputeKind::Workflow),
1520 cpu_seconds: None,
1521 // A workflow job on a self-hosted runner: no agent ran it and nobody asked an agent for it.
1522 agent: None,
1523 asked_by: None,
1524 reservation_id: None,
1525 self_hosted: true,
1526 instance: None,
1527 },
1528 )
1529 .await;
1530 if let Err(error) = recorded {
1531 worker::console_error!("actions: self-hosted time not recorded for {}: {error}", job.id);
1532 }
1533 Ok(())
1534 }
1535
1536 /// `runner` and `RUNNER_*` for a job on a self-hosted runner.
1537 pub async fn runner_context_for(&self, runner_id: &str, variables: &mut Map<String, Value>) -> Result<Value> {
1538 let mut context = g1t_actions::events::runner_context();
1539 let Some(runner) = self.runner_by_id(runner_id).await? else { return Ok(context) };
1540 let os = match runner.os.as_str() {
1541 "macos" => "macOS",
1542 "windows" => "Windows",
1543 _ => "Linux",
1544 };
1545 let arch = if runner.arch == "arm64" { "ARM64" } else { "X64" };
1546 context["name"] = json!(runner.name);
1547 context["os"] = json!(os);
1548 context["arch"] = json!(arch);
1549 context["environment"] = json!("self-hosted");
1550 {
1551 let vars = variables;
1552 vars.insert("RUNNER_NAME".into(), json!(runner.name));
1553 vars.insert("RUNNER_OS".into(), json!(os));
1554 vars.insert("RUNNER_ARCH".into(), json!(arch));
1555 vars.insert("RUNNER_ENVIRONMENT".into(), json!("self-hosted"));
1556 }
1557 Ok(context)
1558 }
1559
1560 // --- Agent work, for the runner service ----------------------------------
1561
1562 /// `runner_route`: the labels g1t's own work in `repo` runs on, when
1563 /// its workspace (or the repository) sends it to self-hosted runners.
1564 pub async fn runner_route(&self, a: RouteArgs) -> Result<Option<Vec<String>>> {
1565 let repo_id = match self.repo_by_path(&a.repo).await? {
1566 Some(repo) => Some(repo.id),
1567 None => None,
1568 };
1569 let settings = self.effective_runner_settings(&a.workspace, repo_id.as_deref()).await?;
1570 Ok(settings.agents_on_self_hosted.then_some(settings.agent_labels))
1571 }
1572
1573 async fn repo_by_path(&self, path: &RepoPath) -> Result<Option<Repo>> {
1574 let Some(actor) = self.workspace_actor(&path.namespace).await? else { return Ok(None) };
1575 self.visible_repo(path, &Some(actor)).await
1576 }
1577
1578 /// `enqueue_task`.
1579 pub async fn enqueue_task(&self, a: EnqueueTaskArgs) -> Result<Outcome<String>> {
1580 let Some(sealer) = &self.sealer else {
1581 return Ok(fail(FailureCode::Conflict, "Agent work cannot be handed to self-hosted runners yet: g1t's key for it is not set."));
1582 };
1583 let id = new_id("rtk", now_ms());
1584 let sealed = sealer.seal(&serde_json::to_string(&a.env)?, &id);
1585 let repo_id = self.repo_by_path(&a.repo).await?.map(|r| r.id);
1586 let labels = match model::runner_labels(&a.labels, model::SELF_HOSTED, model::SELF_HOSTED) {
1587 Ok(labels) => labels,
1588 Err(problem) => return Ok(fail(FailureCode::Invalid, problem)),
1589 };
1590 let at = now();
1591 let inserted = self
1592 .db
1593 .prepare(
1594 "INSERT OR IGNORE INTO runner_tasks (id, sandbox, workspace, repo_id, repo, kind, title, labels, env, timeout_minutes, status, created_at, run_id)
1595 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?) RETURNING id",
1596 )
1597 .bind(&[
1598 id.as_str().into(),
1599 a.sandbox.as_str().into(),
1600 a.workspace.to_lowercase().into(),
1601 optional(repo_id.as_deref()),
1602 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
1603 a.kind.as_str().into(),
1604 a.title.chars().take(300).collect::<String>().into(),
1605 serde_json::to_string(&labels)?.into(),
1606 sealed.into(),
1607 a.timeout_minutes.max(1).into(),
1608 at.into(),
1609 optional(a.run_id.as_deref().filter(|id| !id.is_empty())),
1610 ])?
1611 .first::<Value>(None)
1612 .await?;
1613 if inserted.is_none() {
1614 return Ok(fail(FailureCode::Conflict, "That sandbox already handed work to a self-hosted runner."));
1615 }
1616 Ok(Outcome::Ok(id))
1617 }
1618
1619 /// `cancel_task`: the sandbox stopped it. Its runner hears on its next
1620 /// poll; the sandbox does its own ending.
1621 pub async fn cancel_task(&self, a: CancelTaskArgs) -> Result<Outcome<bool>> {
1622 let done = self
1623 .db
1624 .prepare(
1625 "UPDATE runner_tasks SET status = 'completed', exit_code = -1, reason = ?, env = NULL, finished_at = ?
1626 WHERE sandbox = ? AND status != 'completed' RETURNING id",
1627 )
1628 .bind(&[optional(a.reason.as_deref()), now().into(), a.sandbox.as_str().into()])?
1629 .first::<Value>(None)
1630 .await?;
1631 Ok(Outcome::Ok(done.is_some()))
1632 }
1633
1634 /// Ends a task and tells the sandbox waiting on it, once.
1635 async fn end_task(&self, task: &TaskRow, exit_code: i32, reason: &str) -> Result<()> {
1636 let ended = self
1637 .db
1638 .prepare(
1639 "UPDATE runner_tasks SET status = 'completed', exit_code = ?, reason = ?, env = NULL, finished_at = ?
1640 WHERE id = ? AND status != 'completed' RETURNING id",
1641 )
1642 .bind(&[exit_code.into(), optional(Some(reason).filter(|r| !r.is_empty())), now().into(), task.id.as_str().into()])?
1643 .first::<Value>(None)
1644 .await?;
1645 if ended.is_none() {
1646 return Ok(());
1647 }
1648 if let Some(runner_id) = &task.runner_id {
1649 self.db
1650 .prepare("UPDATE runners SET work_id = NULL, work_kind = NULL WHERE id = ? AND work_id = ?")
1651 .bind(&[runner_id.as_str().into(), task.id.as_str().into()])?
1652 .run()
1653 .await?;
1654 }
1655 let told: Result<Value> = g1t_kit::call(
1656 &self.runner,
1657 "task_ended",
1658 &json!({
1659 "sandbox": task.sandbox,
1660 "exitCode": exit_code,
1661 "reason": if reason.is_empty() { Value::Null } else { json!(reason) },
1662 "runner": task.runner_name,
1663 }),
1664 )
1665 .await;
1666 if let Err(error) = told {
1667 worker::console_error!("actions: the sandbox waiting on task {} was not told: {error}", task.id);
1668 }
1669 Ok(())
1670 }
1671
1672 /// `runner_activity`: what runs for the workspace now, in g1t's
1673 /// sandboxes and handed to its own runners. Its owners only, as its
1674 /// runners are.
1675 pub async fn runner_activity(&self, a: RunnerActivityArgs) -> Result<Outcome<RunnerActivity>> {
1676 let owner = RunnersOwner { repo: None, workspace: Some(a.workspace.clone()) };
1677 let place = check!(self.runner_place(&a.actor, &owner, false).await?);
1678 let workspace = place.workspace;
1679 let cloud_jobs = self
1680 .db
1681 .prepare(
1682 "SELECT jobs.id, jobs.name, jobs.run_id, runs.repo, jobs.started_at FROM jobs JOIN runs ON runs.id = jobs.run_id
1683 WHERE lower(jobs.namespace) = ? AND jobs.status = 'in_progress' AND jobs.labels IS NULL
1684 ORDER BY jobs.started_at DESC LIMIT ?",
1685 )
1686 .bind(&[workspace.as_str().into(), ACTIVITY_LIMIT.into()])?
1687 .all()
1688 .await?
1689 .results::<CloudJob>()?;
1690 let cloud_jobs_queued = self.queued_jobs(&workspace, false).await?;
1691 let self_hosted_jobs_queued = self.queued_jobs(&workspace, true).await?;
1692 let handed_over = self
1693 .db
1694 .prepare(
1695 "SELECT id, run_id, kind, title, repo, status, runner_name, created_at, started_at FROM runner_tasks
1696 WHERE status IN ('queued', 'in_progress') AND workspace = ?
1697 ORDER BY created_at DESC LIMIT ?",
1698 )
1699 .bind(&[workspace.as_str().into(), ACTIVITY_LIMIT.into()])?
1700 .all()
1701 .await?
1702 .results::<HandedOverTask>()?;
1703 Ok(Outcome::Ok(RunnerActivity { cloud_jobs, cloud_jobs_queued, handed_over, self_hosted_jobs_queued }))
1704 }
1705
1706 /// The workspace's workflow jobs queued for its own runners
1707 /// (`labelled`), or for g1t's sandboxes.
1708 async fn queued_jobs(&self, workspace: &str, labelled: bool) -> Result<u32> {
1709 let sql = if labelled {
1710 "SELECT COUNT(*) AS n FROM jobs WHERE lower(namespace) = ? AND status = 'queued' AND labels IS NOT NULL"
1711 } else {
1712 "SELECT COUNT(*) AS n FROM jobs WHERE lower(namespace) = ? AND status = 'queued' AND labels IS NULL"
1713 };
1714 Ok(self.db.prepare(sql).bind(&[workspace.into()])?.first::<Count>(None).await?.map_or(0, |c| c.n))
1715 }
1716
1717 /// `stuck_jobs`: jobs of the viewer's workspaces that have waited ten
1718 /// minutes or more for a self-hosted runner while none that could take
1719 /// them is online, for Mission control's Needs you.
1720 pub async fn stuck_jobs(&self, a: StuckJobsArgs) -> Result<Vec<StuckJob>> {
1721 let Some(viewer) = a.viewer else { return Ok(Vec::new()) };
1722 let at = now_ms();
1723 let mut out = Vec::new();
1724 for membership in viewer.workspaces.iter().take(20) {
1725 let workspace = membership.slug.to_lowercase();
1726 #[derive(Deserialize)]
1727 struct Waiting {
1728 id: String,
1729 name: String,
1730 run_id: String,
1731 labels: String,
1732 queued_at: Option<String>,
1733 repo: String,
1734 repo_id: String,
1735 }
1736 let waiting = self
1737 .db
1738 .prepare(
1739 "SELECT jobs.id, jobs.name, jobs.run_id, jobs.labels, jobs.queued_at, runs.repo, jobs.repo_id FROM jobs JOIN runs ON runs.id = jobs.run_id
1740 WHERE jobs.status = 'queued' AND jobs.labels IS NOT NULL AND lower(jobs.namespace) = ? AND jobs.queued_at < ?
1741 ORDER BY jobs.rowid LIMIT 20",
1742 )
1743 .bind(&[workspace.as_str().into(), rfc3339(at.saturating_sub(10 * 60 * 1000)).into()])?
1744 .all()
1745 .await?
1746 .results::<Waiting>()?;
1747 if waiting.is_empty() {
1748 continue;
1749 }
1750 let groups = self.group_rows(&workspace).await?;
1751 let online: Vec<RunnerRow> = self.runner_rows(&workspace).await?.into_iter().filter(|r| r.online(at)).collect();
1752 // A repository's visibility is asked only when a host-mode runner
1753 // is online, since only those pass over a public repository's jobs.
1754 let any_host = online.iter().any(|runner| runner.isolation.as_deref() == Some("host"));
1755 let mut looked = Looked::default();
1756 for job in waiting {
1757 let wanted = Wanted::from_stored(&serde_json::from_str::<Vec<String>>(&job.labels).unwrap_or_default());
1758 let visibility = if any_host { self.visibility_once(&mut looked, &job.repo_id).await } else { None };
1759 let served = online.iter().any(|runner| {
1760 let group = runner.group_id.as_ref().and_then(|id| groups.iter().find(|g| &g.id == id));
1761 wanted.matches(&runner.labels(), group.map(|g| g.name.as_str()))
1762 && model::isolation_allows(runner.isolation.as_deref(), visibility.as_deref())
1763 });
1764 if !served {
1765 out.push(StuckJob {
1766 id: job.id,
1767 name: job.name,
1768 run_id: job.run_id,
1769 repo: job.repo,
1770 labels: wanted.describe(),
1771 queued_at: job.queued_at.unwrap_or_default(),
1772 });
1773 }
1774 }
1775 }
1776 Ok(out)
1777 }
1778
1779 // --- Every minute ----------------------------------------------------------
1780
1781 /// Jobs and tasks that waited too long, tasks whose runner went quiet,
1782 /// runners offline for weeks, and registration tokens long expired.
1783 pub async fn sweep_runners(&self, at: u64) -> Result<()> {
1784 let before = |ms: u64| rfc3339(at.saturating_sub(ms));
1785 let waited = model::MAX_WAIT_HOURS * 60 * 60 * 1000;
1786 let stale = self
1787 .db
1788 .prepare("SELECT * FROM jobs WHERE status = 'queued' AND labels IS NOT NULL AND queued_at < ? LIMIT 50")
1789 .bind(&[before(waited).into()])?
1790 .all()
1791 .await?
1792 .results::<JobRow>()?;
1793 for job in stale {
1794 let stored: Vec<String> = job.labels.as_deref().and_then(|l| serde_json::from_str(l).ok()).unwrap_or_default();
1795 let why = format!(
1796 "No self-hosted runner with labels {} took it within {} hours.",
1797 Wanted::from_stored(&stored).describe(),
1798 model::MAX_WAIT_HOURS
1799 );
1800 self.finish_job(&job.id, "failure", Some(&why), None).await?;
1801 }
1802 let tasks = self
1803 .db
1804 .prepare(
1805 "SELECT * FROM runner_tasks WHERE (status = 'queued' AND created_at < ?) OR (status = 'in_progress' AND seen_at < ?) LIMIT 50",
1806 )
1807 .bind(&[before(waited).into(), before(SILENT_MS).into()])?
1808 .all()
1809 .await?
1810 .results::<TaskRow>()?;
1811 for task in tasks {
1812 let why = if task.status == "queued" {
1813 format!("No self-hosted runner with labels {} took it within {} hours.", Wanted::of(&serde_json::from_str::<Vec<String>>(&task.labels).unwrap_or_default(), None).describe(), model::MAX_WAIT_HOURS)
1814 } else {
1815 format!("The self-hosted runner {} stopped answering.", task.runner_name.clone().unwrap_or_default())
1816 };
1817 self.end_task(&task, 1, &why).await?;
1818 }
1819 let forgotten = self
1820 .db
1821 .prepare("SELECT * FROM runners WHERE COALESCE(last_seen_at, created_at) < ? LIMIT 50")
1822 .bind(&[before(FORGET_OFFLINE_MS).into()])?
1823 .all()
1824 .await?
1825 .results::<RunnerRow>()?;
1826 for row in forgotten {
1827 self.forget_runner(&row, "The runner was offline for 14 days.").await?;
1828 }
1829 // An ephemeral runner that took its job and then went quiet.
1830 let spent = self
1831 .db
1832 .prepare("SELECT * FROM runners WHERE ephemeral = 1 AND spent = 1 AND work_id IS NULL AND COALESCE(last_seen_at, created_at) < ? LIMIT 50")
1833 .bind(&[before(60 * 60 * 1000).into()])?
1834 .all()
1835 .await?
1836 .results::<RunnerRow>()?;
1837 for row in spent {
1838 self.forget_runner(&row, "The ephemeral runner finished its job.").await?;
1839 }
1840 self.db
1841 .prepare("DELETE FROM runner_registrations WHERE expires_at < ?")
1842 .bind(&[before(24 * 60 * 60 * 1000).into()])?
1843 .run()
1844 .await?;
1845 Ok(())
1846 }
1847}
1848
1849#[derive(Deserialize)]
1850struct IdRow {
1851 id: String,
1852}
1853
1854/// Whether `runner` is online and could take a public repository's job:
1855/// not host-mode, and its repository, group and labels let it.
1856fn takes_public_job(runner: &RunnerRow, groups: &[GroupRow], repo_id: &str, run_repo: &str, wanted: &Wanted, at: u64) -> bool {
1857 let group = runner.group_id.as_ref().and_then(|id| groups.iter().find(|g| &g.id == id));
1858 runner.online(at)
1859 && model::isolation_allows(runner.isolation.as_deref(), Some("public"))
1860 && runner.repo_id.as_deref().is_none_or(|repo| repo == repo_id)
1861 && (runner.repo_id.is_some() || group.is_none_or(|g| g.allows(run_repo)))
1862 && wanted.matches(&runner.labels(), group.map(|g| g.name.as_str()))
1863}
1864
1865fn group_view(group: &GroupRow, runners: &[RunnerRow]) -> RunnerGroup {
1866 RunnerGroup {
1867 id: group.id.clone(),
1868 name: group.name.clone(),
1869 default: group.is_default != 0,
1870 repositories: group.repositories(),
1871 runners: runners.iter().filter(|r| r.group_id.as_deref() == Some(group.id.as_str())).count() as u32,
1872 updated_at: group.updated_at.clone(),
1873 }
1874}
1875
1876#[cfg(test)]
1877mod tests {
1878 use super::*;
1879
1880 fn group(repositories: &[&str]) -> GroupRow {
1881 GroupRow {
1882 id: "rng_1".into(),
1883 name: "Default".into(),
1884 is_default: 1,
1885 repositories: serde_json::to_string(&repositories).unwrap(),
1886 updated_at: "2026-10-06T00:00:00Z".into(),
1887 }
1888 }
1889
1890 #[test]
1891 fn being_seen_is_written_once_a_minute() {
1892 let at = 2_000_000_000_000;
1893 assert!(seen_is_stale(None, at));
1894 assert!(!seen_is_stale(Some(&rfc3339(at - 59_000)), at));
1895 assert!(seen_is_stale(Some(&rfc3339(at - 61_000)), at));
1896 // A runner written down at the last moment is still online until the
1897 // next write, a poll later.
1898 assert!(SEEN_RESOLUTION_MS + model::MAX_POLL_WAIT_MS < model::ONLINE_WITHIN_MS);
1899 assert!(SEEN_RESOLUTION_MS < crate::SILENT_MS);
1900 }
1901
1902 #[test]
1903 fn a_group_lets_its_repositories_use_it() {
1904 assert!(group(&[]).allows("acme/web"));
1905 assert!(group(&["web", "api"]).allows("acme/WEB"));
1906 assert!(group(&["web"]).allows("web"));
1907 assert!(!group(&["web"]).allows("acme/docs"));
1908 }
1909
1910 #[test]
1911 fn names_are_checked() {
1912 assert_eq!(valid_name(" build-01 ").unwrap(), "build-01");
1913 assert!(valid_name("").is_err());
1914 assert!(valid_name("has space").is_err());
1915 assert!(valid_name(&"x".repeat(65)).is_err());
1916 assert!(valid_group_name("GPU machines").is_ok());
1917 assert!(valid_group_name("").is_err());
1918 }
1919
1920 #[test]
1921 fn only_a_sandboxed_runner_that_could_take_it_serves_a_public_job() {
1922 let at = 1_000_000_000;
1923 let runner = |isolation: Option<&str>| RunnerRow {
1924 id: "rnr_1".into(),
1925 workspace: "acme".into(),
1926 repo_id: None,
1927 repo: None,
1928 group_id: None,
1929 name: "a".into(),
1930 labels: r#"["self-hosted","linux","x64"]"#.into(),
1931 os: "linux".into(),
1932 arch: "x64".into(),
1933 version: String::new(),
1934 ephemeral: 0,
1935 credential_hash: String::new(),
1936 previous_hash: None,
1937 rotated_at: String::new(),
1938 work_id: None,
1939 work_kind: None,
1940 spent: 0,
1941 last_seen_at: Some(rfc3339(at)),
1942 created_at: String::new(),
1943 created_by: None,
1944 isolation: isolation.map(str::to_owned),
1945 };
1946 let wanted = Wanted::of(&["self-hosted".to_owned(), "linux".to_owned()], None);
1947 let takes = |row: &RunnerRow| takes_public_job(row, &[], "rep_1", "acme/web", &wanted, at);
1948 assert!(!takes(&runner(Some("host"))));
1949 assert!(takes(&runner(Some("container"))));
1950 assert!(takes(&runner(Some("nested-container"))));
1951 assert!(takes(&runner(None)), "an older runner, which refuses for itself");
1952 assert!(!takes(&RunnerRow { repo_id: Some("rep_2".into()), ..runner(None) }), "another repository's");
1953 assert!(!takes(&RunnerRow { labels: r#"["self-hosted","macos"]"#.into(), ..runner(None) }));
1954 assert!(!takes(&RunnerRow { last_seen_at: None, ..runner(None) }), "offline");
1955 }
1956
1957 #[test]
1958 fn online_means_seen_in_the_last_ninety_seconds() {
1959 let row = RunnerRow {
1960 id: "rnr_1".into(),
1961 workspace: "acme".into(),
1962 repo_id: None,
1963 repo: None,
1964 group_id: None,
1965 name: "a".into(),
1966 labels: "[]".into(),
1967 os: "linux".into(),
1968 arch: "x64".into(),
1969 version: String::new(),
1970 ephemeral: 0,
1971 credential_hash: String::new(),
1972 previous_hash: None,
1973 rotated_at: String::new(),
1974 work_id: None,
1975 work_kind: None,
1976 spent: 0,
1977 last_seen_at: Some(rfc3339(1_000_000_000)),
1978 created_at: String::new(),
1979 created_by: None,
1980 isolation: None,
1981 };
1982 assert!(row.online(1_000_000_000 + 60_000));
1983 assert!(!row.online(1_000_000_000 + 120_000));
1984 assert_eq!(row.workspace, "acme");
1985 }
1986}