-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstack.rs
More file actions
417 lines (349 loc) · 14.1 KB
/
stack.rs
File metadata and controls
417 lines (349 loc) · 14.1 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
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
use std::sync::Arc;
use clap::{Args, Subcommand};
use comfy_table::{
ContentArrangement, Table,
presets::{NOTHING, UTF8_FULL},
};
use snafu::{OptionExt as _, ResultExt, Snafu, ensure};
use stackable_cockpit::{
common::list,
constants::{DEFAULT_NAMESPACE, DEFAULT_OPERATOR_NAMESPACE},
platform::{
operator::ChartSourceType,
release,
stack::{self, StackInstallParameters},
},
utils::{
k8s::{self, Client},
path::PathOrUrlParseError,
},
xfer,
};
use stackable_operator::kvp::{LabelError, Labels};
use tracing::{Span, debug, info, instrument};
use tracing_indicatif::span_ext::IndicatifSpanExt as _;
use crate::{
args::{CommonClusterArgs, CommonClusterArgsError, CommonNamespaceArgs},
cli::{Cli, OutputType},
utils::load_operator_values,
};
#[derive(Debug, Args)]
pub struct StackArgs {
#[command(subcommand)]
subcommand: StackCommands,
/// Target a specific Stackable release
#[arg(long, global = true)]
release: Option<String>,
}
#[derive(Debug, Subcommand)]
pub enum StackCommands {
/// List available stacks
#[command(alias("ls"))]
List(StackListArgs),
/// Describe a specific stack
#[command(alias("desc"))]
Describe(StackDescribeArgs),
/// Install a specific stack
#[command(aliases(["i", "in"]))]
Install(StackInstallArgs),
}
#[derive(Debug, Args)]
pub struct StackListArgs {
#[arg(short, long = "output", value_enum, default_value_t = Default::default())]
output_type: OutputType,
}
#[derive(Debug, Args)]
pub struct StackDescribeArgs {
/// Name of the stack to describe
stack_name: String,
#[arg(short, long = "output", value_enum, default_value_t = Default::default())]
output_type: OutputType,
}
#[derive(Debug, Args)]
pub struct StackInstallArgs {
/// Name of the stack to describe
stack_name: String,
/// Skip the installation of the release during the stack install process
#[arg(
long,
long_help = "Skip the installation of the release during the stack install process
Use \"stackablectl operator install [OPTIONS] <OPERATORS>...\" to install
required operators manually. Operators MUST be installed in the correct version.
Use \"stackablectl operator install --help\" to display more information on how
to specify operator versions."
)]
skip_release: bool,
/// List of parameters to use when installing the stack
#[arg(long)]
stack_parameters: Vec<String>,
/// List of parameters to use when installing the stack
#[arg(long)]
#[arg(long_help = "List of parameters to use when installing the stack
All parameters must have the format '<parameter>=<value>'. Multiple parameters
can be specified and are space separated. Valid parameters are:
- adminPassword=admin123
- adminUser=superuser
- 'endpoint=https://example.com port=1234'
Use \"stackablectl stack describe <STACK>\" to list available parameters for each stack.")]
parameters: Vec<String>,
#[command(flatten)]
local_cluster: CommonClusterArgs,
#[command(flatten)]
namespaces: CommonNamespaceArgs,
}
#[derive(Debug, Snafu)]
pub enum CmdError {
#[snafu(display("path/url parse error"))]
PathOrUrlParse { source: PathOrUrlParseError },
#[snafu(display("failed to serialize YAML output"))]
SerializeYamlOutput { source: serde_yaml::Error },
#[snafu(display("failed to serialize JSON output"))]
SerializeJsonOutput { source: serde_json::Error },
#[snafu(display("no release {release:?}"))]
NoSuchRelease { release: String },
#[snafu(display("failed to get latest release"))]
LatestRelease,
#[snafu(display("failed to build stack/release list"))]
BuildList { source: list::Error },
#[snafu(display("failed to install local cluster"))]
InstallCluster { source: CommonClusterArgsError },
#[snafu(display("failed to install stack {stack_name:?}"))]
InstallStack {
#[snafu(source(from(stack::Error, Box::new)))]
source: Box<stack::Error>,
stack_name: String,
},
#[snafu(display("failed to build labels for stack resources"))]
BuildLabels { source: LabelError },
#[snafu(display("failed to create Kubernetes client"))]
KubeClientCreate {
#[snafu(source(from(k8s::Error, Box::new)))]
source: Box<k8s::Error>,
},
#[snafu(display("failed to load operator values"))]
LoadOperatorValues { source: crate::utils::Error },
}
impl StackArgs {
pub async fn run(
&self,
cli: &Cli,
transfer_client: Arc<xfer::Client>,
) -> Result<String, CmdError> {
debug!("Handle stack args");
let release_files = cli.get_release_files().context(PathOrUrlParseSnafu)?;
let release_list = release::ReleaseList::build(&release_files, &transfer_client)
.await
.context(BuildListSnafu)?;
let release_branch = match &self.release {
Some(release) => {
ensure!(
release_list.contains_key(release),
NoSuchReleaseSnafu { release }
);
if release == "dev" {
"main".to_string()
} else {
format!("release-{release}")
}
}
None => {
let (release_name, _) = release_list.first().context(LatestReleaseSnafu)?;
format!("release-{release_name}")
}
};
let files = cli
.get_stack_files(&release_branch)
.context(PathOrUrlParseSnafu)?;
let stack_list = stack::StackList::build(&files, &transfer_client)
.await
.context(BuildListSnafu)?;
match &self.subcommand {
StackCommands::List(args) => list_cmd(args, stack_list),
StackCommands::Describe(args) => describe_cmd(args, stack_list),
StackCommands::Install(args) => {
install_cmd(args, cli, stack_list, &transfer_client).await
}
}
}
}
#[instrument(skip_all, fields(indicatif.pb_show = true))]
fn list_cmd(args: &StackListArgs, stack_list: stack::StackList) -> Result<String, CmdError> {
info!("Listing stacks");
Span::current().pb_set_message("Fetching stack information");
match args.output_type {
OutputType::Plain | OutputType::Table => {
let (arrangement, preset) = match args.output_type {
OutputType::Plain => (ContentArrangement::Disabled, NOTHING),
_ => (ContentArrangement::Dynamic, UTF8_FULL),
};
let mut table = Table::new();
table
.set_header(vec!["#", "STACK", "RELEASE", "DESCRIPTION"])
.set_content_arrangement(arrangement)
.load_preset(preset);
for (index, (stack_name, stack)) in stack_list.iter().enumerate() {
table.add_row(vec![
(index + 1).to_string(),
stack_name.clone(),
stack.release.clone(),
stack.description.clone(),
]);
}
let mut result = Cli::result();
result
.with_command_hint(
"stackablectl stack describe [OPTIONS] <STACK>",
"display further information for the specified stack",
)
.with_command_hint(
"stackablectl stack install [OPTIONS] <STACK>...",
"install a stack",
)
.with_output(table.to_string());
Ok(result.render())
}
OutputType::Json => serde_json::to_string(&stack_list).context(SerializeJsonOutputSnafu),
OutputType::Yaml => serde_yaml::to_string(&stack_list).context(SerializeYamlOutputSnafu),
}
}
#[instrument(skip_all, fields(indicatif.pb_show = true))]
fn describe_cmd(
args: &StackDescribeArgs,
stack_list: stack::StackList,
) -> Result<String, CmdError> {
info!(stack_name = %args.stack_name, "Describing stack");
Span::current().pb_set_message("Fetching stack information");
match stack_list.get(&args.stack_name) {
Some(stack) => match args.output_type {
OutputType::Plain | OutputType::Table => {
let arrangement = match args.output_type {
OutputType::Plain => ContentArrangement::Disabled,
_ => ContentArrangement::Dynamic,
};
let mut table = Table::new();
let mut parameter_table = Table::new();
parameter_table
.set_header(vec!["NAME", "DESCRIPTION", "DEFAULT VALUE"])
.set_content_arrangement(arrangement.clone())
.load_preset(NOTHING);
for parameter in &stack.parameters {
parameter_table.add_row(vec![
parameter.name.clone(),
parameter.description.clone(),
parameter.default.clone(),
]);
}
table
.set_content_arrangement(arrangement)
.load_preset(NOTHING)
.add_row(vec!["STACK", args.stack_name.as_str()])
.add_row(vec!["DESCRIPTION", stack.description.as_str()])
.add_row(vec!["RELEASE", stack.release.as_str()])
.add_row(vec!["OPERATORS", stack.operators.join(", ").as_str()])
.add_row(vec!["LABELS", stack.labels.join(", ").as_str()])
.add_row(vec!["PARAMETERS", parameter_table.to_string().as_str()]);
let mut result = Cli::result();
result
.with_command_hint(
format!(
"stackablectl stack install {stack_name}",
stack_name = args.stack_name
),
"install the stack",
)
.with_command_hint("stackablectl stack list", "list all available stacks")
.with_output(table.to_string());
Ok(result.render())
}
OutputType::Json => serde_json::to_string(&stack).context(SerializeJsonOutputSnafu),
OutputType::Yaml => serde_yaml::to_string(&stack).context(SerializeYamlOutputSnafu),
},
None => Ok("No such stack".into()),
}
}
#[instrument(skip(cli, stack_list, transfer_client), fields(indicatif.pb_show = true))]
async fn install_cmd(
args: &StackInstallArgs,
cli: &Cli,
stack_list: stack::StackList,
transfer_client: &xfer::Client,
) -> Result<String, CmdError> {
info!(stack_name = %args.stack_name, "Installing stack");
Span::current().pb_set_message("Installing stack");
let files = cli.get_release_files().context(PathOrUrlParseSnafu)?;
let release_list = release::ReleaseList::build(&files, transfer_client)
.await
.context(BuildListSnafu)?;
match stack_list.get(&args.stack_name) {
Some(stack_spec) => {
let mut output = Cli::result();
// Install local cluster if needed
args.local_cluster
.install_if_needed()
.await
.context(InstallClusterSnafu)?;
let client = Client::new().await.context(KubeClientCreateSnafu)?;
// Construct labels which get attached to all dynamic objects which
// are part of the stack.
let labels = Labels::try_from([
("stackable.tech/managed-by", "stackablectl"),
("stackable.tech/stack", &args.stack_name),
("stackable.tech/vendor", "Stackable"),
])
.context(BuildLabelsSnafu)?;
let values_file = cli.get_values_file().context(PathOrUrlParseSnafu)?;
let operator_values = load_operator_values(values_file.as_ref(), transfer_client)
.await
.context(LoadOperatorValuesSnafu)?;
let install_parameters = StackInstallParameters {
stack_name: args.stack_name.clone(),
// There is no demo when installing only a stack
demo_name: None,
operator_namespace: args.namespaces.operator_namespace.clone(),
stack_namespace: args.namespaces.namespace.clone(),
parameters: args.parameters.clone(),
skip_release: args.skip_release,
labels,
chart_source: ChartSourceType::from(cli.chart_type()),
operator_values,
};
stack_spec
.install(release_list, install_parameters, &client, transfer_client)
.await
.context(InstallStackSnafu {
stack_name: args.stack_name.clone(),
})?;
let operator_cmd = format!(
"stackablectl operator installed{option}",
option = if args.namespaces.operator_namespace != DEFAULT_OPERATOR_NAMESPACE {
format!(
" --operator-namespace {namespace}",
namespace = args.namespaces.operator_namespace
)
} else {
"".into()
}
);
let stacklet_cmd = format!(
"stackablectl stacklet list{option}",
option = if args.namespaces.namespace != DEFAULT_NAMESPACE {
format!(
" --namespace {namespace}",
namespace = args.namespaces.namespace
)
} else {
"".into()
}
);
output
.with_command_hint(operator_cmd, "display the installed operators")
.with_command_hint(stacklet_cmd, "display the installed stacklets")
.with_output(format!(
"Installed stack {stack_name:?}",
stack_name = args.stack_name
));
Ok(output.render())
}
None => Ok("No such stack".into()),
}
}