1#![allow(clippy::print_stdout, clippy::print_stderr)]
6
7use anyhow::{bail, Result};
8use std::io::{self, Write};
9use tracing::info;
10
11use hyprstream_rpc_std::worker_client::ContainerMetadata;
12use hyprstream_rpc_std::worker_client::{
13 ContainerConfig,
14 ContainerFilter,
15 ContainerState,
16 ContainerStats,
17 ContainerStatsFilter,
18 ContainerStatusRequest,
19 CreateContainerRequest,
20 ExecSyncRequest,
21 ImageFilter,
22 ImageSpec,
23 ImageStatusRequest,
24 KeyValue,
25 PodSandboxConfig,
26 PodSandboxFilter,
27 PodSandboxState,
28 PodSandboxStats,
29 PodSandboxStatusRequest,
31 PullImageRequest,
32 StopContainerRequest,
33 Timestamp,
34};
35
36use hyprstream_rpc_std::worker_client::WorkerClient;
37
38pub async fn handle_worker_list(
44 client: &WorkerClient,
45 sandbox_filter: Option<String>,
46 container_filter: Option<String>,
47 containers_only: bool,
48 sandboxes_only: bool,
49 _state_filter: Option<String>,
50 _verbose: bool,
51) -> Result<()> {
52 if !containers_only {
53 let filter = PodSandboxFilter {
55 id: sandbox_filter.clone().unwrap_or_default(),
56 ..Default::default()
57 };
58
59 let sandboxes = client.sandbox().list(&filter).await?;
60
61 if !sandboxes.is_empty() {
62 println!("SANDBOX ID STATE CREATED");
63 for sb in &sandboxes {
64 let state = match sb.state {
65 PodSandboxState::SandboxReady => "Ready",
66 PodSandboxState::SandboxNotReady => "NotReady",
67 };
68 let id_short = truncate_id(&sb.id, 36);
69 println!(
70 "{:<40}{:<16}{}",
71 id_short,
72 state,
73 format_timestamp(sb.created_at.clone())
74 );
75 }
76 } else if sandboxes_only {
77 println!("No sandboxes found.");
78 }
79 }
80
81 if !sandboxes_only {
82 let filter = ContainerFilter {
84 id: container_filter.unwrap_or_default(),
85 pod_sandbox_id: sandbox_filter.clone().unwrap_or_default(),
86 ..Default::default()
87 };
88
89 let containers = client.container().list(&filter).await?;
90
91 if !containers.is_empty() {
92 if !containers_only {
93 println!(); }
95 println!(
96 "CONTAINER ID IMAGE STATE SANDBOX"
97 );
98 for c in &containers {
99 let state = match c.state {
100 ContainerState::ContainerCreated => "Created",
101 ContainerState::ContainerRunning => "Running",
102 ContainerState::ContainerExited => "Exited",
103 ContainerState::ContainerUnknown => "Unknown",
104 };
105 let id_short = truncate_id(&c.id, 36);
106 let image = if c.image.image.is_empty() {
107 "-"
108 } else {
109 &c.image.image
110 };
111 let image_short = truncate_id(image, 30);
112 let sandbox_short = truncate_id(&c.pod_sandbox_id, 12);
113 println!("{id_short:<40}{image_short:<32}{state:<16}{sandbox_short}");
114 }
115 }
116 }
117
118 Ok(())
119}
120
121#[allow(clippy::too_many_arguments)]
127pub async fn handle_worker_run(
128 client: &WorkerClient,
129 image: &str,
130 command: Vec<String>,
131 sandbox_id: Option<String>,
132 name: Option<String>,
133 env: Vec<String>,
134 workdir: Option<String>,
135 detach: bool,
136 auto_remove: bool,
137) -> Result<()> {
138 info!(image = %image, "Running container");
139
140 let image_spec = ImageSpec {
142 image: image.to_owned(),
143 annotations: vec![],
144 runtime_handler: String::new(),
145 };
146
147 if client
149 .image()
150 .status(&ImageStatusRequest {
151 image: image_spec.clone(),
152 verbose: false,
153 })
154 .await
155 .is_err()
156 {
157 println!("Pulling image {image}...");
158 client
159 .image()
160 .pull(&PullImageRequest {
161 image: image_spec.clone(),
162 auth: Default::default(),
163 sandbox_config: PodSandboxConfig::default(),
164 })
165 .await?;
166 println!("Image pulled");
167 }
168
169 let sandbox_id = if let Some(id) = sandbox_id {
171 id
172 } else {
173 let config = PodSandboxConfig::default();
174 let id = client.sandbox().run(&config).await?;
175 println!("Created sandbox {}", truncate_id(&id, 12));
176 id
177 };
178
179 let container_config = ContainerConfig {
181 metadata: ContainerMetadata {
182 name: name.unwrap_or_else(generate_name),
183 attempt: 0,
184 },
185 image: ImageSpec {
186 image: image_spec.image.clone(),
187 annotations: Default::default(),
188 runtime_handler: image_spec.runtime_handler.clone(),
189 },
190 command: if command.is_empty() {
191 vec![]
192 } else {
193 command.clone()
194 },
195 args: vec![],
196 working_dir: workdir.unwrap_or_default(),
197 envs: parse_env_vars(&env),
198 ..Default::default()
199 };
200
201 let container_id = client
203 .container()
204 .create(&CreateContainerRequest {
205 pod_sandbox_id: sandbox_id.clone(),
206 config: container_config,
207 sandbox_config: PodSandboxConfig::default(),
208 })
209 .await?;
210
211 client.container().start(&container_id).await?;
212
213 if detach {
214 println!("{container_id}");
215 } else {
216 println!("Container {} started", truncate_id(&container_id, 12));
217
218 loop {
220 let status = client
221 .container()
222 .status(&ContainerStatusRequest {
223 container_id: container_id.clone(),
224 verbose: false,
225 })
226 .await?;
227 if status.status.state == ContainerState::ContainerExited {
228 println!("Container exited with code {:?}", status.status.exit_code);
229 break;
230 }
231 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
232 }
233
234 if auto_remove {
235 client.container().remove(&container_id).await?;
236 println!("Container removed");
237 }
238 }
239
240 Ok(())
241}
242
243pub async fn handle_worker_stop(
249 client: &WorkerClient,
250 id: &str,
251 timeout: i64,
252 force: bool,
253) -> Result<()> {
254 info!(id = %id, timeout = %timeout, force = %force, "Stopping");
255
256 if client
258 .container()
259 .status(&ContainerStatusRequest {
260 container_id: id.to_owned(),
261 verbose: false,
262 })
263 .await
264 .is_ok()
265 {
266 let actual_timeout = if force { 0 } else { timeout };
267 client
268 .container()
269 .stop(&StopContainerRequest {
270 container_id: id.to_owned(),
271 timeout: actual_timeout,
272 })
273 .await?;
274 println!("{id}");
275 return Ok(());
276 }
277
278 client.sandbox().stop(id).await?;
280 println!("{id}");
281 Ok(())
282}
283
284pub async fn handle_worker_start(client: &WorkerClient, container_id: &str) -> Result<()> {
290 info!(container_id = %container_id, "Starting container");
291
292 client.container().start(container_id).await?;
293 println!("{container_id}");
294 Ok(())
295}
296
297pub async fn handle_worker_restart(client: &WorkerClient, id: &str, timeout: i64) -> Result<()> {
303 info!(id = %id, "Restarting");
304
305 handle_worker_stop(client, id, timeout, false).await?;
307
308 if client
310 .container()
311 .status(&ContainerStatusRequest {
312 container_id: id.to_owned(),
313 verbose: false,
314 })
315 .await
316 .is_ok()
317 {
318 client.container().start(id).await?;
319 } else {
320 bail!("Sandbox restart not supported - use rm + run");
322 }
323
324 println!("{id}");
325 Ok(())
326}
327
328pub async fn handle_worker_rm(client: &WorkerClient, ids: Vec<String>, force: bool) -> Result<()> {
334 for id in ids {
335 if let Ok(status) = client
337 .container()
338 .status(&ContainerStatusRequest {
339 container_id: id.clone(),
340 verbose: false,
341 })
342 .await
343 {
344 if status.status.state == ContainerState::ContainerRunning {
345 if force {
346 client
347 .container()
348 .stop(&StopContainerRequest {
349 container_id: id.clone(),
350 timeout: 0,
351 })
352 .await?;
353 } else {
354 bail!("Container {} is running. Use -f to force.", id);
355 }
356 }
357 client.container().remove(&id).await?;
358 println!("{id}");
359 continue;
360 }
361
362 if client
364 .sandbox()
365 .status(&PodSandboxStatusRequest {
366 pod_sandbox_id: id.clone(),
367 verbose: false,
368 })
369 .await
370 .is_ok()
371 {
372 if force {
373 let _ = client.sandbox().stop(&id).await;
374 }
375 client.sandbox().remove(&id).await?;
376 println!("{id}");
377 continue;
378 }
379
380 bail!("No such container or sandbox: {}", id);
381 }
382
383 Ok(())
384}
385
386pub async fn handle_worker_status(client: &WorkerClient, id: &str, verbose: bool) -> Result<()> {
392 if let Ok(status) = client
394 .container()
395 .status(&ContainerStatusRequest {
396 container_id: id.to_owned(),
397 verbose,
398 })
399 .await
400 {
401 println!("Type: Container");
402 println!("ID: {}", status.status.id);
403 println!("State: {:?}", status.status.state);
404 let image_str = if status.status.image.image.is_empty() {
405 "-"
406 } else {
407 &status.status.image.image
408 };
409 println!("Image: {image_str}");
410 println!("Created: {}", format_timestamp(status.status.created_at));
411 if status.status.state == ContainerState::ContainerExited {
412 println!("Exit Code: {}", status.status.exit_code);
413 }
414 if verbose {
415 println!("\nInfo:");
416 print_kv_info(&status.info);
417 }
418 return Ok(());
419 }
420
421 let status = client
423 .sandbox()
424 .status(&PodSandboxStatusRequest {
425 pod_sandbox_id: id.to_owned(),
426 verbose,
427 })
428 .await?;
429 println!("Type: Sandbox");
430 println!("ID: {}", status.status.id);
431 println!("State: {:?}", status.status.state);
432 println!("Created: {}", format_timestamp(status.status.created_at));
433 if verbose {
434 println!("\nInfo:");
435 print_kv_info(&status.info);
436 }
437
438 Ok(())
439}
440
441pub async fn handle_worker_stats(
447 client: &WorkerClient,
448 ids: Vec<String>,
449 no_header: bool,
450) -> Result<()> {
451 if !no_header {
452 println!(
453 "{:<40}{:<12}{:<24}{:<16}",
454 "ID", "CPU %", "MEM USAGE / LIMIT", "NET I/O"
455 );
456 }
457
458 if ids.is_empty() {
459 let stats = client
461 .container()
462 .list_stats(&ContainerStatsFilter::default())
463 .await?;
464 for s in stats {
465 print_container_stats(&s.attributes.id, &s);
466 }
467 } else {
468 for id in ids {
469 if let Ok(s) = client.container().stats(&id).await {
470 print_container_stats(&id, &s);
471 } else if let Ok(s) = client.sandbox().stats(&id).await {
472 print_sandbox_stats(&id, &s);
473 }
474 }
475 }
476
477 Ok(())
478}
479
480fn print_container_stats(id: &str, stats: &ContainerStats) {
481 let cpu_pct = format!("{:.2}%", stats.cpu.usage_nano_cores as f64 / 1e9 * 100.0);
482 let mem = format!(
483 "{} / {}",
484 format_size(stats.memory.usage_bytes),
485 format_size(stats.memory.available_bytes),
486 );
487
488 println!(
489 "{:<40}{:<12}{:<24}{:<16}",
490 truncate_id(id, 36),
491 cpu_pct,
492 mem,
493 "-"
494 );
495}
496
497fn print_sandbox_stats(id: &str, stats: &PodSandboxStats) {
498 let cpu_pct = format!(
499 "{:.2}%",
500 stats.linux.cpu.usage_nano_cores as f64 / 1e9 * 100.0,
501 );
502 let mem = format!(
503 "{} / {}",
504 format_size(stats.linux.memory.usage_bytes),
505 format_size(stats.linux.memory.available_bytes),
506 );
507 let net = format!(
508 "{} / {}",
509 format_size(stats.linux.network.default_interface.rx_bytes),
510 format_size(stats.linux.network.default_interface.tx_bytes),
511 );
512
513 println!(
514 "{:<40}{:<12}{:<24}{:<16}",
515 truncate_id(id, 36),
516 cpu_pct,
517 mem,
518 net
519 );
520}
521
522pub async fn handle_worker_exec(
528 client: &WorkerClient,
529 container_id: &str,
530 command: Vec<String>,
531 timeout: i64,
532) -> Result<()> {
533 if command.is_empty() {
534 bail!("No command specified");
535 }
536
537 let result = client
538 .container()
539 .exec(&ExecSyncRequest {
540 container_id: container_id.to_owned(),
541 cmd: command,
542 timeout,
543 })
544 .await?;
545
546 if !result.stdout.is_empty() {
548 io::stdout().write_all(&result.stdout)?;
549 }
550
551 if !result.stderr.is_empty() {
553 io::stderr().write_all(&result.stderr)?;
554 }
555
556 if result.exit_code != 0 {
557 std::process::exit(result.exit_code);
558 }
559
560 Ok(())
561}
562
563pub async fn handle_worker_terminal(
573 client: &WorkerClient,
574 container_id: &str,
575 detach_keys: &str,
576) -> Result<()> {
577 use hyprstream_rpc::streaming::StreamPayload;
578 use std::sync::atomic::{AtomicBool, Ordering};
579 use std::sync::Arc;
580 use tokio::signal;
581
582 info!(container_id = %container_id, "Attaching to container terminal");
583
584 use hyprstream_rpc_std::worker_client::ContainerRpc;
586 let mut stream_handle = ContainerRpc::attach(
587 &client.container(),
588 &hyprstream_rpc_std::worker_client::AttachRequest {
589 container_id: container_id.to_owned(),
590 fds: vec![],
591 },
592 )
593 .await?;
594
595 println!(
596 "Attached to container {}\n\
597 Stream ID: {}\n\
598 Detach with: {}",
599 truncate_id(container_id, 12),
600 truncate_id(stream_handle.stream_id(), 16),
601 detach_keys,
602 );
603
604 let running = Arc::new(AtomicBool::new(true));
606 let cancel = stream_handle.cancel_token().clone();
607
608 let running_signal = running.clone();
610 let cancel_signal = cancel.clone();
611 tokio::spawn(async move {
612 let _ = signal::ctrl_c().await;
613 running_signal.store(false, Ordering::SeqCst);
614 cancel_signal.cancel();
615 });
616
617 let detach_byte = parse_detach_keys(detach_keys);
619
620 println!("\n--- Terminal attached. Press {detach_keys} to detach ---\n");
621
622 let running_recv = running.clone();
624 let cancel_recv = cancel.clone();
625 let recv_handle = std::thread::spawn(move || {
626 struct RunGuard(Arc<AtomicBool>);
628 impl Drop for RunGuard {
629 fn drop(&mut self) {
630 self.0.store(false, Ordering::SeqCst);
631 }
632 }
633 let _guard = RunGuard(running_recv);
634
635 let rt = match tokio::runtime::Builder::new_current_thread()
639 .enable_all()
640 .build()
641 {
642 Ok(rt) => rt,
643 Err(e) => {
644 eprintln!("failed to build stream recv runtime: {e}");
645 return;
646 }
647 };
648 rt.block_on(async move {
649 use futures::StreamExt;
650 while let Some(payload) = stream_handle.next().await {
651 match payload {
652 Ok(StreamPayload::Data(data)) => {
653 print!("{}", String::from_utf8_lossy(&data));
655 let _ = io::stdout().flush();
656 }
657 Ok(StreamPayload::Complete(_)) => {
658 println!("\n--- Stream complete ---");
659 break;
660 }
661 Ok(StreamPayload::Error(message)) => {
662 eprintln!("\n--- Stream error: {message} ---");
663 break;
664 }
665 Ok(StreamPayload::Tagged { .. }) => {
666 continue;
668 }
669 Err(e) => {
670 tracing::warn!("Stream receive error: {}", e);
671 break;
672 }
673 }
674 }
675 });
676 cancel_recv.cancel(); });
679
680 use std::io::BufRead;
683 let stdin = io::stdin();
684 for line in stdin.lock().lines() {
685 if !running.load(Ordering::SeqCst) {
686 break;
687 }
688
689 if let Ok(line) = line {
690 if line.as_bytes().first() == Some(&detach_byte) {
692 println!("\n--- Detached ---");
693 break;
694 }
695
696 tracing::debug!("Stdin input (not sent): {}", line);
699 }
700 }
701
702 cancel.cancel(); running.store(false, Ordering::SeqCst);
704 let _ = recv_handle.join();
705
706 println!("Terminal session ended.");
707 Ok(())
708}
709
710fn parse_detach_keys(keys: &str) -> u8 {
712 const DEFAULT_DETACH_KEY: u8 = 0x1D;
714
715 match keys.to_lowercase().as_str() {
716 "ctrl-a" | "ctrl+a" => 0x01,
717 "ctrl-b" | "ctrl+b" => 0x02,
718 "ctrl-c" | "ctrl+c" => 0x03,
719 "ctrl-d" | "ctrl+d" => 0x04,
720 "ctrl-q" | "ctrl+q" => 0x11,
721 _ => DEFAULT_DETACH_KEY,
723 }
724}
725
726pub async fn handle_images_list(client: &WorkerClient, _verbose: bool) -> Result<()> {
732 let images = client
733 .image()
734 .list(&ImageFilter {
735 image: ImageSpec::default(),
736 })
737 .await?;
738
739 println!(
740 "{:<48}{:<16}{:<16}{:<12}",
741 "REPOSITORY", "TAG", "IMAGE ID", "SIZE"
742 );
743 for img in images {
744 for tag in &img.repo_tags {
745 let (repo, tag_part) = tag.rsplit_once(':').unwrap_or((tag, "latest"));
746 let id_short = truncate_id(&img.id, 12);
747 let size = format_size(img.size);
748 println!("{repo:<48}{tag_part:<16}{id_short:<16}{size:<12}");
749 }
750 }
751
752 Ok(())
753}
754
755pub async fn handle_images_pull(
757 client: &WorkerClient,
758 image: &str,
759 username: Option<String>,
760 password: Option<String>,
761) -> Result<()> {
762 println!("Pulling {image}...");
763
764 let image_spec = ImageSpec {
765 image: image.to_owned(),
766 annotations: vec![],
767 runtime_handler: String::new(),
768 };
769
770 let auth = match (username, password) {
771 (Some(u), Some(p)) => hyprstream_rpc_std::worker_client::AuthConfig {
772 username: u,
773 password: p,
774 auth: String::new(),
775 server_address: String::new(),
776 identity_token: String::new(),
777 registry_token: String::new(),
778 },
779 _ => Default::default(),
780 };
781
782 let id = client
783 .image()
784 .pull(&PullImageRequest {
785 image: image_spec,
786 auth,
787 sandbox_config: PodSandboxConfig::default(),
788 })
789 .await?;
790 println!("Pulled {} ({})", image, truncate_id(&id, 12));
791
792 Ok(())
793}
794
795pub async fn handle_images_rm(
797 client: &WorkerClient,
798 images: Vec<String>,
799 _force: bool,
800) -> Result<()> {
801 for img in images {
802 let image_spec = ImageSpec {
803 image: img.clone(),
804 annotations: vec![],
805 runtime_handler: String::new(),
806 };
807
808 client.image().remove(&image_spec).await?;
809 println!("Deleted: {img}");
810 }
811
812 Ok(())
813}
814
815pub async fn handle_images_df(client: &WorkerClient) -> Result<()> {
817 let usage = client.image().fs_info().await?;
818
819 println!(
820 "{:<16}{:<16}{:<16}{:<16}",
821 "TYPE", "TOTAL", "USED", "AVAILABLE"
822 );
823
824 if usage.is_empty() {
825 println!("{:<16}{:<16}{:<16}{:<16}", "Images", "-", "0B", "-");
826 } else {
827 for fs in &usage {
828 let used = format_size(fs.used_bytes);
829 println!("{:<16}{:<16}{:<16}{:<16}", "Images", "-", used, "-");
830 }
831 }
832
833 Ok(())
834}
835
836fn format_timestamp(ts: Timestamp) -> String {
841 use chrono::{TimeZone, Utc};
842 if ts.seconds == 0 && ts.nanos == 0 {
843 return "-".to_owned();
844 }
845 Utc.timestamp_opt(ts.seconds, ts.nanos as u32)
846 .single()
847 .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
848 .unwrap_or_else(|| "-".to_owned())
849}
850
851fn print_kv_info(info: &[KeyValue]) {
852 for kv in info {
853 println!(" {}: {}", kv.key, kv.value);
854 }
855}
856
857fn format_size(bytes: u64) -> String {
858 const KB: u64 = 1024;
859 const MB: u64 = KB * 1024;
860 const GB: u64 = MB * 1024;
861
862 if bytes >= GB {
863 format!("{:.1}GB", bytes as f64 / GB as f64)
864 } else if bytes >= MB {
865 format!("{:.1}MB", bytes as f64 / MB as f64)
866 } else if bytes >= KB {
867 format!("{:.1}KB", bytes as f64 / KB as f64)
868 } else {
869 format!("{bytes}B")
870 }
871}
872
873fn truncate_id(id: &str, max_len: usize) -> &str {
874 if id.len() <= max_len {
875 id
876 } else {
877 &id[..max_len]
878 }
879}
880
881fn generate_name() -> String {
882 use std::time::{SystemTime, UNIX_EPOCH};
883 let timestamp = SystemTime::now()
884 .duration_since(UNIX_EPOCH)
885 .unwrap_or_default()
886 .as_secs();
887 format!("container-{}", timestamp % 100000)
888}
889
890fn parse_env_vars(env: &[String]) -> Vec<KeyValue> {
891 env.iter()
892 .filter_map(|e| {
893 let parts: Vec<&str> = e.splitn(2, '=').collect();
894 if parts.len() == 2 {
895 Some(KeyValue {
896 key: parts[0].to_owned(),
897 value: parts[1].to_owned(),
898 })
899 } else {
900 None
901 }
902 })
903 .collect()
904}