| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
use crate::capability::{CapabilityDenied, CapabilitySet}; |
| 13 |
use crate::executor::{Executor, SyncOpts}; |
| 14 |
use crate::remote::{LogSink, RunOutput}; |
| 15 |
use crate::step::{Action, ObserveKind, Step}; |
| 16 |
use crate::wire::{Frame, HealthResponse, RunRequest}; |
| 17 |
use anyhow::{Context, Result}; |
| 18 |
use async_trait::async_trait; |
| 19 |
use futures_util::StreamExt; |
| 20 |
use std::path::Path; |
| 21 |
use std::time::Duration; |
| 22 |
|
| 23 |
|
| 24 |
pub struct AgentRpc { |
| 25 |
base_url: String, |
| 26 |
host_label: String, |
| 27 |
caps: CapabilitySet, |
| 28 |
client: reqwest::Client, |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
const HEALTH_TIMEOUT: Duration = Duration::from_secs(10); |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
fn install_crypto_provider() { |
| 57 |
static INSTALLED: std::sync::Once = std::sync::Once::new(); |
| 58 |
INSTALLED.call_once(|| { |
| 59 |
let _ = rustls::crypto::ring::default_provider().install_default(); |
| 60 |
}); |
| 61 |
} |
| 62 |
|
| 63 |
impl AgentRpc { |
| 64 |
|
| 65 |
|
| 66 |
pub fn new( |
| 67 |
base_url: impl Into<String>, |
| 68 |
host_label: impl Into<String>, |
| 69 |
caps: CapabilitySet, |
| 70 |
) -> Self { |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
install_crypto_provider(); |
| 77 |
let client = reqwest::Client::builder() |
| 78 |
.connect_timeout(CONNECT_TIMEOUT) |
| 79 |
.build() |
| 80 |
.expect("reqwest client with a connect timeout"); |
| 81 |
Self { |
| 82 |
base_url: base_url.into(), |
| 83 |
host_label: host_label.into(), |
| 84 |
caps, |
| 85 |
client, |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
pub async fn health(&self) -> Result<HealthResponse> { |
| 91 |
let resp = self |
| 92 |
.client |
| 93 |
.get(format!("{}/health", self.base_url)) |
| 94 |
.timeout(HEALTH_TIMEOUT) |
| 95 |
.send() |
| 96 |
.await |
| 97 |
.with_context(|| { |
| 98 |
format!( |
| 99 |
"GET /health ({}): no answer within {}s — the agent is unreachable, or it is \ |
| 100 |
accepting connections without answering them", |
| 101 |
self.host_label, |
| 102 |
HEALTH_TIMEOUT.as_secs() |
| 103 |
) |
| 104 |
})? |
| 105 |
.error_for_status() |
| 106 |
.context("agent /health status")?; |
| 107 |
resp.json().await.context("decoding /health") |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
use crate::remote::exit_status_from_code as exit_status; |
| 120 |
|
| 121 |
#[async_trait] |
| 122 |
impl Executor for AgentRpc { |
| 123 |
async fn run_streaming(&self, step: &Step, sink: &mut dyn LogSink) -> Result<RunOutput> { |
| 124 |
|
| 125 |
|
| 126 |
if !self.caps.permits(&step.action) { |
| 127 |
return Err(CapabilityDenied::new(&self.host_label, &step.action).into()); |
| 128 |
} |
| 129 |
|
| 130 |
let resp = self |
| 131 |
.client |
| 132 |
.post(format!("{}/run", self.base_url)) |
| 133 |
.json(&RunRequest { step: step.clone() }) |
| 134 |
.send() |
| 135 |
.await |
| 136 |
.context("POST /run")?; |
| 137 |
if resp.status() == reqwest::StatusCode::FORBIDDEN { |
| 138 |
let body = resp.text().await.unwrap_or_default(); |
| 139 |
anyhow::bail!("agent denied /run: {}", body.trim()); |
| 140 |
} |
| 141 |
let resp = resp.error_for_status().context("agent /run status")?; |
| 142 |
|
| 143 |
let mut stream = resp.bytes_stream(); |
| 144 |
let mut buf: Vec<u8> = Vec::new(); |
| 145 |
let mut captured: Vec<u8> = Vec::new(); |
| 146 |
let mut exit_code: Option<i32> = None; |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024; |
| 152 |
while let Some(chunk) = stream.next().await { |
| 153 |
let chunk = chunk.context("reading /run stream")?; |
| 154 |
buf.extend_from_slice(&chunk); |
| 155 |
while let Some(nl) = buf.iter().position(|&b| b == b'\n') { |
| 156 |
let line: Vec<u8> = buf.drain(..=nl).collect(); |
| 157 |
let line = &line[..line.len() - 1]; |
| 158 |
if line.is_empty() { |
| 159 |
continue; |
| 160 |
} |
| 161 |
let frame: Frame = serde_json::from_slice(line).with_context(|| { |
| 162 |
format!("decoding agent frame: {}", String::from_utf8_lossy(line)) |
| 163 |
})?; |
| 164 |
match frame { |
| 165 |
Frame::Chunk { text } => { |
| 166 |
crate::remote::push_bounded( |
| 167 |
&mut captured, |
| 168 |
text.as_bytes(), |
| 169 |
crate::remote::OUTPUT_TAIL_CAP, |
| 170 |
); |
| 171 |
sink.write_chunk(text.as_bytes()).await; |
| 172 |
} |
| 173 |
Frame::Exit { code } => exit_code = Some(code), |
| 174 |
Frame::Error { message } => anyhow::bail!("agent error: {message}"), |
| 175 |
|
| 176 |
Frame::Unknown => {} |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
anyhow::ensure!( |
| 181 |
buf.len() <= MAX_FRAME_BYTES, |
| 182 |
"agent /run frame exceeded {MAX_FRAME_BYTES} bytes without a newline", |
| 183 |
); |
| 184 |
} |
| 185 |
|
| 186 |
let code = exit_code.context("agent closed /run stream without an exit frame")?; |
| 187 |
Ok(RunOutput { |
| 188 |
status: exit_status(code), |
| 189 |
stdout: captured, |
| 190 |
stderr: Vec::new(), |
| 191 |
}) |
| 192 |
} |
| 193 |
|
| 194 |
async fn pull_file(&self, remote: &Path, local: &Path, _opts: &SyncOpts) -> Result<()> { |
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
let action = Action::Observe(ObserveKind::Artifact); |
| 201 |
if !self.caps.permits(&action) { |
| 202 |
return Err(CapabilityDenied::new(&self.host_label, &action).into()); |
| 203 |
} |
| 204 |
|
| 205 |
let resp = self |
| 206 |
.client |
| 207 |
.get(format!("{}/pull", self.base_url)) |
| 208 |
.query(&[("path", remote.to_string_lossy().as_ref())]) |
| 209 |
.send() |
| 210 |
.await |
| 211 |
.context("GET /pull")?; |
| 212 |
|
| 213 |
|
| 214 |
if resp.status() == reqwest::StatusCode::FORBIDDEN { |
| 215 |
let body = resp.text().await.unwrap_or_default(); |
| 216 |
anyhow::bail!("agent denied /pull: {}", body.trim()); |
| 217 |
} |
| 218 |
let resp = resp.error_for_status().context("agent /pull status")?; |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
if let Some(parent) = local.parent() { |
| 223 |
tokio::fs::create_dir_all(parent).await.ok(); |
| 224 |
} |
| 225 |
let mut file = tokio::fs::File::create(local) |
| 226 |
.await |
| 227 |
.context("creating pulled artifact")?; |
| 228 |
let mut stream = resp.bytes_stream(); |
| 229 |
while let Some(chunk) = stream.next().await { |
| 230 |
let chunk = chunk.context("reading /pull body")?; |
| 231 |
tokio::io::AsyncWriteExt::write_all(&mut file, &chunk) |
| 232 |
.await |
| 233 |
.context("writing pulled artifact")?; |
| 234 |
} |
| 235 |
tokio::io::AsyncWriteExt::flush(&mut file) |
| 236 |
.await |
| 237 |
.context("flushing pulled artifact")?; |
| 238 |
Ok(()) |
| 239 |
} |
| 240 |
|
| 241 |
async fn pull_dir(&self, _remote: &Path, _local: &Path, _opts: &SyncOpts) -> Result<()> { |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
anyhow::bail!( |
| 247 |
"AgentRpc::pull_dir is unsupported by design; the agent serves one file per \ |
| 248 |
/pull — use pull_file, or SshExec/rsync for a directory" |
| 249 |
) |
| 250 |
} |
| 251 |
|
| 252 |
async fn pull_glob( |
| 253 |
&self, |
| 254 |
_remote_glob: &str, |
| 255 |
_local_dir: &Path, |
| 256 |
_opts: &SyncOpts, |
| 257 |
) -> Result<()> { |
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
anyhow::bail!( |
| 262 |
"AgentRpc::pull_glob is unsupported by design; the agent serves one concrete \ |
| 263 |
path per /pull — resolve the glob on the host and use pull_file, or collect \ |
| 264 |
with SshExec/rsync" |
| 265 |
) |
| 266 |
} |
| 267 |
|
| 268 |
async fn push_dir(&self, _local: &Path, _remote: &Path, _opts: &SyncOpts) -> Result<()> { |
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
anyhow::bail!( |
| 273 |
"AgentRpc::push_dir is unsupported by design; move source/data with SshExec/rsync \ |
| 274 |
or a `git pull` step, not the agent" |
| 275 |
) |
| 276 |
} |
| 277 |
|
| 278 |
async fn preflight(&self) -> Result<()> { |
| 279 |
let health = self.health().await.with_context(|| { |
| 280 |
format!( |
| 281 |
"agent /health failed for `{}` — is ops-agent running in the Aqua session on the build host?", |
| 282 |
self.host_label, |
| 283 |
) |
| 284 |
})?; |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
anyhow::ensure!( |
| 289 |
health.version == 0 || health.version == crate::wire::PROTOCOL_VERSION, |
| 290 |
"agent `{}` speaks wire protocol v{}, but this client expects v{} — upgrade the mismatched side", |
| 291 |
self.host_label, |
| 292 |
health.version, |
| 293 |
crate::wire::PROTOCOL_VERSION, |
| 294 |
); |
| 295 |
Ok(()) |
| 296 |
} |
| 297 |
|
| 298 |
fn capabilities(&self) -> &CapabilitySet { |
| 299 |
&self.caps |
| 300 |
} |
| 301 |
} |
| 302 |
|