-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.rs
515 lines (449 loc) · 16.1 KB
/
cli.rs
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::ffi::OsString;
use crate::check_in::{CheckInConfig, CronConfig, HeartbeatConfig};
use crate::error::ErrorConfig;
use crate::log::{LogConfig, LogOrigin};
use ::log::warn;
use clap::Parser;
/// A wrapper to track the execution of arbitrary processes with AppSignal.
///
/// This wrapper allows an arbitrary process to be executed, sending its
/// standard output and standard error as logs to AppSignal, as well as
/// tracking its lifetime using heartbeat or cron check-ins.
///
/// The wrapper is transparent: it passes through standard input to the
/// executed process, it passes through the executed process's standard
/// output and standard error to its own standard output and standard error,
/// and it exits with the executed process's exit code.
#[derive(Debug, Parser)]
#[command(version)]
pub struct Cli {
/// The AppSignal *app-level* push API key.
///
/// Required unless a log source API key is provided (see `--log-source`)
/// and no check-ins are being sent (see `--cron` and `--heartbeat`)
#[arg(
long,
env = "APPSIGNAL_APP_PUSH_API_KEY",
value_name = "APP_PUSH_API_KEY",
required_unless_present = "log_source"
)]
api_key: Option<String>,
/// The log group to use to send logs.
///
/// If this option is not set, logs will be sent to the "process"
/// log group.
///
/// By default, both standard output and standard error will be sent as
/// logs. Use the --no-stdout and --no-stderr options to disable
/// sending standard output and standard error respectively, or use the
/// --no-log option to disable sending logs entirely.
#[arg(long, value_name = "GROUP")]
log: Option<String>,
/// The action name to use to group errors by.
///
/// If this option is not set, errors will not be sent to AppSignal when
/// a process exits with a non-zero exit code.
#[arg(long, value_name = "ACTION", requires = "api_key")]
error: Option<String>,
/// The log source API key to use to send logs.
///
/// If this option is not set, logs will be sent to the default
/// "application" log source for the application specified by the
/// app-level push API key.
#[arg(
long,
env = "APPSIGNAL_LOG_SOURCE_API_KEY",
value_name = "LOG_SOURCE_API_KEY"
)]
log_source: Option<String>,
/// The identifier to use to send heartbeat check-ins.
///
/// If this option is set, a heartbeat check-in will be sent two times
/// per minute.
#[arg(long, value_name = "IDENTIFIER", requires = "api_key", conflicts_with = "cron")]
heartbeat: Option<String>,
/// The identifier to use to send cron check-ins.
///
/// If this option is set, a start cron check-in will be sent when the
/// process starts, and if the wrapped process finishes with a success
/// exit code, a finish cron check-in will be sent when the process
/// finishes.
#[arg(long, value_name = "IDENTIFIER", requires = "api_key", conflicts_with = "heartbeat")]
cron: Option<String>,
/// Do not send standard output.
///
/// Do not send standard output as logs, and do not use the last
/// lines of standard output as part of the error message when
/// `--error` is set.
#[arg(long)]
no_stdout: bool,
/// Do not send standard error.
///
/// Do not send standard error as logs, and do not use the last
/// lines of standard error as part of the error message when
/// `--error` is set.
#[arg(long)]
no_stderr: bool,
/// Do not send any logs.
#[arg(long)]
no_log: bool,
/// The command to execute.
#[arg(allow_hyphen_values = true, last = true, required = true)]
pub command: Vec<String>,
/// The AppSignal public endpoint to use.
#[arg(
long,
hide = true,
env = "APPSIGNAL_PUBLIC_ENDPOINT",
value_name = "PUBLIC_ENDPOINT",
default_value = "https://appsignal-endpoint.net"
)]
endpoint: String,
/// The hostname to report when sending logs.
#[arg(
long,
env = "APPSIGNAL_HOSTNAME",
default_value = hostname(),
)]
hostname: String,
/// The digest to uniquely identify this invocation of the process.
/// Used in cron check-ins as a digest, and in logs as an attribute.
/// Unless overriden, this value is automatically set to a random value.
#[arg(
long,
hide = true,
default_value = random_digest(),
hide_default_value = true
)]
digest: String,
}
pub fn hostname() -> String {
use nix::unistd::gethostname;
gethostname()
.ok()
.and_then(|hostname| OsString::into_string(hostname).ok())
.unwrap_or_else(|| "unknown".to_string())
}
fn random_digest() -> String {
use hex::encode;
use rand::random;
encode(random::<[u8; 8]>())
}
impl Cli {
fn log_and_no_log_warning(&self) -> Option<String> {
let using: Option<&str> = if self.no_log {
Some("--no-log")
} else if self.no_stdout && self.no_stderr {
Some("--no-stdout and --no-stderr")
} else {
None
};
let alongside = if self.log.is_some() {
Some("--log")
} else if self.log_source.is_some() {
Some("--log-source")
} else {
None
};
match (using, alongside) {
(Some(using), Some(alongside)) => Some(format!(
"using {using} alongside {alongside}; \
no logs will be sent to AppSignal"
)),
_ => None,
}
}
fn no_log_and_no_data_warning(&self) -> Option<String> {
let no_checkins: bool = self.cron.is_none() && self.heartbeat.is_none();
let no_errors: bool = self.error.is_none();
if no_checkins && no_errors {
let using: Option<&str> = if self.no_log {
Some("--no-log")
} else if self.no_stdout && self.no_stderr {
Some("--no-stdout and --no-stderr")
} else {
None
};
if let Some(using) = using {
return Some(format!(
"using {using} without either --cron, --heartbeat or --error; \
no data will be sent to AppSignal"
));
}
}
None
}
fn warnings(&self) -> Vec<String> {
let mut warnings = Vec::new();
if let Some(warning) = self.log_and_no_log_warning() {
warnings.push(warning);
}
if let Some(warning) = self.no_log_and_no_data_warning() {
warnings.push(warning);
}
warnings
}
pub fn warn(&self) {
for warning in self.warnings() {
warn!("{}", warning);
}
}
pub fn cron(&self) -> Option<CronConfig> {
match (self.api_key.as_ref(), self.cron.as_ref()) {
(Some(api_key), Some(identifier)) => Some(CronConfig {
check_in: CheckInConfig {
api_key: api_key.clone(),
endpoint: self.endpoint.clone(),
identifier: identifier.clone(),
},
digest: self.digest.clone(),
}),
_ => None,
}
}
pub fn heartbeat(&self) -> Option<HeartbeatConfig> {
match (self.api_key.as_ref(), self.heartbeat.as_ref()) {
(Some(api_key), Some(identifier)) => Some(HeartbeatConfig {
check_in: CheckInConfig {
api_key: api_key.clone(),
endpoint: self.endpoint.clone(),
identifier: identifier.clone(),
},
}),
_ => None,
}
}
pub fn log(&self) -> LogConfig {
let api_key = self
.log_source
.as_ref()
.or(self.api_key.as_ref())
.unwrap()
.clone();
let endpoint = self.endpoint.clone();
let origin = self.log_origin();
let group = self.log.clone().unwrap_or_else(|| "process".to_string());
let hostname = self.hostname.clone();
let digest = self.digest.clone();
let command = self.command_as_str();
LogConfig {
api_key,
endpoint,
origin,
hostname,
group,
digest,
command,
}
}
pub fn error(&self) -> Option<ErrorConfig> {
self.error.as_ref().map(|action| {
let api_key = self.api_key.as_ref().unwrap().clone();
let endpoint = self.endpoint.clone();
let action = action.clone();
let hostname = self.hostname.clone();
let digest = self.digest.clone();
let command = self.command_as_str();
ErrorConfig {
api_key,
endpoint,
action,
hostname,
digest,
command,
}
})
}
fn log_origin(&self) -> LogOrigin {
LogOrigin::from_args(self.no_log, self.no_stdout, self.no_stderr)
}
pub fn should_pipe_stderr(&self) -> bool {
// If `--error` is set, we need to pipe stderr for the error message,
// even if we're not sending logs, unless `--no-stderr` is set.
if self.error.is_some() {
return !self.no_stderr;
}
self.log_origin().is_err()
}
pub fn should_pipe_stdout(&self) -> bool {
// If `--error` is set, we need to pipe stdout for the error message,
// even if we're not sending logs, unless `--no-stdout` is set.
if self.error.is_some() {
return !self.no_stdout;
}
self.log_origin().is_out()
}
fn command_as_str(&self) -> String {
self.command.join(" ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::package::NAME;
// These arguments are required -- without them, the CLI parser will fail.
fn with_required_args(args: Vec<&str>) -> Vec<&str> {
let first_args: Vec<&str> = vec![NAME, "--api-key", "some-api-key"];
let last_args: Vec<&str> = vec!["--", "true"];
first_args
.into_iter()
.chain(args)
.chain(last_args)
.collect()
}
#[test]
fn random_digest() {
let digest = super::random_digest();
assert!(digest.chars().all(|c| c.is_ascii_hexdigit()));
assert_eq!(digest.len(), 16);
}
#[test]
fn cli_no_warnings() {
let cli =
Cli::try_parse_from(with_required_args(vec![])).expect("failed to parse CLI arguments");
let warnings = cli.warnings();
assert!(warnings.is_empty());
}
#[test]
fn cli_warnings_log_and_no_log() {
for (args, warning) in [(
vec!["--log", "some-group", "--no-log"],
"using --no-log alongside --log; no logs will be sent to AppSignal"
),
(
vec!["--log-source", "some-log-source", "--no-log"],
"using --no-log alongside --log-source; no logs will be sent to AppSignal"
),
(
vec!["--log", "some-group", "--no-stdout", "--no-stderr"],
"using --no-stdout and --no-stderr alongside --log; no logs will be sent to AppSignal"
),
(
vec!["--log-source", "some-log-source", "--no-stdout", "--no-stderr"],
"using --no-stdout and --no-stderr alongside --log-source; no logs will be sent to AppSignal"
)] {
let cli = Cli::try_parse_from(
with_required_args(args)
).expect("failed to parse CLI arguments");
let warnings = cli.warnings();
assert!(!warnings.is_empty());
assert!(
warnings.contains(&warning.to_string()),
"actual: {warnings:?}, expected to contain: {warning:?}"
);
}
}
#[test]
fn cli_warnings_no_log_and_no_data() {
for (args, warning) in [
(
vec!["--no-log"],
Some("using --no-log without either --cron, --heartbeat or --error; no data will be sent to AppSignal")
),
(
vec!["--no-stdout", "--no-stderr"],
Some("using --no-stdout and --no-stderr without either --cron, --heartbeat or --error; no data will be sent to AppSignal")
),
(
vec!["--no-log", "--no-stdout", "--no-stderr"],
Some("using --no-log without either --cron, --heartbeat or --error; no data will be sent to AppSignal")
),
(
vec!["--no-log", "--cron", "some-cron"],
None
),
(
vec!["--no-log", "--heartbeat", "some-heartbeat"],
None
),
(
vec!["--no-log", "--error", "some-error"],
None
)
] {
let cli = Cli::try_parse_from(
with_required_args(args)
).expect("failed to parse CLI arguments");
let warnings = cli.warnings();
if let Some(warning) = warning {
assert_eq!(warnings.len(), 1);
assert_eq!(warnings[0], warning);
} else {
assert!(warnings.is_empty());
}
}
}
#[test]
fn cli_log_config() {
let cli = Cli::try_parse_from(with_required_args(vec![
"--log",
"some-group",
"--hostname",
"some-hostname",
"--digest",
"some-digest",
]))
.expect("failed to parse CLI arguments");
let log_config = cli.log();
assert_eq!(log_config.api_key, "some-api-key");
assert_eq!(log_config.endpoint, "https://appsignal-endpoint.net");
assert_eq!(log_config.origin, LogOrigin::All);
assert_eq!(log_config.group, "some-group");
assert_eq!(log_config.hostname, "some-hostname");
assert_eq!(log_config.digest, "some-digest");
}
#[test]
fn cli_log_config_no_log_options() {
for (args, origin) in [
(vec!["--no-log"], LogOrigin::None),
(vec!["--no-stdout", "--no-stderr"], LogOrigin::None),
(vec!["--no-stdout"], LogOrigin::Stderr),
(vec!["--no-stderr"], LogOrigin::Stdout),
] {
let cli = Cli::try_parse_from(with_required_args(args))
.expect("failed to parse CLI arguments");
let log_config = cli.log();
assert_eq!(log_config.origin, origin);
}
}
#[test]
fn cli_check_in_config() {
for (args, cron, heartbeat) in [
(
vec!["--cron", "some-cron", "--digest", "some-digest"],
true,
false,
),
(vec!["--heartbeat", "some-heartbeat"], false, true),
(vec![], false, false),
] {
let cli = Cli::try_parse_from(with_required_args(args))
.expect("failed to parse CLI arguments");
let cron_config = cli.cron();
let heartbeat_config = cli.heartbeat();
if cron {
let cron_config = cron_config.expect("expected cron config");
assert_eq!(cron_config.check_in.identifier, "some-cron");
assert_eq!(cron_config.check_in.api_key, "some-api-key");
assert_eq!(
cron_config.check_in.endpoint,
"https://appsignal-endpoint.net"
);
assert_eq!(cron_config.digest, "some-digest");
} else {
assert!(cron_config.is_none());
}
if heartbeat {
let heartbeat_config = heartbeat_config.expect("expected heartbeat config");
assert_eq!(heartbeat_config.check_in.identifier, "some-heartbeat");
assert_eq!(heartbeat_config.check_in.api_key, "some-api-key");
assert_eq!(
heartbeat_config.check_in.endpoint,
"https://appsignal-endpoint.net"
);
} else {
assert!(heartbeat_config.is_none());
}
}
}
}