-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcli.rs
415 lines (380 loc) · 12.6 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
//! This module provides helper methods to deal with common CLI options using the `clap` crate.
//!
//! In particular it currently supports handling two kinds of options:
//! * CRD printing
//! * Product config location
//!
//! # Example
//!
//! This example show the usage of the CRD functionality.
//!
//! ```no_run
//! // Handle CLI arguments
//! use clap::{crate_version, Parser};
//! use kube::CustomResource;
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
//! use stackable_operator::{CustomResourceExt, cli, shared::crd};
//!
//! const OPERATOR_VERSION: &str = "23.1.1";
//!
//! #[derive(Clone, CustomResource, Debug, JsonSchema, Serialize, Deserialize)]
//! #[kube(
//! group = "foo.stackable.tech",
//! version = "v1",
//! kind = "FooCluster",
//! namespaced
//! )]
//! pub struct FooClusterSpec {
//! pub name: String,
//! }
//!
//! #[derive(Clone, CustomResource, Debug, JsonSchema, Serialize, Deserialize)]
//! #[kube(
//! group = "bar.stackable.tech",
//! version = "v1",
//! kind = "BarCluster",
//! namespaced
//! )]
//! pub struct BarClusterSpec {
//! pub name: String,
//! }
//!
//! #[derive(clap::Parser)]
//! #[command(
//! name = "Foobar Operator",
//! author,
//! version,
//! about = "Stackable Operator for Foobar"
//! )]
//! struct Opts {
//! #[clap(subcommand)]
//! command: cli::Command,
//! }
//!
//! # fn main() -> Result<(), crd::Error> {
//! let opts = Opts::parse();
//!
//! match opts.command {
//! cli::Command::Crd => {
//! FooCluster::print_yaml_schema(OPERATOR_VERSION)?;
//! BarCluster::print_yaml_schema(OPERATOR_VERSION)?;
//! },
//! cli::Command::Run { .. } => {
//! // Run the operator
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Product config handling works similarly:
//!
//! ```no_run
//! use clap::{crate_version, Parser};
//! use stackable_operator::cli;
//!
//! #[derive(clap::Parser)]
//! #[command(
//! name = "Foobar Operator",
//! author,
//! version,
//! about = "Stackable Operator for Foobar"
//! )]
//! struct Opts {
//! #[clap(subcommand)]
//! command: cli::Command,
//! }
//!
//! # fn main() -> Result<(), cli::Error> {
//! let opts = Opts::parse();
//!
//! match opts.command {
//! cli::Command::Crd => {
//! // Print CRD objects
//! }
//! cli::Command::Run(cli::ProductOperatorRun { product_config, watch_namespace, .. }) => {
//! let product_config = product_config.load(&[
//! "deploy/config-spec/properties.yaml",
//! "/etc/stackable/spark-operator/config-spec/properties.yaml",
//! ])?;
//! }
//! }
//! # Ok(())
//! # }
//!
//! ```
//!
//!
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
use clap::Args;
use product_config::ProductConfigManager;
use snafu::{ResultExt, Snafu};
use stackable_telemetry::tracing::TelemetryOptions;
use crate::{namespace::WatchNamespace, utils::cluster_info::KubernetesClusterInfoOpts};
pub const AUTHOR: &str = "Stackable GmbH - [email protected]";
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, PartialEq, Snafu)]
pub enum Error {
#[snafu(display("failed to load product config"))]
ProductConfigLoad {
source: product_config::error::Error,
},
#[snafu(display(
"failed to locate a required file in any of the following locations: {search_path:?}"
))]
RequiredFileMissing { search_path: Vec<PathBuf> },
}
/// Framework-standardized commands
///
/// If you need operator-specific commands then you can flatten [`Command`] into your own command enum. For example:
/// ```rust
/// #[derive(clap::Parser)]
/// enum Command {
/// /// Print hello world message
/// Hello,
/// #[clap(flatten)]
/// Framework(stackable_operator::cli::Command)
/// }
/// ```
#[derive(clap::Parser, Debug, PartialEq, Eq)]
// The enum-level doccomment is intended for developers, not end users
// so supress it from being included in --help
#[command(long_about = "")]
pub enum Command<Run: Args = ProductOperatorRun> {
/// Print CRD objects
Crd,
/// Run operator
Run(Run),
}
/// Default parameters that all product operators take when running
///
/// Can be embedded into an extended argument set:
///
/// ```rust
/// # use stackable_operator::cli::{Command, ProductOperatorRun, ProductConfigPath};
/// use clap::Parser;
/// use stackable_operator::namespace::WatchNamespace;
/// use stackable_telemetry::tracing::TelemetryOptions;
///
/// #[derive(clap::Parser, Debug, PartialEq, Eq)]
/// struct Run {
/// #[clap(long)]
/// name: String,
/// #[clap(flatten)]
/// common: ProductOperatorRun,
/// }
///
/// let opts = Command::<Run>::parse_from(["foobar-operator", "run", "--name", "foo", "--product-config", "bar", "--watch-namespace", "foobar"]);
/// assert_eq!(opts, Command::Run(Run {
/// name: "foo".to_string(),
/// common: ProductOperatorRun {
/// product_config: ProductConfigPath::from("bar".as_ref()),
/// watch_namespace: WatchNamespace::One("foobar".to_string()),
/// telemetry_arguments: TelemetryOptions::default(),
/// cluster_info_opts: Default::default(),
/// },
/// }));
/// ```
///
/// or replaced entirely
///
/// ```rust
/// # use stackable_operator::cli::{Command, ProductOperatorRun};
/// use clap::Parser;
///
/// #[derive(clap::Parser, Debug, PartialEq, Eq)]
/// struct Run {
/// #[arg(long)]
/// name: String,
/// }
///
/// let opts = Command::<Run>::parse_from(["foobar-operator", "run", "--name", "foo"]);
/// assert_eq!(opts, Command::Run(Run {
/// name: "foo".to_string(),
/// }));
/// ```
#[derive(clap::Parser, Debug, PartialEq, Eq)]
#[command(long_about = "")]
pub struct ProductOperatorRun {
/// Provides the path to a product-config file
#[arg(long, short = 'p', value_name = "FILE", default_value = "", env)]
pub product_config: ProductConfigPath,
/// Provides a specific namespace to watch (instead of watching all namespaces)
#[arg(long, env, default_value = "")]
pub watch_namespace: WatchNamespace,
#[command(flatten)]
pub telemetry_arguments: TelemetryOptions,
#[command(flatten)]
pub cluster_info_opts: KubernetesClusterInfoOpts,
}
/// A path to a [`ProductConfigManager`] spec file
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProductConfigPath {
path: Option<PathBuf>,
}
impl From<&OsStr> for ProductConfigPath {
fn from(s: &OsStr) -> Self {
Self {
// StructOpt doesn't let us hook in to see the underlying `Option<&str>`, so we treat the
// otherwise-invalid `""` as a sentinel for using the default instead.
path: if s.is_empty() { None } else { Some(s.into()) },
}
}
}
impl ProductConfigPath {
/// Load the [`ProductConfigManager`] from the given path, falling back to the first
/// path that exists from `default_search_paths` if none is given by the user.
pub fn load(&self, default_search_paths: &[impl AsRef<Path>]) -> Result<ProductConfigManager> {
let resolved_path = Self::resolve_path(self.path.as_deref(), default_search_paths)?;
ProductConfigManager::from_yaml_file(resolved_path).context(ProductConfigLoadSnafu)
}
/// Check if the path can be found anywhere
///
/// 1. User provides path `user_provided_path` to file. Return [`Error`] if not existing.
/// 2. User does not provide path to file -> search in `default_paths` and
/// take the first existing file.
/// 3. Return [`Error`] if nothing was found.
fn resolve_path<'a>(
user_provided_path: Option<&'a Path>,
default_paths: &'a [impl AsRef<Path> + 'a],
) -> Result<&'a Path> {
// Use override if specified by the user, otherwise search through defaults given
let search_paths = if let Some(path) = user_provided_path {
vec![path]
} else {
default_paths.iter().map(|path| path.as_ref()).collect()
};
for path in &search_paths {
if path.exists() {
return Ok(path);
}
}
RequiredFileMissingSnafu {
search_path: search_paths
.into_iter()
.map(PathBuf::from)
.collect::<Vec<_>>(),
}
.fail()
}
}
#[cfg(test)]
mod tests {
use std::{env, fs::File};
use clap::Parser;
use rstest::*;
use tempfile::tempdir;
use super::*;
const USER_PROVIDED_PATH: &str = "user_provided_path_properties.yaml";
const DEPLOY_FILE_PATH: &str = "deploy_config_spec_properties.yaml";
const DEFAULT_FILE_PATH: &str = "default_file_path_properties.yaml";
const WATCH_NAMESPACE: &str = "WATCH_NAMESPACE";
#[test]
fn verify_cli() {
use clap::CommandFactory;
ProductOperatorRun::command().print_long_help().unwrap();
ProductOperatorRun::command().debug_assert()
}
#[rstest]
#[case(
Some(USER_PROVIDED_PATH),
vec![],
USER_PROVIDED_PATH,
USER_PROVIDED_PATH
)]
#[case(
None,
vec![DEPLOY_FILE_PATH, DEFAULT_FILE_PATH],
DEPLOY_FILE_PATH,
DEPLOY_FILE_PATH
)]
#[case(None, vec!["bad", DEFAULT_FILE_PATH], DEFAULT_FILE_PATH, DEFAULT_FILE_PATH)]
fn resolve_path_good(
#[case] user_provided_path: Option<&str>,
#[case] default_locations: Vec<&str>,
#[case] path_to_create: &str,
#[case] expected: &str,
) -> Result<()> {
let temp_dir = tempdir().expect("create temporary directory");
let full_path_to_create = temp_dir.path().join(path_to_create);
let full_user_provided_path = user_provided_path.map(|p| temp_dir.path().join(p));
let expected_path = temp_dir.path().join(expected);
let mut full_default_locations = vec![];
for loc in default_locations {
let temp = temp_dir.path().join(loc);
full_default_locations.push(temp.as_path().display().to_string());
}
let full_default_locations_ref = full_default_locations
.iter()
.map(String::as_str)
.collect::<Vec<_>>();
let file = File::create(full_path_to_create).expect("create temporary file");
let found_path = ProductConfigPath::resolve_path(
full_user_provided_path.as_deref(),
&full_default_locations_ref,
)?;
assert_eq!(found_path, expected_path);
drop(file);
temp_dir.close().expect("clean up temporary directory");
Ok(())
}
#[test]
#[should_panic]
fn resolve_path_user_path_not_existing() {
ProductConfigPath::resolve_path(Some(USER_PROVIDED_PATH.as_ref()), &[DEPLOY_FILE_PATH])
.unwrap();
}
#[test]
fn resolve_path_nothing_found_errors() {
if let Err(Error::RequiredFileMissing { search_path }) =
ProductConfigPath::resolve_path(None, &[DEPLOY_FILE_PATH, DEFAULT_FILE_PATH])
{
assert_eq!(search_path, vec![
PathBuf::from(DEPLOY_FILE_PATH),
PathBuf::from(DEFAULT_FILE_PATH)
])
} else {
panic!("must return RequiredFileMissing when file was not found")
}
}
#[test]
fn product_operator_run_watch_namespace() {
// clean env var to not interfere if already set
unsafe { env::remove_var(WATCH_NAMESPACE) };
// cli with namespace
let opts = ProductOperatorRun::parse_from([
"run",
"--product-config",
"bar",
"--watch-namespace",
"foo",
]);
assert_eq!(opts, ProductOperatorRun {
product_config: ProductConfigPath::from("bar".as_ref()),
watch_namespace: WatchNamespace::One("foo".to_string()),
cluster_info_opts: Default::default(),
telemetry_arguments: Default::default(),
});
// no cli / no env
let opts = ProductOperatorRun::parse_from(["run", "--product-config", "bar"]);
assert_eq!(opts, ProductOperatorRun {
product_config: ProductConfigPath::from("bar".as_ref()),
watch_namespace: WatchNamespace::All,
cluster_info_opts: Default::default(),
telemetry_arguments: Default::default(),
});
// env with namespace
unsafe { env::set_var(WATCH_NAMESPACE, "foo") };
let opts = ProductOperatorRun::parse_from(["run", "--product-config", "bar"]);
assert_eq!(opts, ProductOperatorRun {
product_config: ProductConfigPath::from("bar".as_ref()),
watch_namespace: WatchNamespace::One("foo".to_string()),
cluster_info_opts: Default::default(),
telemetry_arguments: Default::default(),
});
}
}