-
Notifications
You must be signed in to change notification settings - Fork 626
Expand file tree
/
Copy pathrun.rs
More file actions
5460 lines (4914 loc) · 177 KB
/
run.rs
File metadata and controls
5460 lines (4914 loc) · 177 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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! CLI command implementations.
use crate::tls::{
TlsOptions, build_rustls_config, grpc_client, grpc_inference_client, require_tls_materials,
};
use bytes::Bytes;
use dialoguer::{Confirm, Select, theme::ColorfulTheme};
use futures::StreamExt;
use http_body_util::Full;
use hyper::{Request, StatusCode};
use hyper_rustls::HttpsConnectorBuilder;
use hyper_util::{client::legacy::Client, rt::TokioExecutor};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use miette::{IntoDiagnostic, Result, WrapErr};
use openshell_bootstrap::{
DeployOptions, GatewayMetadata, RemoteOptions, clear_active_gateway, container_name,
extract_host_from_ssh_destination, get_gateway_metadata, list_gateways, load_active_gateway,
remove_gateway_metadata, resolve_ssh_hostname, save_active_gateway, save_last_sandbox,
store_gateway_metadata,
};
use openshell_core::proto::{
ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, ClearDraftChunksRequest,
CreateProviderRequest, CreateSandboxRequest, DeleteProviderRequest, DeleteSandboxRequest,
GetClusterInferenceRequest, GetDraftHistoryRequest, GetDraftPolicyRequest,
GetGatewayConfigRequest, GetProviderRequest, GetSandboxConfigRequest, GetSandboxLogsRequest,
GetSandboxPolicyStatusRequest, GetSandboxRequest, HealthRequest, ListProvidersRequest,
ListSandboxPoliciesRequest, ListSandboxesRequest, PolicyStatus, Provider,
RejectDraftChunkRequest, Sandbox, SandboxPhase, SandboxPolicy, SandboxSpec, SandboxTemplate,
SetClusterInferenceRequest, SettingScope, SettingValue, UpdateConfigRequest,
UpdateProviderRequest, WatchSandboxRequest, setting_value,
};
use openshell_core::settings::{self, SettingValueKind};
use openshell_providers::{
ProviderRegistry, detect_provider_from_command, normalize_provider_type,
};
use owo_colors::OwoColorize;
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
use tonic::{Code, Status};
// Re-export SSH functions for backward compatibility
pub use crate::ssh::{Editor, print_ssh_config};
pub use crate::ssh::{
sandbox_connect, sandbox_connect_editor, sandbox_exec, sandbox_forward, sandbox_ssh_proxy,
sandbox_ssh_proxy_by_name, sandbox_sync_down, sandbox_sync_up, sandbox_sync_up_files,
};
pub use openshell_core::forward::{
find_forward_by_port, list_forwards, stop_forward, stop_forwards_for_sandbox,
};
/// Convert a sandbox phase integer to a human-readable string.
fn phase_name(phase: i32) -> &'static str {
match SandboxPhase::try_from(phase) {
Ok(SandboxPhase::Unspecified) => "Unspecified",
Ok(SandboxPhase::Provisioning) => "Provisioning",
Ok(SandboxPhase::Ready) => "Ready",
Ok(SandboxPhase::Error) => "Error",
Ok(SandboxPhase::Deleting) => "Deleting",
Ok(SandboxPhase::Unknown) | Err(_) => "Unknown",
}
}
fn ready_false_condition_message(
status: Option<&openshell_core::proto::SandboxStatus>,
) -> Option<String> {
let condition = status?.conditions.iter().find(|condition| {
condition.r#type == "Ready" && condition.status.eq_ignore_ascii_case("false")
})?;
if condition.message.is_empty() {
if condition.reason.is_empty() {
None
} else {
Some(condition.reason.clone())
}
} else if condition.reason.is_empty() {
Some(condition.message.clone())
} else {
Some(format!("{}: {}", condition.reason, condition.message))
}
}
fn provisioning_timeout_message(
timeout_secs: u64,
requested_gpu: bool,
condition_message: Option<&str>,
) -> String {
let mut message = format!("sandbox provisioning timed out after {timeout_secs}s");
if let Some(condition_message) = condition_message.filter(|msg| !msg.is_empty()) {
message.push_str(". Last reported status: ");
message.push_str(condition_message);
}
if requested_gpu {
message.push_str(
". Hint: this may be because the available GPU is already in use by another sandbox.",
);
}
message
}
/// Format milliseconds since Unix epoch as a `YYYY-MM-DD HH:MM:SS` UTC string.
fn format_epoch_ms(ms: i64) -> String {
use std::time::UNIX_EPOCH;
let Ok(ms_u64) = u64::try_from(ms) else {
return "-".to_string();
};
let Ok(time) = UNIX_EPOCH
.checked_add(Duration::from_millis(ms_u64))
.ok_or(())
else {
return "-".to_string();
};
let Ok(dur) = time.duration_since(UNIX_EPOCH) else {
return "-".to_string();
};
let secs = dur.as_secs();
let days = secs / 86400;
let time_of_day = secs % 86400;
let hours = time_of_day / 3600;
let minutes = (time_of_day % 3600) / 60;
let seconds = time_of_day % 60;
// Convert days since epoch to year-month-day using a basic civil calendar algorithm.
let (y, m, d) = civil_from_days(days);
format!("{y:04}-{m:02}-{d:02} {hours:02}:{minutes:02}:{seconds:02}")
}
/// Convert days since 1970-01-01 to (year, month, day).
/// Algorithm from Howard Hinnant's `chrono`-compatible date library.
fn civil_from_days(days: u64) -> (i64, u64, u64) {
let z = days.cast_signed() + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097).cast_unsigned();
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe.cast_signed() + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
(y, m, d)
}
/// Known provisioning steps derived from Kubernetes events and sandbox lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum ProvisioningStep {
/// Sandbox CRD created, waiting for pod to be scheduled.
RequestingSandbox,
/// Pulling the sandbox container image.
PullingSandboxImage,
/// Container is starting up.
StartingSandbox,
}
impl ProvisioningStep {
/// Human-readable label for a completed step.
fn completed_label(self) -> &'static str {
match self {
Self::RequestingSandbox => "Sandbox allocated",
Self::PullingSandboxImage => "Image pulled",
Self::StartingSandbox => "Sandbox ready",
}
}
/// Human-readable label for an in-progress step (shown on the spinner).
fn active_label(self) -> &'static str {
match self {
Self::RequestingSandbox => "Requesting sandbox...",
Self::PullingSandboxImage => "Pulling image...",
Self::StartingSandbox => "Starting sandbox...",
}
}
}
/// Kubernetes event reason codes we care about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KubeEventReason {
Scheduled,
Pulling,
Pulled,
Started,
}
/// Map a Kubernetes event reason string to an enum.
fn parse_kube_event_reason(reason: &str) -> Option<KubeEventReason> {
match reason {
"Scheduled" => Some(KubeEventReason::Scheduled),
"Pulling" => Some(KubeEventReason::Pulling),
"Pulled" => Some(KubeEventReason::Pulled),
"Started" => Some(KubeEventReason::Started),
_ => None,
}
}
/// Live-updating display showing a provisioning step checklist with spinner.
///
/// Completed steps are printed as static `✓ Step` lines. The current
/// in-progress step is shown on a spinner with elapsed time.
struct ProvisioningDisplay {
mp: MultiProgress,
spinner: ProgressBar,
/// Blank line below the spinner so progress doesn't sit flush against
/// the bottom of the terminal.
spacer: ProgressBar,
/// Steps that have been completed, in order.
completed_steps: Vec<ProvisioningStep>,
/// Progress bars for completed steps (so they can be cleared).
completed_bars: Vec<ProgressBar>,
/// The currently active step label (shown on the spinner).
active_label: String,
/// Detail text shown next to the active step (e.g. image name).
active_detail: String,
/// When the current active step started (for elapsed time).
step_start: Instant,
}
impl ProvisioningDisplay {
fn new() -> Self {
let mp = MultiProgress::new();
let spinner = mp.add(ProgressBar::new_spinner());
spinner.set_style(
ProgressStyle::with_template("{spinner:.cyan} {msg} ({elapsed})")
.unwrap_or_else(|_| ProgressStyle::default_spinner()),
);
spinner.enable_steady_tick(Duration::from_millis(120));
// Always keep a blank line below the spinner so the progress area
// doesn't sit flush against the bottom of the terminal.
let spacer = mp.add(ProgressBar::new(0));
spacer.set_style(
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()),
);
spacer.set_message("");
let now = Instant::now();
Self {
mp,
spinner,
spacer,
completed_steps: Vec::new(),
completed_bars: Vec::new(),
active_label: ProvisioningStep::RequestingSandbox
.active_label()
.to_string(),
active_detail: String::new(),
step_start: now,
}
}
/// Record a completed provisioning step.
///
/// The step is printed as a static `✓` line and the spinner advances
/// to the next expected state.
fn complete_step(&mut self, step: ProvisioningStep) {
self.complete_step_with_label(step, step.completed_label());
}
/// Record a completed provisioning step with a custom label.
fn complete_step_with_label(&mut self, step: ProvisioningStep, label: &str) {
// Don't duplicate steps we've already printed.
if self.completed_steps.contains(&step) {
return;
}
self.completed_steps.push(step);
let elapsed = self.step_start.elapsed();
let elapsed_str = format_elapsed(elapsed);
// Use a progress bar instead of println so we can clear it later.
let bar = self.mp.insert_before(&self.spinner, ProgressBar::new(0));
bar.set_style(
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()),
);
bar.set_message(format!(
"{} {} {}",
"\u{2713}".green().bold(),
label,
elapsed_str.dimmed()
));
bar.finish();
self.completed_bars.push(bar);
// Reset step timer for the next step.
self.step_start = Instant::now();
self.spinner.reset_elapsed();
self.active_detail.clear();
}
/// Set the active (in-progress) step shown on the spinner.
fn set_active(&mut self, label: &str) {
self.active_label = label.to_string();
self.active_detail.clear();
// Reset the spinner's elapsed time for the new step.
self.spinner.reset_elapsed();
self.step_start = Instant::now();
self.update_spinner();
}
/// Set the active step from a known provisioning step enum.
fn set_active_step(&mut self, step: ProvisioningStep) {
self.set_active(step.active_label());
}
/// Set detail text shown alongside the active step (e.g. image name).
fn set_active_detail(&mut self, detail: &str) {
self.active_detail = detail.to_string();
self.update_spinner();
}
fn update_spinner(&self) {
let msg = if self.active_detail.is_empty() {
self.active_label.clone()
} else {
format!("{} {}", self.active_label, self.active_detail.dimmed())
};
self.spinner.set_message(msg);
}
/// Finish with an error message shown on the last step line.
fn finish_error(&self, msg: &str) {
let _ = self
.mp
.println(format!("{} {}", "\u{2717}".red().bold(), msg.red()));
self.spinner.finish_and_clear();
}
/// Print a line above the progress bars (for static header content).
fn println(&self, msg: &str) {
let _ = self.mp.println(msg);
}
/// Clear all progress output (spinner, spacer, and completed step lines).
fn clear(&mut self) {
self.spacer.finish_and_clear();
self.spinner.finish_and_clear();
for bar in &self.completed_bars {
bar.finish_and_clear();
}
}
}
/// Format a duration as a compact elapsed time string, e.g. `(3s)` or `(1m 12s)`.
fn format_elapsed(d: Duration) -> String {
let secs = d.as_secs();
if secs < 60 {
format!("({secs}s)")
} else {
let mins = secs / 60;
let rem = secs % 60;
format!("({mins}m {rem}s)")
}
}
/// Format a total elapsed time for non-interactive mode timestamps.
fn format_timestamp(d: Duration) -> String {
let secs = d.as_secs_f64();
format!("[{secs:.1}s]")
}
/// Extract image size in bytes from a Kubernetes Pulled event message.
/// Example: "Successfully pulled image ... Image size: 620405524 bytes."
fn extract_image_size(message: &str) -> Option<u64> {
let size_prefix = "Image size: ";
let start = message.find(size_prefix)? + size_prefix.len();
let rest = &message[start..];
let end = rest.find(' ')?;
rest[..end].parse().ok()
}
/// Format bytes as a human-readable string (e.g., "620 MB").
fn format_bytes(bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if bytes >= GB {
format!("{:.1} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{} MB", bytes / MB)
} else if bytes >= KB {
format!("{} KB", bytes / KB)
} else {
format!("{} B", bytes)
}
}
fn print_sandbox_header(sandbox: &Sandbox, display: Option<&ProvisioningDisplay>) {
let lines = [
String::new(),
format!(
"{} {}",
"Created sandbox:".cyan().bold(),
sandbox.name.bold()
),
String::new(),
];
match display {
Some(d) => {
for line in lines {
d.println(&line);
}
}
None => {
for line in lines {
println!("{line}");
}
}
}
}
const CLUSTER_DEPLOY_LOG_LINES: usize = 15;
/// Return the current terminal width, falling back to 80 columns.
fn term_width() -> usize {
crossterm::terminal::size()
.map(|(w, _)| w as usize)
.unwrap_or(80)
}
/// Build a horizontal rule of `─` characters with an optional centered label.
fn horizontal_rule(label: Option<&str>, width: usize) -> String {
match label {
Some(text) => {
let text_with_pad = format!(" {text} ");
let text_len = text_with_pad.len();
if width <= text_len {
return text_with_pad;
}
let remaining = width - text_len;
let left = remaining / 2;
let right = remaining - left;
format!("{}{}{}", "─".repeat(left), text_with_pad, "─".repeat(right),)
}
None => "─".repeat(width),
}
}
/// Truncate a string to fit within the given column width.
///
/// If the string is longer than `max_width`, it is cut and an ellipsis (`…`)
/// is appended so the total visible width equals `max_width`.
fn truncate_to_width(s: &str, max_width: usize) -> String {
if max_width == 0 {
return String::new();
}
// Fast path: ASCII-only check via byte length (covers the vast majority of log lines).
if s.len() <= max_width {
return s.to_string();
}
// The string is longer than the budget. We need to truncate.
// Walk by chars to handle multi-byte UTF-8 correctly.
let mut end = 0;
for (count, (idx, ch)) in s.char_indices().enumerate() {
if count + 1 > max_width.saturating_sub(1) {
break;
}
end = idx + ch.len_utf8();
}
format!("{}…", &s[..end])
}
struct GatewayDeployLogPanel {
mp: MultiProgress,
status: String,
progress: Option<String>,
current_step: Option<String>,
spinner: ProgressBar,
/// Blank line below the spinner so progress doesn't sit flush against the
/// bottom of the terminal.
spacer: ProgressBar,
completed_steps: Vec<ProgressBar>,
top_border: Option<ProgressBar>,
log_lines: Vec<ProgressBar>,
bottom_border: Option<ProgressBar>,
buffer: VecDeque<String>,
}
impl GatewayDeployLogPanel {
fn new(_name: &str, _location: &str) -> Self {
let mp = MultiProgress::new();
let spinner = mp.add(ProgressBar::new_spinner());
spinner.set_style(
ProgressStyle::with_template("{spinner:.cyan} {msg}")
.unwrap_or_else(|_| ProgressStyle::default_spinner()),
);
spinner.enable_steady_tick(Duration::from_millis(120));
// Keep a blank line below the spinner so it doesn't sit flush
// against the bottom of the terminal.
let spacer = mp.add(ProgressBar::new(0));
spacer.set_style(
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar()),
);
spacer.set_message("");
let panel = Self {
mp,
status: "Starting".to_string(),
progress: None,
current_step: None,
spinner,
spacer,
completed_steps: Vec::new(),
top_border: None,
log_lines: Vec::with_capacity(CLUSTER_DEPLOY_LOG_LINES),
bottom_border: None,
buffer: VecDeque::with_capacity(CLUSTER_DEPLOY_LOG_LINES),
};
panel.update_spinner_message();
panel
}
fn push_log(&mut self, line: String) {
let line = line.trim().to_string();
if line.is_empty() {
return;
}
if let Some(status) = line.strip_prefix("[status] ") {
self.handle_status(status.to_string());
return;
}
if let Some(detail) = line.strip_prefix("[progress] ") {
self.handle_progress(detail.to_string());
return;
}
self.ensure_log_panel();
if self.buffer.len() == CLUSTER_DEPLOY_LOG_LINES {
self.buffer.pop_front();
}
self.buffer.push_back(line);
self.render();
}
fn handle_status(&mut self, status: String) {
if is_progress_status(&status) {
self.handle_progress(status);
return;
}
if let Some(previous_step) = self.current_step.replace(status.clone()) {
self.push_completed_step(&previous_step, true);
}
self.status = status;
self.progress = None;
self.update_spinner_message();
}
fn handle_progress(&mut self, detail: String) {
self.progress = Some(detail);
self.update_spinner_message();
}
fn ensure_log_panel(&mut self) {
if self.top_border.is_some() {
return;
}
let line_style =
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar());
let width = term_width();
let top_border = self.mp.add(ProgressBar::new(0));
top_border.set_style(line_style.clone());
top_border.set_message(
horizontal_rule(Some("Gateway Logs"), width)
.cyan()
.to_string(),
);
for _ in 0..CLUSTER_DEPLOY_LOG_LINES {
let line = self.mp.add(ProgressBar::new(0));
line.set_style(line_style.clone());
line.set_message(String::new());
self.log_lines.push(line);
}
let bottom_border = self.mp.add(ProgressBar::new(0));
bottom_border.set_style(line_style);
bottom_border.set_message(horizontal_rule(None, width).cyan().to_string());
self.top_border = Some(top_border);
self.bottom_border = Some(bottom_border);
}
fn push_completed_step(&mut self, step: &str, success: bool) {
if step.is_empty() {
return;
}
let symbol = if success {
"✓".green().bold().to_string()
} else {
"x".red().bold().to_string()
};
let line_style =
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar());
let bar = self.mp.insert_before(&self.spinner, ProgressBar::new(0));
bar.set_style(line_style);
bar.set_message(format!("{symbol} {step}"));
self.completed_steps.push(bar);
}
fn update_spinner_message(&self) {
let msg = if let Some(detail) = &self.progress {
format!("{} ({})", self.status, detail.dimmed())
} else {
self.status.clone()
};
self.spinner.set_message(msg);
}
fn finish_success(&mut self) {
if let Some(step) = self.current_step.take() {
self.push_completed_step(&step, true);
}
// Keep completed step checkmarks visible, clear the log panel.
for bar in &self.completed_steps {
bar.finish();
}
self.clear_log_panel();
self.spinner.finish_and_clear();
self.spacer.finish_and_clear();
}
fn finish_failure(&mut self) {
if let Some(step) = self.current_step.take() {
self.push_completed_step(&step, false);
}
// On failure, preserve everything (including logs) for debugging.
for bar in &self.completed_steps {
bar.finish();
}
if let Some(top_border) = &self.top_border {
top_border.finish();
}
for bar in &self.log_lines {
bar.finish();
}
if let Some(bottom_border) = &self.bottom_border {
bottom_border.finish();
}
self.spinner.finish_and_clear();
self.spacer.finish_and_clear();
}
/// Clear the container log panel from the terminal output.
fn clear_log_panel(&self) {
if let Some(top_border) = &self.top_border {
top_border.finish_and_clear();
}
for bar in &self.log_lines {
bar.finish_and_clear();
}
if let Some(bottom_border) = &self.bottom_border {
bottom_border.finish_and_clear();
}
}
fn render(&self) {
let width = term_width();
for (idx, bar) in self.log_lines.iter().enumerate() {
let line = self.buffer.get(idx).map(String::as_str).unwrap_or_default();
bar.set_message(truncate_to_width(line, width));
}
}
}
fn is_progress_status(status: &str) -> bool {
status.starts_with("Exported ")
|| status.starts_with("Downloading:")
|| status.starts_with("Extracting:")
}
/// Show gateway status.
#[allow(clippy::branches_sharing_code)]
pub async fn gateway_status(gateway_name: &str, server: &str, tls: &TlsOptions) -> Result<()> {
println!("{}", "Server Status".cyan().bold());
println!();
println!(" {} {}", "Gateway:".dimmed(), gateway_name);
println!(" {} {}", "Server:".dimmed(), server);
if tls.is_bearer_auth() {
println!(" {} Edge (bearer token)", "Auth:".dimmed());
}
// Try to connect and get health
match grpc_client(server, tls).await {
Ok(mut client) => match client.health(HealthRequest {}).await {
Ok(response) => {
let health = response.into_inner();
println!(" {} {}", "Status:".dimmed(), "Connected".green());
println!(" {} {}", "Version:".dimmed(), health.version);
}
Err(e) => {
if let Some(status) = http_health_check(server, tls).await? {
if status.is_success() {
println!(" {} {}", "Status:".dimmed(), "Connected (HTTP)".yellow());
println!(" {} {}", "HTTP: ".dimmed(), status);
println!(" {} {}", "gRPC error:".dimmed(), e);
} else {
println!(" {} {}", "Status:".dimmed(), "Error".red());
println!(" {} {}", "HTTP:".dimmed(), status);
println!(" {} {}", "gRPC error:".dimmed(), e);
}
} else {
println!(" {} {}", "Status:".dimmed(), "Error".red());
println!(" {} {}", "Error:".dimmed(), e);
}
}
},
Err(e) => {
if let Some(status) = http_health_check(server, tls).await? {
if status.is_success() {
println!(" {} {}", "Status:".dimmed(), "Connected (HTTP)".yellow());
println!(" {} {}", "HTTP:".dimmed(), status);
println!(" {} {}", "gRPC error:".dimmed(), e);
} else {
println!(" {} {}", "Status:".dimmed(), "Disconnected".red());
println!(" {} {}", "HTTP:".dimmed(), status);
println!(" {} {}", "Error:".dimmed(), e);
}
} else {
println!(" {} {}", "Status:".dimmed(), "Disconnected".red());
println!(" {} {}", "Error:".dimmed(), e);
}
}
}
Ok(())
}
/// Set the active gateway.
pub fn gateway_use(name: &str) -> Result<()> {
// Verify the gateway exists
get_gateway_metadata(name).ok_or_else(|| {
miette::miette!(
"No gateway metadata found for '{name}'.\n\
Deploy a gateway first with: openshell gateway start --name {name}\n\
Or list available gateways: openshell gateway select"
)
})?;
save_active_gateway(name)?;
eprintln!("{} Active gateway set to '{name}'", "✓".green().bold());
Ok(())
}
pub fn gateway_select(name: Option<&str>, gateway_flag: &Option<String>) -> Result<()> {
let interactive = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
gateway_select_with(name, gateway_flag, interactive, |gateways, default| {
let prompt = format!(
"Select a gateway\n{}",
format_gateway_select_header(gateways)
);
let items = format_gateway_select_items(gateways);
Select::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.items(&items)
.default(default)
.report(false)
.interact_opt()
.into_diagnostic()
.map(|selection| selection.map(|index| gateways[index].name.clone()))
})
}
fn format_gateway_select_header(gateways: &[GatewayMetadata]) -> String {
let (name_width, endpoint_width, type_width) = gateway_select_column_widths(gateways);
format!(
" {:<name_width$} {:<endpoint_width$} {:<type_width$} {}",
"NAME".bold(),
"ENDPOINT".bold(),
"TYPE".bold(),
"AUTH".bold(),
)
}
fn format_gateway_select_items(gateways: &[GatewayMetadata]) -> Vec<String> {
let (name_width, endpoint_width, type_width) = gateway_select_column_widths(gateways);
gateways
.iter()
.map(|gateway| {
format!(
"{:<name_width$} {:<endpoint_width$} {:<type_width$} {}",
gateway.name,
gateway.gateway_endpoint,
gateway_type_label(gateway),
gateway_auth_label(gateway),
)
})
.collect()
}
fn gateway_select_column_widths(gateways: &[GatewayMetadata]) -> (usize, usize, usize) {
let name_width = gateways
.iter()
.map(|gateway| gateway.name.len())
.max()
.unwrap_or(4)
.max(4);
let endpoint_width = gateways
.iter()
.map(|gateway| gateway.gateway_endpoint.len())
.max()
.unwrap_or(8)
.max(8);
let type_width = gateways
.iter()
.map(|gateway| gateway_type_label(gateway).len())
.max()
.unwrap_or(4)
.max(4);
(name_width, endpoint_width, type_width)
}
fn gateway_type_label(gateway: &GatewayMetadata) -> &'static str {
match gateway.auth_mode.as_deref() {
Some("cloudflare_jwt") => "cloud",
_ if gateway.is_remote => "remote",
_ => "local",
}
}
fn gateway_auth_label(gateway: &GatewayMetadata) -> &str {
gateway.auth_mode.as_deref().unwrap_or("unknown")
}
fn gateway_select_with<F>(
name: Option<&str>,
gateway_flag: &Option<String>,
interactive: bool,
choose_gateway: F,
) -> Result<()>
where
F: FnOnce(&[GatewayMetadata], usize) -> Result<Option<String>>,
{
if let Some(name) = name {
return gateway_use(name);
}
let gateways = list_gateways()?;
if gateways.is_empty() || !interactive {
gateway_list(gateway_flag)?;
if !gateways.is_empty() {
eprintln!();
eprintln!(
"Select a gateway with: {}",
"openshell gateway select <name>".dimmed()
);
}
return Ok(());
}
let active = gateway_flag.clone().or_else(load_active_gateway);
let default = active
.as_deref()
.and_then(|name| gateways.iter().position(|gateway| gateway.name == name))
.unwrap_or(0);
if let Some(name) = choose_gateway(&gateways, default)? {
gateway_use(&name)?;
} else {
eprintln!("{} Gateway selection cancelled", "!".yellow());
}
Ok(())
}
/// Register an existing gateway.
///
/// Without extra flags the gateway is treated as an edge-authenticated (cloud)
/// gateway and a browser is opened for authentication.
///
/// Pass `remote` (SSH destination) to register a remote mTLS gateway, or
/// `local = true` for a local mTLS gateway. In both cases the CLI extracts
/// mTLS certificates from the running container automatically.
///
/// An `ssh://` endpoint (e.g., `ssh://user@host:8080`) is shorthand for
/// `--remote user@host` with the gateway endpoint derived from the URL.
pub async fn gateway_add(
endpoint: &str,
name: Option<&str>,
remote: Option<&str>,
ssh_key: Option<&str>,
local: bool,
) -> Result<()> {
// If the endpoint starts with ssh://, parse it into an SSH destination
// and a gateway endpoint automatically. The host is resolved via
// `ssh -G` so that SSH config aliases map to the real hostname/IP.
// e.g. ssh://drew@spark:8080 -> remote="drew@spark", endpoint="https://<resolved>:8080"
let (endpoint, remote) = if endpoint.starts_with("ssh://") {
if local {
return Err(miette::miette!(
"Cannot use --local with an ssh:// endpoint.\n\
ssh:// implies a remote gateway."
));
}
if remote.is_some() {
return Err(miette::miette!(
"Cannot use --remote with an ssh:// endpoint.\n\
The SSH destination is already embedded in the URL."
));
}
let parsed = url::Url::parse(endpoint)
.map_err(|e| miette::miette!("Invalid ssh:// URL '{endpoint}': {e}"))?;
let host = parsed
.host_str()
.ok_or_else(|| miette::miette!("ssh:// URL must include a hostname: {endpoint}"))?;
let port = parsed
.port()
.ok_or_else(|| miette::miette!("ssh:// URL must include a port: {endpoint}"))?;
let ssh_dest = if parsed.username().is_empty() {
host.to_string()
} else {
format!("{}@{host}", parsed.username())
};
// Resolve the SSH host alias (e.g. ~/.ssh/config HostName) so the
// endpoint uses the actual hostname/IP that matches the TLS certificate
// SANs — consistent with the `gateway start` path.
let resolved = resolve_ssh_hostname(host);
let https_endpoint = format!("https://{resolved}:{port}");
(https_endpoint, Some(ssh_dest))
} else {
// Normalise the endpoint: ensure it has a scheme.
let endpoint = if endpoint.contains("://") {
endpoint.to_string()
} else {
format!("https://{endpoint}")
};
(endpoint, remote.map(String::from))
};
let remote = remote.as_deref();
// Validate --ssh-key requires a remote gateway context.
if ssh_key.is_some() && remote.is_none() {
return Err(miette::miette!(
"--ssh-key requires --remote or an ssh:// endpoint"
));
}
// Derive a gateway name from the hostname when none is provided.
let derived_name;
let name = if let Some(n) = name {
n
} else {
// Parse out just the host portion of the URL.
derived_name = url::Url::parse(&endpoint)
.ok()
.and_then(|u| u.host_str().map(String::from))
.unwrap_or_else(|| endpoint.clone());
&derived_name
};
// Fail if a gateway with this name already exists.
if get_gateway_metadata(name).is_some() {
return Err(miette::miette!(
"Gateway '{}' already exists.\n\
Remove it first with: openshell gateway destroy --name {}\n\
Or choose a different name with: --name <name>",
name,
name,
));
}
if remote.is_some() || local {
// mTLS gateway (remote or local).
let remote_opts = remote.map(|dest| {
let mut opts = RemoteOptions::new(dest);
if let Some(key) = ssh_key {
opts = opts.with_ssh_key(key);
}
opts
});
// Extract certs BEFORE storing metadata — if this fails the gateway
// is not registered. Pass the endpoint port so the container can be
// identified by its host port binding when multiple gateways run on