-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelpers.rs
More file actions
321 lines (281 loc) · 9.92 KB
/
helpers.rs
File metadata and controls
321 lines (281 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use std::path::{Path, PathBuf};
use std::process::Stdio;
use anyhow::{Context, Result, bail};
use chrono::Utc;
use rand::distr;
use rand::distr::SampleString as _;
use tokio::process::Command;
use crate::types::TfVars;
// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------
/// Returns the project root directory (the git repo root).
pub fn project_root() -> Result<PathBuf> {
let output = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output()
.context("Failed to run `git rev-parse --show-toplevel`")?;
if !output.status.success() {
bail!("Not inside a git repository");
}
let root = std::str::from_utf8(&output.stdout)
.context("git output was not valid UTF-8")?
.trim();
Ok(PathBuf::from(root))
}
pub fn example_dir(provider: crate::types::CloudProvider) -> Result<PathBuf> {
let root = project_root()?;
let path = root.join(provider.dir_name()).join("examples/simple");
if !path.exists() {
bail!("Example directory does not exist: {}", path.display());
}
Ok(path)
}
pub fn runs_dir() -> Result<PathBuf> {
Ok(project_root()?.join("test/runs"))
}
pub fn test_run_dir(test_run: &str) -> Result<PathBuf> {
let path = runs_dir()?.join(test_run);
if !path.exists() {
bail!("Test run directory does not exist: {}", path.display());
}
Ok(path)
}
/// Reads the saved TfVars from a test run directory.
pub fn read_tfvars(dir: &Path) -> Result<TfVars> {
let tfvars_path = dir.join("terraform.tfvars.json");
let content = std::fs::read_to_string(&tfvars_path)
.with_context(|| format!("Failed to read {}", tfvars_path.display()))?;
serde_json::from_str(&content).context("Failed to parse terraform.tfvars.json")
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
const LIFECYCLE_FILE: &str = ".lifecycle";
pub async fn write_lifecycle(dir: &Path, phase: &str, status: &str) -> Result<()> {
let path = dir.join(LIFECYCLE_FILE);
tokio::fs::write(&path, format!("{phase} {status}\n")).await?;
Ok(())
}
// ---------------------------------------------------------------------------
// ID generation
// ---------------------------------------------------------------------------
/// A distribution that samples uniformly from a fixed set of characters.
struct Charset(&'static [u8]);
const LOWER_ALPHANUMERIC: Charset = Charset(b"0123456789abcdefghijklmnopqrstuvwxyz");
const LOWER_ALPHA: Charset = Charset(b"abcdefghijklmnopqrstuvwxyz");
impl distr::Distribution<char> for Charset {
fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> char {
self.0[rng.random_range(0..self.0.len())] as char
}
}
impl distr::SampleString for Charset {
fn append_string<R: rand::Rng + ?Sized>(&self, rng: &mut R, s: &mut String, len: usize) {
s.extend((0..len).map(|_| <Self as distr::Distribution<char>>::sample(self, rng)));
}
}
/// Generates a test run ID like `t260319-a4bc2f`.
///
/// The ID is used as `name_prefix` in terraform, which AWS constrains to
/// max 38 chars and lowercase alphanumeric + hyphens only. We use a short
/// date (YYMMDD, 6 chars) and a 6-char lowercase alphanumeric suffix
/// (last char always a letter), totalling 15 chars, leaving plenty of room
/// for AWS resource name suffixes.
pub fn generate_test_run_id() -> String {
let now = Utc::now();
let date = now.format("%y%m%d");
let mut rng = rand::rng();
let mut suffix = LOWER_ALPHANUMERIC.sample_string(&mut rng, 5);
LOWER_ALPHA.append_string(&mut rng, &mut suffix, 1);
format!("t{date}-{suffix}")
}
// ---------------------------------------------------------------------------
// Command execution
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// GitHub Actions log grouping
// ---------------------------------------------------------------------------
fn is_ci() -> bool {
std::env::var_os("CI").is_some()
}
/// Wraps an async block in GitHub Actions log grouping.
/// Outside CI this is a no-op passthrough.
pub async fn ci_log_group<F, Fut, T>(name: &str, f: F) -> Result<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
if is_ci() {
println!("::group::{name}");
}
let result = f().await;
if is_ci() {
println!("::endgroup::");
}
result
}
// ---------------------------------------------------------------------------
// Command execution
// ---------------------------------------------------------------------------
pub async fn run_cmd(cmd: &mut Command) -> Result<()> {
let status = cmd
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.await
.context("Failed to execute command")?;
if !status.success() {
bail!("Command exited with status: {}", status);
}
Ok(())
}
pub async fn run_cmd_output(cmd: &mut Command) -> Result<String> {
let output = cmd
.stderr(Stdio::inherit())
.output()
.await
.context("Failed to execute command")?;
if !output.status.success() {
bail!("Command exited with status: {}", output.status);
}
Ok(String::from_utf8(output.stdout)?.trim().to_string())
}
/// Retries an async operation until it succeeds or the maximum number of
/// attempts is exhausted. Delays `interval` between attempts. On each
/// failure the error is passed to `on_retry` for logging.
pub async fn retry<F, Fut, T>(
max_attempts: u32,
interval: std::time::Duration,
mut on_retry: impl FnMut(u32, &anyhow::Error),
mut f: F,
) -> Result<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let mut last_err = None;
for attempt in 1..=max_attempts {
match f().await {
Ok(val) => return Ok(val),
Err(e) => {
if attempt < max_attempts {
on_retry(attempt, &e);
tokio::time::sleep(interval).await;
}
last_err = Some(e);
}
}
}
Err(last_err.unwrap())
}
pub fn kubectl(kubeconfig: &Path) -> Command {
let mut cmd = Command::new("kubectl");
cmd.arg("--kubeconfig").arg(kubeconfig);
cmd
}
// ---------------------------------------------------------------------------
// S3 backend helpers
// ---------------------------------------------------------------------------
/// Parsed S3 backend configuration from a `backend.tf` file.
pub struct S3Backend {
pub bucket: String,
pub region: String,
pub profile: Option<String>,
/// The key prefix (test run ID), extracted from the state key.
pub key_prefix: String,
}
/// Reads `backend.tf` from the given directory and extracts the S3
/// configuration. Returns `None` if the file does not exist (local state).
pub fn read_s3_backend(dir: &Path) -> Result<Option<S3Backend>> {
let path = dir.join("backend.tf");
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e).context("Failed to read backend.tf"),
};
fn extract<'a>(content: &'a str, key: &str) -> Option<&'a str> {
content
.lines()
.find(|l| l.trim_start().starts_with(key))
.and_then(|l| l.split('"').nth(1))
}
let bucket = extract(&content, "bucket")
.context("backend.tf missing bucket")?
.to_string();
let region = extract(&content, "region")
.context("backend.tf missing region")?
.to_string();
let profile = extract(&content, "profile").map(|s| s.to_string());
let key = extract(&content, "key").context("backend.tf missing key")?;
let key_prefix = key
.split('/')
.next()
.context("backend.tf key has no prefix")?
.to_string();
Ok(Some(S3Backend {
bucket,
region,
profile,
key_prefix,
}))
}
/// Uploads `terraform.tfvars.json` to the S3 backend alongside the state
/// file, so that other commands or CI jobs can discover the tfvars for a
/// given test run.
pub async fn upload_tfvars_to_backend(dir: &Path) -> Result<()> {
let backend = match read_s3_backend(dir)? {
Some(b) => b,
None => return Ok(()),
};
let src = dir.join("terraform.tfvars.json");
let s3_uri = format!(
"s3://{}/{}/terraform.tfvars.json",
backend.bucket, backend.key_prefix
);
println!("Uploading terraform.tfvars.json to {s3_uri}");
let mut cmd = Command::new("aws");
cmd.args([
"s3",
"cp",
&src.display().to_string(),
&s3_uri,
"--region",
&backend.region,
]);
if let Some(profile) = &backend.profile {
cmd.args(["--profile", profile]);
}
run_cmd(&mut cmd)
.await
.context("Failed to upload terraform.tfvars.json to S3")?;
Ok(())
}
/// Deletes the remote state file and tfvars file from S3 for the given
/// test run directory. No-ops if no S3 backend is configured.
pub async fn delete_backend_state(dir: &Path) -> Result<()> {
let backend = match read_s3_backend(dir)? {
Some(b) => b,
None => return Ok(()),
};
let prefix = format!(
"s3://{}/{}/",
backend.bucket, backend.key_prefix
);
println!("Deleting remote state from {prefix}");
let mut cmd = Command::new("aws");
cmd.args([
"s3",
"rm",
&prefix,
"--recursive",
"--region",
&backend.region,
]);
if let Some(profile) = &backend.profile {
cmd.args(["--profile", profile]);
}
run_cmd(&mut cmd)
.await
.context("Failed to delete remote state from S3")?;
Ok(())
}