push.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //! Post-build registry push (`[registry]` config section).
  2. //!
  3. //! Images are pushed as **version tags**, not `:local`: the version is the
  4. //! image's build checksum (recursive SHA-256 of the image dir, the same
  5. //! value stamped as the `sm121.checksum` label) — identical content always
  6. //! maps to the identical tag, so re-publishing "the same thing" cannot
  7. //! create a duplicate; changed content is a new version. Each push also
  8. //! refreshes the mutable `latest` tag.
  9. //!
  10. //! A local publication ledger (`published.json` next to the global config)
  11. //! records what was published and with which image digest: a re-push with
  12. //! an unchanged digest is skipped (with a note) unless forced. The push
  13. //! itself runs in a tmux session on the build node — a 30 GB push must not
  14. //! ride on a single SSH session — polled with the same 30 s / 90 min loop
  15. //! as the build. The launcher stores no registry credentials: the node must
  16. //! be `docker login`-ed once.
  17. use super::build::{DEFAULT_MAX_BUILD_SECS, format_elapsed};
  18. use super::shq;
  19. use crate::config::{Config, Node};
  20. use crate::ssh::run_ssh;
  21. use anyhow::Result;
  22. use std::collections::HashMap;
  23. use tracing::info;
  24. /// One published image: its version tag, the local image digest it was
  25. /// published from, and when. Keyed by the repo name (the image name without
  26. /// its tag).
  27. #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
  28. pub struct PublishedEntry {
  29. pub version: String,
  30. pub image_id: String,
  31. pub published_at: String,
  32. }
  33. /// Ledger file: `<global config dir>/published.json`.
  34. fn ledger_path() -> Option<std::path::PathBuf> {
  35. crate::config::default_config_dir().map(|d| d.join("published.json"))
  36. }
  37. fn read_published() -> HashMap<String, PublishedEntry> {
  38. let Some(p) = ledger_path() else {
  39. return HashMap::new();
  40. };
  41. std::fs::read_to_string(p)
  42. .ok()
  43. .and_then(|s| serde_json::from_str(&s).ok())
  44. .unwrap_or_default()
  45. }
  46. fn record_published(name: &str, entry: &PublishedEntry) {
  47. let Some(p) = ledger_path() else {
  48. return;
  49. };
  50. let mut m = read_published();
  51. m.insert(name.to_string(), entry.clone());
  52. if let Some(parent) = p.parent() {
  53. let _ = std::fs::create_dir_all(parent);
  54. }
  55. let _ = std::fs::write(&p, serde_json::to_string_pretty(&m).unwrap_or_default());
  56. }
  57. /// Map a local image to the two pushed refs: `{base}/{name}:{version}` and
  58. /// `{base}/{name}:latest`. `None` when the mapping is meaningless (empty
  59. /// base, image name, or version).
  60. pub(crate) fn registry_refs(
  61. base: &str,
  62. image_tag: &str,
  63. version: &str,
  64. ) -> Option<(String, String)> {
  65. let base = base.trim().trim_end_matches('/');
  66. let name = image_tag.trim();
  67. let version = version.trim();
  68. if base.is_empty() || name.is_empty() || version.is_empty() {
  69. return None;
  70. }
  71. let name_part = name.rsplit_once(':').map(|(n, _)| n).unwrap_or(name);
  72. let repo = name_part.rsplit('/').next()?.trim();
  73. if repo.is_empty() {
  74. return None;
  75. }
  76. Some((
  77. format!("{base}/{repo}:{version}"),
  78. format!("{base}/{repo}:latest"),
  79. ))
  80. }
  81. /// Push a built image to the configured `[registry]` (no-op when the section
  82. /// is absent). `version` = the build checksum (first 12 hex chars); both the
  83. /// version tag and `latest` are pushed. Skips (with a note) when the ledger
  84. /// records this exact image digest under the same version, unless `force`.
  85. pub async fn push_image(
  86. config: &Config,
  87. node: &Node,
  88. image_tag: &str,
  89. version: &str,
  90. force: bool,
  91. label: &str,
  92. ) -> Result<()> {
  93. let Some(registry) = config.registry.as_ref() else {
  94. return Ok(());
  95. };
  96. let Some((version_ref, latest_ref)) = registry_refs(&registry.base, image_tag, version) else {
  97. anyhow::bail!(
  98. "{}",
  99. fluent_i18n::t!("push-mapping-failed", {
  100. "base" => registry.base.clone(),
  101. "image" => image_tag.to_string()
  102. })
  103. );
  104. };
  105. let host = registry.base.split('/').next().unwrap_or(&registry.base);
  106. let repo_name = latest_ref
  107. .rsplit_once(":latest")
  108. .map(|(repo, _)| repo.to_string())
  109. .unwrap_or_else(|| image_tag.to_string());
  110. // Duplicate guard: ledger says this exact image was already published
  111. // under this version → skip unless explicitly forced.
  112. let image_id = run_ssh(
  113. config,
  114. node,
  115. format!(
  116. "docker image inspect --format '{{{{.Id}}}}' {} 2>/dev/null || echo MISSING",
  117. shq(image_tag)
  118. ),
  119. false,
  120. )
  121. .await
  122. .unwrap_or_default()
  123. .trim()
  124. .to_string();
  125. if image_id.is_empty() || image_id == "MISSING" {
  126. let node_name = node.name.clone();
  127. anyhow::bail!("image '{image_tag}' not found on '{node_name}' — build it first");
  128. }
  129. if !force
  130. && let Some(e) = read_published().get(&repo_name)
  131. && e.image_id == image_id
  132. && e.version == version.trim()
  133. {
  134. info!(
  135. "{}",
  136. fluent_i18n::t!("push-already-published", {
  137. "ref" => version_ref.clone(),
  138. "label" => label.to_string()
  139. })
  140. );
  141. return Ok(());
  142. }
  143. let session_name = format!("sm121-push-{label}");
  144. let logfile = format!("/tmp/{label}-push.log");
  145. let marker = format!("Push done: {version_ref}");
  146. run_ssh(
  147. config,
  148. node,
  149. format!(
  150. "tmux kill-session -t {s} 2>/dev/null || true",
  151. s = shq(&session_name)
  152. ),
  153. false,
  154. )
  155. .await?;
  156. let tmux_cmd = format!(
  157. "tmux new-session -d -s {s} \"docker push {a} > {log} 2>&1 && docker push {b} >> {log} 2>&1 \
  158. && echo '{m}' >> {log}\"",
  159. s = shq(&session_name),
  160. a = shq(&version_ref),
  161. b = shq(&latest_ref),
  162. m = shq(&marker),
  163. log = shq(&logfile)
  164. );
  165. info!(
  166. "{}",
  167. fluent_i18n::t!("pushing-image", { "ref" => version_ref.clone(), "session" => session_name.clone() })
  168. );
  169. run_ssh(config, node, tmux_cmd, false).await?;
  170. let start = std::time::Instant::now();
  171. loop {
  172. tokio::time::sleep(std::time::Duration::from_secs(30)).await;
  173. let elapsed = start.elapsed();
  174. if elapsed.as_secs() >= DEFAULT_MAX_BUILD_SECS {
  175. anyhow::bail!(
  176. "{}",
  177. fluent_i18n::t!("push-timeout", {
  178. "ref" => version_ref.clone(),
  179. "node" => node.name.clone(),
  180. "elapsed" => format_elapsed(elapsed),
  181. "session" => session_name.clone(),
  182. "log" => logfile.clone()
  183. })
  184. );
  185. }
  186. let alive = run_ssh(
  187. config,
  188. node,
  189. format!(
  190. "tmux has-session -t {s} 2>&1 || echo DEAD",
  191. s = shq(&session_name)
  192. ),
  193. false,
  194. )
  195. .await?;
  196. let dead = alive.trim().contains("DEAD");
  197. if let Ok(logs) = run_ssh(
  198. config,
  199. node,
  200. format!(
  201. "tail -10 {log} 2>/dev/null || echo '(no log yet)'",
  202. log = shq(&logfile)
  203. ),
  204. false,
  205. )
  206. .await
  207. {
  208. for line in logs.lines().filter(|l| !l.is_empty()) {
  209. info!(" [push] {}", line.trim());
  210. }
  211. }
  212. if dead {
  213. let ok = run_ssh(
  214. config,
  215. node,
  216. format!(
  217. "grep -F -- {m} {log} >/dev/null 2>&1 && echo OK || echo NO",
  218. m = shq(&marker),
  219. log = shq(&logfile)
  220. ),
  221. false,
  222. )
  223. .await
  224. .map(|s| s.trim() == "OK")
  225. .unwrap_or(false);
  226. if ok {
  227. let digest = run_ssh(
  228. config,
  229. node,
  230. format!(
  231. "grep -oE 'digest: sha256:[0-9a-f]+ size: [0-9]+' {log} | tail -1",
  232. log = shq(&logfile)
  233. ),
  234. false,
  235. )
  236. .await
  237. .unwrap_or_default();
  238. let digest_suffix = digest
  239. .trim()
  240. .lines()
  241. .last()
  242. .map(|d| format!(" — {d}"))
  243. .unwrap_or_default();
  244. info!(
  245. "{}{}",
  246. fluent_i18n::t!("pushed-image", {
  247. "ref" => version_ref.clone(),
  248. "latest" => latest_ref.clone(),
  249. "elapsed" => format_elapsed(elapsed)
  250. }),
  251. digest_suffix
  252. );
  253. record_published(
  254. &repo_name,
  255. &PublishedEntry {
  256. version: version.trim().to_string(),
  257. image_id,
  258. published_at: crate::stamp::utc_stamp(),
  259. },
  260. );
  261. } else {
  262. let exit_log = run_ssh(
  263. config,
  264. node,
  265. format!("tail -20 {log}", log = shq(&logfile)),
  266. false,
  267. )
  268. .await
  269. .unwrap_or_default();
  270. anyhow::bail!(
  271. "{}",
  272. fluent_i18n::t!("push-failed", {
  273. "ref" => version_ref.clone(),
  274. "node" => node.name.clone(),
  275. "elapsed" => format_elapsed(elapsed),
  276. "log" => exit_log.trim().to_string(),
  277. "host" => host.to_string()
  278. })
  279. );
  280. }
  281. return Ok(());
  282. }
  283. info!(
  284. "{}",
  285. fluent_i18n::t!("push-running", { "elapsed" => format_elapsed(elapsed) })
  286. );
  287. }
  288. }