1use bake::{Context, Error, Result};
8use base_benchmark::{
9 ArtifactManifest, Campaign, Cancellation, Mode, PrepareRequest, Prepared, RunRequest, Suite,
10 Tree, Workspace, parse_cpus, remote::Remote, summarize_directory,
11};
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16fn workspace(context: &Context, manifest_path: Option<PathBuf>) -> Workspace {
17 Workspace::new(resolve(
18 context,
19 manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
20 ))
21}
22
23fn resolve(context: &Context, path: impl AsRef<Path>) -> PathBuf {
25 context.root().join(path)
26}
27
28fn failed(error: std::io::Error) -> Error {
29 Error::new(error.to_string())
30}
31
32fn remote(
34 host: Option<String>,
35 directory: Option<String>,
36 program: Option<String>,
37) -> Option<Remote> {
38 host.map(|host| {
39 let mut remote = Remote::new(host);
40 remote.directory = directory.unwrap_or(remote.directory);
41 remote.program = program;
42 remote
43 })
44}
45
46fn options(
48 positional: &[&str],
49 named: &[(&str, Option<String>)],
50 repeated: &[(&str, &[String])],
51) -> Vec<String> {
52 let mut arguments: Vec<String> = positional.iter().map(|value| (*value).to_owned()).collect();
53 for (name, value) in named {
54 if let Some(value) = value {
55 arguments.extend([format!("--{name}"), value.clone()]);
56 }
57 }
58 for (name, values) in repeated {
59 for value in *values {
60 arguments.extend([format!("--{name}"), value.clone()]);
61 }
62 }
63 arguments
64}
65
66fn display(path: Option<PathBuf>) -> Option<String> {
67 path.map(|path| path.display().to_string())
68}
69
70fn assignment<'a>(value: &'a str, form: &str) -> Result<(&'a str, &'a str)> {
72 value
73 .split_once('=')
74 .filter(|(name, value)| !name.is_empty() && !value.is_empty())
75 .ok_or_else(|| Error::new(format!("expected {form}, got {value:?}")))
76}
77
78fn parse_programs(values: &[String]) -> Result<BTreeMap<&str, &str>> {
80 let mut programs = BTreeMap::new();
81 for value in values {
82 let (name, path) = assignment(value, "NAME=PATH")?;
83 if programs.insert(name, path).is_some() {
84 return Err(Error::new(format!(
85 "--program {name} was given more than once"
86 )));
87 }
88 }
89 Ok(programs)
90}
91
92fn with_programs(
94 context: &Context,
95 mut workspace: Workspace,
96 programs: BTreeMap<&str, &str>,
97) -> Workspace {
98 for (name, path) in programs {
99 workspace = workspace.with_program(name, resolve(context, path));
100 }
101 workspace
102}
103
104fn parse_role_cpus(values: &[String]) -> Result<BTreeMap<String, Vec<usize>>> {
106 values
107 .iter()
108 .map(|value| {
109 let (role, cpus) = assignment(value, "ROLE=CPUS")?;
110 Ok((role.to_owned(), parse_cpus(cpus).map_err(failed)?))
111 })
112 .collect()
113}
114
115#[bake::task]
117pub fn list(
118 context: &mut Context,
119 #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
120) -> Result<Vec<Suite>> {
121 workspace(context, manifest_path).suites().map_err(failed)
122}
123
124#[bake::task]
126#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
127pub fn prepare(
128 context: &mut Context,
129 #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
130 String,
131 >,
132 #[bake(help = "LABEL=PATH source tree; repeat for each tree, baseline first.")] tree: Vec<Tree>,
133 #[bake(
134 help = "Layout replicas of the baseline to rebuild at other paths; defaults to 1 for two or more trees, otherwise 0."
135 )]
136 replicas: Option<usize>,
137 #[bake(help = "New output directory; defaults to target/base-benchmark/prepared-TIME.")] output: Option<PathBuf>,
138 #[bake(help = "Prepare only the feature sets this scenario needs; repeat for each.")] scenario: Vec<String>,
139 #[bake(
140 named,
141 default = false,
142 help = "Build every tree with this workspace's workload package."
143 )]
144 overlay: bool,
145 #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
146 #[bake(help = "Prepare on this SSH host, mirroring local paths there.")] host: Option<String>,
147 #[bake(
148 help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
149 )]
150 remote_directory: Option<String>,
151 #[bake(
152 help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
153 )]
154 remote_program: Option<String>,
155) -> Result<Prepared> {
156 let tree: Vec<Tree> = tree
157 .into_iter()
158 .map(|tree| Tree {
159 path: resolve(context, tree.path),
160 ..tree
161 })
162 .collect();
163 let output = output.map(|output| resolve(context, output));
164 let manifest_path = resolve(
165 context,
166 manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
167 );
168 if let Some(remote) = remote(host, remote_directory, remote_program) {
169 let cancellation = Cancellation::new();
171 let _signals = cancellation.on_termination_signals();
172 let trees: Vec<String> = tree
173 .iter()
174 .map(|tree| format!("{}={}", tree.label, tree.path.display()))
175 .collect();
176 return remote
177 .execute(
178 "prepare",
179 options(
180 &[],
181 &[
182 ("manifest-path", display(Some(manifest_path))),
183 ("package", package),
184 ("replicas", replicas.map(|replicas| replicas.to_string())),
185 ("output", display(output)),
186 ("overlay", Some(overlay.to_string())),
187 ],
188 &[("tree", &trees), ("scenario", &scenario)],
189 ),
190 &cancellation,
191 )
192 .and_then(|outcome| {
193 let manifest_path = outcome.output.join("artifacts.json");
195 ArtifactManifest::read(&manifest_path).map(|manifest| Prepared {
196 manifest_path,
197 manifest,
198 })
199 })
200 .map_err(failed);
201 }
202 let cancellation = Cancellation::new();
203 let _signals = cancellation.on_termination_signals();
204 Workspace::new(manifest_path)
205 .prepare(
206 PrepareRequest {
207 package,
208 trees: tree,
209 replicas,
210 output,
211 scenarios: scenario,
212 overlay,
213 },
214 &cancellation,
215 )
216 .map_err(failed)
217}
218
219#[bake::task]
221#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
222pub fn smoke(
223 context: &mut Context,
224 #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
225 String,
226 >,
227 #[bake(help = "New output directory; defaults to target/base-benchmark/smoke-TIME.")]
228 output: Option<PathBuf>,
229 #[bake(
230 help = "Host-wide lock file; defaults to /tmp/base-benchmark-host.lock. With --host, a path on the host, relative to the remote user's home."
231 )]
232 lock: Option<PathBuf>,
233 #[bake(
234 help = "NAME=PATH of an external program that a scenario's role runs; repeat for each. With --host, a path on the host, relative to the remote user's home."
235 )]
236 program: Vec<String>,
237 #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
238 #[bake(help = "Smoke on this SSH host, mirroring local paths there.")] host: Option<String>,
239 #[bake(
240 help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
241 )]
242 remote_directory: Option<String>,
243 #[bake(
244 help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
245 )]
246 remote_program: Option<String>,
247) -> Result<Vec<Campaign>> {
248 let output = output.map(|output| resolve(context, output));
249 let programs = parse_programs(&program)?;
251 if let Some(remote) = remote(host, remote_directory, remote_program) {
252 let cancellation = Cancellation::new();
254 let _signals = cancellation.on_termination_signals();
255 let manifest_path = resolve(
256 context,
257 manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
258 );
259 let scenarios: Vec<String> = Workspace::new(manifest_path.clone())
260 .suite(package.as_deref())
261 .map_err(failed)?
262 .scenarios
263 .into_iter()
264 .map(|scenario| scenario.name)
265 .collect();
266 return remote
267 .execute(
268 "smoke",
269 options(
270 &[],
271 &[
272 ("manifest-path", display(Some(manifest_path))),
273 ("package", package),
274 ("output", display(output)),
275 ("lock", display(lock)),
277 ],
278 &[("program", &program)],
280 ),
281 &cancellation,
282 )
283 .and_then(|outcome| {
284 scenarios
286 .iter()
287 .map(|scenario| summarize_directory(&outcome.output.join(scenario)))
288 .collect::<std::io::Result<Vec<_>>>()
289 })
290 .map(report_all)
291 .map_err(failed);
292 }
293 let cancellation = Cancellation::new();
294 let _signals = cancellation.on_termination_signals();
295 let lock = lock.map(|lock| resolve(context, lock));
296 let campaigns = with_programs(context, workspace(context, manifest_path), programs)
297 .smoke(
298 package.as_deref(),
299 output,
300 lock,
301 &cancellation,
302 &mut std::io::stderr(),
303 )
304 .map_err(failed)?;
305 Ok(report_all(campaigns))
306}
307
308fn report_all(campaigns: Vec<Campaign>) -> Vec<Campaign> {
310 for campaign in &campaigns {
311 eprintln!("{}\n{}", campaign.output.display(), campaign.report);
312 }
313 campaigns
314}
315
316#[bake::task]
318#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
319pub fn run(
320 context: &mut Context,
321 #[bake(help = "Scenario name.")] scenario: String,
322 #[bake(named, help = "artifacts.json from benchmark:prepare.")] artifacts: PathBuf,
323 #[bake(help = "smoke, screening, or recorded; defaults to screening.")] mode: Option<Mode>,
324 #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
325 String,
326 >,
327 #[bake(help = "Rounds; defaults to 1, 5, or 10 by mode.")] rounds: Option<u32>,
328 #[bake(
329 help = "Seed for the round order and stack padding; defaults to the clock and is recorded."
330 )]
331 seed: Option<u64>,
332 #[bake(
333 help = "CPU list for every workload process of a single-process scenario, such as 2 or 2,4-5. Required for recorded runs."
334 )]
335 cpus: Option<String>,
336 #[bake(
337 help = "ROLE=CPUS, such as server=2,3, pinning a multi-process scenario's role; repeat for each role. Recorded runs need every role placed."
338 )]
339 role_cpus: Vec<String>,
340 #[bake(
341 help = "NAME=PATH of an external program that a scenario's role runs; repeat for each. With --host, a path on the host, relative to the remote user's home."
342 )]
343 program: Vec<String>,
344 #[bake(
345 help = "Whole-process perf stat event for a single-process scenario; repeat for several."
346 )]
347 perf_event: Vec<String>,
348 #[bake(
349 help = "Seconds before a workload process, or a multi-process scenario's session, is killed; defaults to 300."
350 )]
351 timeout_seconds: Option<u64>,
352 #[bake(
353 help = "Host-wide lock file; defaults to /tmp/base-benchmark-host.lock. With --host, a path on the host, relative to the remote user's home."
354 )]
355 lock: Option<PathBuf>,
356 #[bake(help = "New output directory; defaults to target/base-benchmark/SCENARIO-MODE-TIME.")]
357 output: Option<PathBuf>,
358 #[bake(help = "The predeclared interpretation rule. Required for recorded runs.")]
359 decision_rule: Option<String>,
360 #[bake(
361 named,
362 default = false,
363 help = "Declare that the host is otherwise idle. Required for recorded runs."
364 )]
365 idle_host: bool,
366 #[bake(help = "Vary initial stack alignment per sample; defaults to true.")]
367 stack_padding: Option<bool>,
368 #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
369 #[bake(help = "Collect on this SSH host, from artifacts prepared there.")] host: Option<String>,
370 #[bake(
371 help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
372 )]
373 remote_directory: Option<String>,
374 #[bake(
375 help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
376 )]
377 remote_program: Option<String>,
378) -> Result<Campaign> {
379 let programs = parse_programs(&program)?;
381 let placement = cpus
382 .as_deref()
383 .map(parse_cpus)
384 .transpose()
385 .map_err(failed)?
386 .unwrap_or_default();
387 let role_placement = parse_role_cpus(&role_cpus)?;
388 if let Some(remote) = remote(host, remote_directory, remote_program) {
389 let cancellation = Cancellation::new();
391 let _signals = cancellation.on_termination_signals();
392 let manifest_path = resolve(
393 context,
394 manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
395 );
396 return remote
397 .execute(
398 "run",
399 options(
400 &[&scenario],
401 &[
402 ("manifest-path", display(Some(manifest_path))),
403 ("artifacts", display(Some(resolve(context, artifacts)))),
404 ("mode", mode.map(|mode| mode.to_string())),
405 ("package", package),
406 ("rounds", rounds.map(|rounds| rounds.to_string())),
407 ("seed", seed.map(|seed| seed.to_string())),
408 ("cpus", cpus),
409 (
410 "timeout-seconds",
411 timeout_seconds.map(|seconds| seconds.to_string()),
412 ),
413 ("lock", display(lock)),
415 (
416 "output",
417 display(output.map(|output| resolve(context, output))),
418 ),
419 ("decision-rule", decision_rule),
420 ("idle-host", Some(idle_host.to_string())),
421 (
422 "stack-padding",
423 stack_padding.map(|padding| padding.to_string()),
424 ),
425 ],
426 &[
428 ("role-cpus", &role_cpus),
429 ("program", &program),
430 ("perf-event", &perf_event),
431 ],
432 ),
433 &cancellation,
434 )
435 .and_then(|outcome| summarize_directory(&outcome.output))
436 .map(|campaign| report_all(vec![campaign]).remove(0))
437 .map_err(failed);
438 }
439 let request = RunRequest {
440 package,
441 mode,
442 rounds,
443 seed,
444 cpus: placement,
445 role_cpus: role_placement,
446 perf_events: perf_event,
447 timeout: timeout_seconds.map(Duration::from_secs),
448 lock: lock.map(|lock| resolve(context, lock)),
449 output: output.map(|output| resolve(context, output)),
450 decision_rule,
451 idle_host,
452 stack_padding,
453 invocation: std::env::args().collect(),
454 ..RunRequest::new(scenario, resolve(context, artifacts))
455 };
456 let cancellation = Cancellation::new();
457 let _signals = cancellation.on_termination_signals();
458 let campaign = with_programs(context, workspace(context, manifest_path), programs)
459 .run(request, &cancellation, &mut std::io::stderr())
460 .map_err(failed)?;
461 eprintln!("{}\n{}", campaign.output.display(), campaign.report);
462 Ok(campaign)
463}
464
465#[bake::task]
467pub fn summarize(
468 context: &mut Context,
469 #[bake(help = "Campaign directory.")] output: PathBuf,
470) -> Result<Campaign> {
471 let campaign = summarize_directory(&resolve(context, output)).map_err(failed)?;
472 eprintln!("{}", campaign.report);
473 Ok(campaign)
474}