Skip to content
191 linesCodeBlameRaw
1//! What `g1t-runner register` keeps: where g1t is, who this runner is, its
2//! credential, and how it runs work. One JSON file in the runner's folder,
3//! readable by its owner only.
4
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Result};
8use serde::{Deserialize, Serialize};
9
10#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct Config {
12 /// The site, as given to `--url`: `https://g1t.sh`.
13 pub url: String,
14 /// The API the runner calls: `https://api.g1t.sh`.
15 pub api: String,
16 /// The runner's id and name.
17 pub runner: String,
18 pub name: String,
19 /// Its credential (`g1tr_…`). Rotated by g1t every day.
20 pub credential: String,
21 pub workspace: String,
22 #[serde(default)]
23 pub repo: Option<String>,
24 #[serde(default)]
25 pub group: Option<String>,
26 pub labels: Vec<String>,
27 /// Runs one job, then removes itself.
28 #[serde(default)]
29 pub ephemeral: bool,
30 /// Where jobs keep their files when they run on this machine directly.
31 pub work_dir: PathBuf,
32 /// Runs work in Docker containers (the default), or directly.
33 #[serde(default = "yes")]
34 pub docker: bool,
35 /// The image workflow jobs run in when they name no `container:`.
36 #[serde(default)]
37 pub image: Option<String>,
38 /// The image agent work runs in: git, Node and the agent's CLI.
39 #[serde(default)]
40 pub agent_image: Option<String>,
41 /// A Linux build of `g1t-runner` to run inside containers, instead of
42 /// this binary (on Linux) or the release's (elsewhere).
43 #[serde(default)]
44 pub harness: Option<PathBuf>,
45 /// Checks for new versions and updates itself.
46 #[serde(default = "yes")]
47 pub auto_update: bool,
48 /// Each job container's memory limit (`--memory`): `8g`. Three
49 /// quarters of the machine's (or the runner container's) memory if
50 /// left out.
51 #[serde(default)]
52 pub memory: Option<String>,
53 /// Each job container's CPUs (`--cpus`): `2`, `1.5`. Every CPU if left out.
54 #[serde(default)]
55 pub cpus: Option<String>,
56 /// The most processes in a job container (`--pids-limit`). 4096 if left out.
57 #[serde(default)]
58 pub pids_limit: Option<u32>,
59 /// With nested-container isolation, a job that uses Docker gets an
60 /// engine of its own. Off: jobs have no Docker.
61 #[serde(default = "yes")]
62 pub job_docker: bool,
63 /// The image a job's own engine runs: `docker:28-dind` if left out.
64 #[serde(default)]
65 pub job_docker_image: Option<String>,
66 /// Runs jobs native to this OS, each in a throwaway VM of its own
67 /// (`--native`, native.rs): Windows Sandbox on Windows.
68 #[serde(default)]
69 pub native: bool,
70}
71
72fn yes() -> bool {
73 true
74}
75
76/// The runner's folder: `--dir`, `G1T_RUNNER_DIR`, else `.g1t-runner` in
77/// the home folder.
78pub fn folder(given: Option<&str>) -> PathBuf {
79 if let Some(dir) = given.filter(|d| !d.is_empty()) {
80 return PathBuf::from(dir);
81 }
82 if let Some(dir) = std::env::var_os("G1T_RUNNER_DIR").filter(|d| !d.is_empty()) {
83 return PathBuf::from(dir);
84 }
85 let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
86 .map(PathBuf::from)
87 .unwrap_or_else(|| PathBuf::from("."));
88 home.join(".g1t-runner")
89}
90
91pub fn path(folder: &Path) -> PathBuf {
92 folder.join("config.json")
93}
94
95pub fn load(folder: &Path) -> Result<Config> {
96 let file = path(folder);
97 let text = std::fs::read_to_string(&file)
98 .with_context(|| format!("this runner is not registered ({} not found): run `g1t-runner register` first", file.display()))?;
99 serde_json::from_str(&text).with_context(|| format!("{} does not read", file.display()))
100}
101
102/// Writes the configuration so only its owner can read it, through a
103/// temporary file, so a crash never leaves half a credential.
104pub fn save(folder: &Path, config: &Config) -> Result<()> {
105 std::fs::create_dir_all(folder).with_context(|| format!("could not make {}", folder.display()))?;
106 let file = path(folder);
107 let temp = folder.join("config.json.new");
108 std::fs::write(&temp, serde_json::to_string_pretty(config)?)?;
109 #[cfg(unix)]
110 {
111 use std::os::unix::fs::PermissionsExt;
112 std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(0o600))?;
113 }
114 std::fs::rename(&temp, &file).with_context(|| format!("could not write {}", file.display()))?;
115 Ok(())
116}
117
118pub fn forget(folder: &Path) {
119 let _ = std::fs::remove_file(path(folder));
120}
121
122/// The API for a site: `https://g1t.sh` calls `https://api.g1t.sh`.
123pub fn api_for(url: &str) -> String {
124 let url = url.trim_end_matches('/');
125 match url.split_once("://") {
126 Some((scheme, host)) if !host.starts_with("api.") && !host.starts_with("localhost") && !host.starts_with("127.") => {
127 format!("{scheme}://api.{host}")
128 }
129 _ => url.to_owned(),
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 #[test]
138 fn the_api_is_found_from_the_site() {
139 assert_eq!(api_for("https://g1t.sh"), "https://api.g1t.sh");
140 assert_eq!(api_for("https://g1t.sh/"), "https://api.g1t.sh");
141 assert_eq!(api_for("https://api.g1t.sh"), "https://api.g1t.sh");
142 assert_eq!(api_for("https://git.example.com"), "https://api.git.example.com");
143 assert_eq!(api_for("http://localhost:8787"), "http://localhost:8787");
144 }
145
146 #[test]
147 fn an_older_configuration_still_reads() {
148 let old = r#"{"url":"https://g1t.sh","api":"https://api.g1t.sh","runner":"rnr_1","name":"a","credential":"g1tr_x",
149 "workspace":"acme","labels":["self-hosted"],"work_dir":"/tmp/w"}"#;
150 let config: Config = serde_json::from_str(old).unwrap();
151 assert!(config.docker && config.job_docker && config.auto_update);
152 assert_eq!(config.memory, None);
153 }
154
155 #[test]
156 fn a_configuration_survives_a_round_trip() {
157 let dir = std::env::temp_dir().join(format!("g1t-runner-config-{}", std::process::id()));
158 let config = Config {
159 url: "https://g1t.sh".into(),
160 api: "https://api.g1t.sh".into(),
161 runner: "rnr_1".into(),
162 name: "build-01".into(),
163 credential: "g1tr_x".into(),
164 workspace: "acme".into(),
165 repo: None,
166 group: Some("Default".into()),
167 labels: vec!["self-hosted".into(), "linux".into()],
168 ephemeral: false,
169 work_dir: dir.join("work"),
170 docker: true,
171 image: None,
172 agent_image: None,
173 harness: None,
174 auto_update: true,
175 memory: Some("4g".into()),
176 cpus: None,
177 pids_limit: None,
178 job_docker: true,
179 job_docker_image: None,
180 native: false,
181 };
182 save(&dir, &config).unwrap();
183 let back = load(&dir).unwrap();
184 assert_eq!(back.runner, "rnr_1");
185 assert_eq!(back.labels, config.labels);
186 assert_eq!(back.memory.as_deref(), Some("4g"));
187 forget(&dir);
188 assert!(load(&dir).is_err());
189 let _ = std::fs::remove_dir_all(&dir);
190 }
191}