forked from kata-containers/kata-containers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.rs
1920 lines (1488 loc) · 48 KB
/
client.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
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
// Copyright (c) 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
// Description: Client side of ttRPC comms
use crate::types::{Config, Options};
use crate::utils;
use anyhow::{anyhow, Result};
use byteorder::ByteOrder;
use nix::sys::socket::{connect, socket, AddressFamily, SockAddr, SockFlag, SockType, UnixAddr};
use protocols::agent::*;
use protocols::agent_ttrpc::*;
use protocols::health::*;
use protocols::health_ttrpc::*;
use slog::{debug, info};
use std::io;
use std::io::Write; // XXX: for flush()
use std::os::unix::io::{IntoRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::thread::sleep;
use std::time::Duration;
use ttrpc;
use ttrpc::context::Context;
// Hack until the actual Context type supports this.
fn clone_context(ctx: &Context) -> Context {
Context {
metadata: ctx.metadata.clone(),
timeout_nano: ctx.timeout_nano,
}
}
// Agent command handler type
//
// Notes:
//
// - 'cmdline' is the command line (command name and optional space separate
// arguments).
// - 'options' can be read and written to, allowing commands to pass state to
// each other via well-known option names.
type AgentCmdFp = fn(
ctx: &Context,
client: &AgentServiceClient,
health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()>;
// Builtin command handler type
type BuiltinCmdFp = fn(args: &str) -> (Result<()>, bool);
enum ServiceType {
Agent,
Health,
}
// XXX: Agent command names *MUST* start with an upper-case letter.
struct AgentCmd {
name: &'static str,
st: ServiceType,
fp: AgentCmdFp,
}
// XXX: Builtin command names *MUST* start with a lower-case letter.
struct BuiltinCmd {
name: &'static str,
descr: &'static str,
fp: BuiltinCmdFp,
}
// Command that causes the agent to exit (iff tracing is enabled)
const SHUTDOWN_CMD: &'static str = "DestroySandbox";
// Command that requests this program ends
const CMD_QUIT: &'static str = "quit";
const CMD_REPEAT: &'static str = "repeat";
const DEFAULT_PROC_SIGNAL: &'static str = "SIGKILL";
const ERR_API_FAILED: &str = "API failed";
static AGENT_CMDS: &'static [AgentCmd] = &[
AgentCmd {
name: "AddARPNeighbors",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_add_arp_neighbors,
},
AgentCmd {
name: "Check",
st: ServiceType::Health,
fp: agent_cmd_health_check,
},
AgentCmd {
name: "Version",
st: ServiceType::Health,
fp: agent_cmd_health_version,
},
AgentCmd {
name: "CloseStdin",
st: ServiceType::Agent,
fp: agent_cmd_container_close_stdin,
},
AgentCmd {
name: "CopyFile",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_copy_file,
},
AgentCmd {
name: "CreateContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_create,
},
AgentCmd {
name: "CreateSandbox",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_create,
},
AgentCmd {
name: "DestroySandbox",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_destroy,
},
AgentCmd {
name: "ExecProcess",
st: ServiceType::Agent,
fp: agent_cmd_container_exec,
},
AgentCmd {
name: "GetGuestDetails",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_get_guest_details,
},
AgentCmd {
name: "GetMetrics",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_get_metrics,
},
AgentCmd {
name: "GetOOMEvent",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_get_oom_event,
},
AgentCmd {
name: "ListInterfaces",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_list_interfaces,
},
AgentCmd {
name: "ListRoutes",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_list_routes,
},
AgentCmd {
name: "MemHotplugByProbe",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_mem_hotplug_by_probe,
},
AgentCmd {
name: "OnlineCPUMem",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_online_cpu_mem,
},
AgentCmd {
name: "PauseContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_pause,
},
AgentCmd {
name: "ReadStderr",
st: ServiceType::Agent,
fp: agent_cmd_container_read_stderr,
},
AgentCmd {
name: "ReadStdout",
st: ServiceType::Agent,
fp: agent_cmd_container_read_stdout,
},
AgentCmd {
name: "ReseedRandomDev",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_reseed_random_dev,
},
AgentCmd {
name: "RemoveContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_remove,
},
AgentCmd {
name: "ResumeContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_resume,
},
AgentCmd {
name: "SetGuestDateTime",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_set_guest_date_time,
},
AgentCmd {
name: "SignalProcess",
st: ServiceType::Agent,
fp: agent_cmd_container_signal_process,
},
AgentCmd {
name: "StartContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_start,
},
AgentCmd {
name: "StartTracing",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_tracing_start,
},
AgentCmd {
name: "StatsContainer",
st: ServiceType::Agent,
fp: agent_cmd_container_stats,
},
AgentCmd {
name: "StopTracing",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_tracing_stop,
},
AgentCmd {
name: "TtyWinResize",
st: ServiceType::Agent,
fp: agent_cmd_container_tty_win_resize,
},
AgentCmd {
name: "UpdateContainer",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_update_container,
},
AgentCmd {
name: "UpdateInterface",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_update_interface,
},
AgentCmd {
name: "UpdateRoutes",
st: ServiceType::Agent,
fp: agent_cmd_sandbox_update_routes,
},
AgentCmd {
name: "WaitProcess",
st: ServiceType::Agent,
fp: agent_cmd_container_wait_process,
},
AgentCmd {
name: "WriteStdin",
st: ServiceType::Agent,
fp: agent_cmd_container_write_stdin,
},
];
static BUILTIN_CMDS: &'static [BuiltinCmd] = &[
BuiltinCmd {
name: "echo",
descr: "Display the arguments",
fp: builtin_cmd_echo,
},
BuiltinCmd {
name: "help",
descr: "Alias for 'list'",
fp: builtin_cmd_list,
},
BuiltinCmd {
name: "list",
descr: "List all available commands",
fp: builtin_cmd_list,
},
BuiltinCmd {
name: "repeat",
descr: "Repeat the next command 'n' times [-1 for forever]",
fp: builtin_cmd_repeat,
},
BuiltinCmd {
name: "sleep",
descr:
"Pause for specified period number of nanoseconds (supports human-readable suffixes [no floating points numbers])",
fp: builtin_cmd_sleep,
},
BuiltinCmd {
name: CMD_QUIT,
descr: "Exit this program",
fp: builtin_cmd_quit,
},
];
fn get_agent_cmd_names() -> Vec<String> {
let mut names = Vec::new();
for cmd in AGENT_CMDS {
names.push(cmd.name.to_string());
}
names
}
fn get_agent_cmd_details() -> Vec<String> {
let mut cmds = Vec::new();
for cmd in AGENT_CMDS {
let service = match cmd.st {
ServiceType::Agent => "agent",
ServiceType::Health => "health",
};
cmds.push(format!("{} ({} service)", cmd.name, service));
}
cmds
}
fn get_agent_cmd_func(name: &str) -> Result<AgentCmdFp> {
for cmd in AGENT_CMDS {
if cmd.name == name {
return Ok(cmd.fp);
}
}
Err(anyhow!("Invalid command: {:?}", name))
}
fn get_builtin_cmd_details() -> Vec<String> {
let mut cmds = Vec::new();
for cmd in BUILTIN_CMDS {
cmds.push(format!("{} ({})", cmd.name, cmd.descr));
}
cmds
}
fn get_all_cmd_details() -> Vec<String> {
let mut cmds = get_builtin_cmd_details();
cmds.append(&mut get_agent_cmd_names());
cmds
}
fn get_builtin_cmd_func(name: &str) -> Result<BuiltinCmdFp> {
for cmd in BUILTIN_CMDS {
if cmd.name == name {
return Ok(cmd.fp);
}
}
Err(anyhow!("Invalid command: {:?}", name))
}
fn client_create_vsock_fd(cid: libc::c_uint, port: u32) -> Result<RawFd> {
let fd = socket(
AddressFamily::Vsock,
SockType::Stream,
SockFlag::SOCK_CLOEXEC,
None,
)
.map_err(|e| anyhow!(e))?;
let sock_addr = SockAddr::new_vsock(cid, port);
connect(fd, &sock_addr).map_err(|e| anyhow!(e))?;
Ok(fd)
}
fn create_ttrpc_client(server_address: String) -> Result<ttrpc::Client> {
if server_address == "" {
return Err(anyhow!("server address cannot be blank"));
}
let fields: Vec<&str> = server_address.split("://").collect();
if fields.len() != 2 {
return Err(anyhow!("invalid server address URI"));
}
let scheme = fields[0].to_lowercase();
let fd: RawFd = match scheme.as_str() {
// Formats:
//
// - "unix://absolute-path" (domain socket)
// (example: "unix:///tmp/domain.socket")
//
// - "unix://@absolute-path" (abstract socket)
// (example: "unix://@/tmp/abstract.socket")
//
"unix" => {
let mut abstract_socket = false;
let mut path = fields[1].to_string();
if path.starts_with('@') {
abstract_socket = true;
// Remove the magic abstract-socket request character ('@')
// and crucially add a trailing nul terminator (required to
// interoperate with the ttrpc crate).
path = path[1..].to_string() + &"\x00".to_string();
}
if abstract_socket {
let socket_fd = match socket(
AddressFamily::Unix,
SockType::Stream,
SockFlag::empty(),
None,
) {
Ok(s) => s,
Err(e) => return Err(anyhow!(e).context("Failed to create Unix Domain socket")),
};
let unix_addr = match UnixAddr::new_abstract(path.as_bytes()) {
Ok(s) => s,
Err(e) => {
return Err(
anyhow!(e).context("Failed to create Unix Domain abstract socket")
)
}
};
let sock_addr = SockAddr::Unix(unix_addr);
connect(socket_fd, &sock_addr).map_err(|e| {
anyhow!(e).context("Failed to connect to Unix Domain abstract socket")
})?;
socket_fd
} else {
let stream = match UnixStream::connect(path) {
Ok(s) => s,
Err(e) => {
return Err(
anyhow!(e).context("failed to create named UNIX Domain stream socket")
)
}
};
stream.into_raw_fd()
}
}
// Format: "vsock://cid:port"
"vsock" => {
let addr: Vec<&str> = fields[1].split(':').collect();
if addr.len() != 2 {
return Err(anyhow!("invalid VSOCK server address URI"));
}
let cid: u32 = match addr[0] {
"-1" | "" => libc::VMADDR_CID_ANY,
_ => match addr[0].parse::<u32>() {
Ok(c) => c,
Err(e) => return Err(anyhow!(e).context("VSOCK CID is not numeric")),
},
};
let port: u32 = match addr[1].parse::<u32>() {
Ok(r) => r,
Err(e) => return Err(anyhow!(e).context("VSOCK port is not numeric")),
};
client_create_vsock_fd(cid, port).map_err(|e| {
anyhow!(e).context("failed to create VSOCK connection (check agent is running)")
})?
}
_ => {
return Err(anyhow!("invalid server address URI scheme: {:?}", scheme));
}
};
Ok(ttrpc::client::Client::new(fd))
}
fn kata_service_agent(server_address: String) -> Result<AgentServiceClient> {
let ttrpc_client = create_ttrpc_client(server_address)?;
Ok(AgentServiceClient::new(ttrpc_client))
}
fn kata_service_health(server_address: String) -> Result<HealthClient> {
let ttrpc_client = create_ttrpc_client(server_address)?;
Ok(HealthClient::new(ttrpc_client))
}
fn announce(cfg: &Config) {
info!(sl!(), "announce"; "config" => format!("{:?}", cfg));
}
pub fn client(cfg: &Config, commands: Vec<&str>) -> Result<()> {
if commands.len() == 1 && commands[0] == "list" {
println!("Built-in commands:\n");
let mut builtin_cmds = get_builtin_cmd_details();
builtin_cmds.sort();
builtin_cmds.iter().for_each(|n| println!(" {}", n));
println!();
println!("Agent API commands:\n");
let mut agent_cmds = get_agent_cmd_details();
agent_cmds.sort();
agent_cmds.iter().for_each(|n| println!(" {}", n));
println!();
return Ok(());
}
announce(cfg);
// Create separate connections for each of the services provided
// by the agent.
let client = kata_service_agent(cfg.server_address.clone())?;
let health = kata_service_health(cfg.server_address.clone())?;
let mut options = Options::new();
let ttrpc_ctx = ttrpc::context::with_timeout(cfg.timeout_nano);
// Special-case loading the OCI config file so it is accessible
// to all commands.
let oci_spec_json = utils::get_oci_spec_json(cfg)?;
options.insert("spec".to_string(), oci_spec_json);
// Convenience option
options.insert("bundle-dir".to_string(), cfg.bundle_dir.clone());
info!(sl!(), "client setup complete";
"server-address" => cfg.server_address.to_string());
if cfg.interactive {
return interactive_client_loop(&cfg, &mut options, &client, &health, &ttrpc_ctx);
}
let mut repeat_count = 1;
for cmd in commands {
if cmd.starts_with(CMD_REPEAT) {
repeat_count = get_repeat_count(cmd);
continue;
}
let (result, shutdown) = handle_cmd(
&cfg,
&client,
&health,
&ttrpc_ctx,
repeat_count,
&mut options,
&cmd,
);
if result.is_err() {
return result;
}
if shutdown {
break;
}
// Reset
repeat_count = 1;
}
Ok(())
}
// Handle internal and agent API commands.
fn handle_cmd(
cfg: &Config,
client: &AgentServiceClient,
health: &HealthClient,
ctx: &Context,
repeat_count: i64,
options: &mut Options,
cmdline: &str,
) -> (Result<()>, bool) {
let fields: Vec<&str> = cmdline.split_whitespace().collect();
let cmd = fields[0];
if cmd == "" {
// Ignore empty commands
return (Ok(()), false);
}
let first = match cmd.chars().nth(0) {
Some(c) => c,
None => return (Err(anyhow!("failed to check command name")), false),
};
let args = if fields.len() > 1 {
fields[1..].join(" ")
} else {
String::new()
};
let mut count = 0;
let mut count_msg = String::new();
if repeat_count < 0 {
count_msg = "forever".to_string();
}
let mut error_count: u64 = 0;
let mut result: (Result<()>, bool);
loop {
if repeat_count > 0 {
count_msg = format!("{} of {}", count + 1, repeat_count);
}
info!(sl!(), "Run command {:} ({})", cmd, count_msg);
if first.is_lowercase() {
result = handle_builtin_cmd(cmd, &args);
} else {
result = handle_agent_cmd(ctx, client, health, options, cmd, &args);
}
if result.0.is_err() {
if cfg.ignore_errors {
error_count += 1;
debug!(sl!(), "ignoring error for command {:}: {:?}", cmd, result.0);
} else {
return result;
}
}
info!(
sl!(),
"Command {:} ({}) returned {:?}", cmd, count_msg, result
);
if repeat_count > 0 {
count += 1;
if count == repeat_count {
break;
}
}
}
if cfg.ignore_errors {
debug!(sl!(), "Error count for command {}: {}", cmd, error_count);
(Ok(()), result.1)
} else {
result
}
}
fn handle_builtin_cmd(cmd: &str, args: &str) -> (Result<()>, bool) {
let f = match get_builtin_cmd_func(&cmd) {
Ok(fp) => fp,
Err(e) => return (Err(e), false),
};
f(&args)
}
// Execute the ttRPC specified by the first field of "line". Return a result
// along with a bool which if set means the client should shutdown.
fn handle_agent_cmd(
ctx: &Context,
client: &AgentServiceClient,
health: &HealthClient,
options: &mut Options,
cmd: &str,
args: &str,
) -> (Result<()>, bool) {
let f = match get_agent_cmd_func(&cmd) {
Ok(fp) => fp,
Err(e) => return (Err(e), false),
};
let result = f(ctx, client, health, options, &args);
if result.is_err() {
return (result, false);
}
let shutdown = cmd == SHUTDOWN_CMD;
(Ok(()), shutdown)
}
fn interactive_client_loop(
cfg: &Config,
options: &mut Options,
client: &AgentServiceClient,
health: &HealthClient,
ctx: &Context,
) -> Result<()> {
let result = builtin_cmd_list("");
if result.0.is_err() {
return result.0;
}
let mut repeat_count: i64 = 1;
loop {
let cmdline =
readline("Enter command").map_err(|e| anyhow!(e).context("failed to read line"))?;
if cmdline == "" {
continue;
}
if cmdline.starts_with(CMD_REPEAT) {
repeat_count = get_repeat_count(&cmdline);
continue;
}
let (result, shutdown) =
handle_cmd(cfg, client, health, ctx, repeat_count, options, &cmdline);
if result.is_err() {
return result;
}
if shutdown {
break;
}
// Reset
repeat_count = 1;
}
Ok(())
}
fn readline(prompt: &str) -> std::result::Result<String, String> {
print!("{}: ", prompt);
io::stdout()
.flush()
.map_err(|e| format!("failed to flush: {:?}", e))?;
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.map_err(|e| format!("failed to read line: {:?}", e))?;
// Remove NL
Ok(line.trim_end().to_string())
}
fn agent_cmd_health_check(
ctx: &Context,
_client: &AgentServiceClient,
health: &HealthClient,
_options: &mut Options,
_args: &str,
) -> Result<()> {
let mut req = CheckRequest::default();
let ctx = clone_context(ctx);
// value unused
req.set_service("".to_string());
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = health
.check(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_health_version(
ctx: &Context,
_client: &AgentServiceClient,
health: &HealthClient,
_options: &mut Options,
_args: &str,
) -> Result<()> {
// XXX: Yes, the API is actually broken!
let mut req = CheckRequest::default();
let ctx = clone_context(ctx);
// value unused
req.set_service("".to_string());
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = health
.version(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_sandbox_create(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = CreateSandboxRequest::default();
let ctx = clone_context(ctx);
let sid = utils::get_option("sid", options, args);
req.set_sandbox_id(sid);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.create_sandbox(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_sandbox_destroy(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
_options: &mut Options,
_args: &str,
) -> Result<()> {
let req = DestroySandboxRequest::default();
let ctx = clone_context(ctx);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.destroy_sandbox(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_container_create(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = CreateContainerRequest::default();
let ctx = clone_context(ctx);
let cid = utils::get_option("cid", options, args);
let exec_id = utils::get_option("exec_id", options, args);
// FIXME: container create: add back "spec=file:///" support
let grpc_spec = utils::get_grpc_spec(options, &cid).map_err(|e| anyhow!(e))?;
req.set_container_id(cid);
req.set_exec_id(exec_id);
req.set_OCI(grpc_spec);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.create_container(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_container_remove(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = RemoveContainerRequest::default();
let cid = utils::get_option("cid", options, args);
let ctx = clone_context(ctx);
req.set_container_id(cid);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.remove_container(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_container_exec(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = ExecProcessRequest::default();
let ctx = clone_context(ctx);
let cid = utils::get_option("cid", options, args);
let exec_id = utils::get_option("exec_id", options, args);
let grpc_spec = utils::get_grpc_spec(options, &cid).map_err(|e| anyhow!(e))?;
let bundle_dir = options
.get("bundle-dir")
.ok_or("BUG: bundle-dir missing")
.map_err(|e| anyhow!(e))?;
let process = grpc_spec
.Process
.into_option()
.ok_or(format!(
"failed to get process from OCI spec: {}",
bundle_dir,
))
.map_err(|e| anyhow!(e))?;
req.set_container_id(cid);
req.set_exec_id(exec_id);
req.set_process(process);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.exec_process(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_container_stats(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = StatsContainerRequest::default();
let ctx = clone_context(ctx);
let cid = utils::get_option("cid", options, args);
req.set_container_id(cid);
debug!(sl!(), "sending request"; "request" => format!("{:?}", req));
let reply = client
.stats_container(ctx, &req)
.map_err(|e| anyhow!("{:?}", e).context(ERR_API_FAILED))?;
info!(sl!(), "response received";
"response" => format!("{:?}", reply));
Ok(())
}
fn agent_cmd_container_pause(
ctx: &Context,
client: &AgentServiceClient,
_health: &HealthClient,
options: &mut Options,
args: &str,
) -> Result<()> {
let mut req = PauseContainerRequest::default();
let ctx = clone_context(ctx);