-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathinstance.rs
171 lines (147 loc) · 6.72 KB
/
instance.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
use std::marker::PhantomData;
use std::path::Path;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use anyhow::Context;
use chrono::{DateTime, Utc};
use libcontainer::container::builder::ContainerBuilder;
use libcontainer::container::Container;
use libcontainer::signal::Signal;
use libcontainer::syscall::syscall::SyscallType;
use nix::errno::Errno;
use nix::sys::wait::{waitid, Id as WaitID, WaitPidFlag, WaitStatus};
use nix::unistd::Pid;
use oci_spec::image::Platform;
use zygote::{WireError, Zygote};
use crate::container::Engine;
use crate::sandbox::async_utils::AmbientRuntime as _;
use crate::sandbox::instance_utils::determine_rootdir;
use crate::sandbox::sync::WaitableCell;
use crate::sandbox::{
containerd, Error as SandboxError, Instance as SandboxInstance, InstanceConfig,
};
use crate::sys::container::executor::Executor;
use crate::sys::stdio::open;
const DEFAULT_CONTAINER_ROOT_DIR: &str = "/run/containerd";
pub struct Instance<E: Engine> {
exit_code: WaitableCell<(u32, DateTime<Utc>)>,
container: Mutex<Container>,
id: String,
_phantom: PhantomData<E>,
}
impl<E: Engine + Default> SandboxInstance for Instance<E> {
type Engine = E;
#[cfg_attr(feature = "tracing", tracing::instrument(parent = tracing::Span::current(), skip_all, level = "Info"))]
fn new(id: String, cfg: &InstanceConfig) -> Result<Self, SandboxError> {
// check if container is OCI image with wasm layers and attempt to read the module
let (modules, platform) = containerd::Client::connect(cfg.get_containerd_address(), &cfg.get_namespace()).block_on()?
.load_modules(&id, &E::default())
.block_on()
.unwrap_or_else(|e| {
log::warn!("Error obtaining wasm layers for container {id}. Will attempt to use files inside container image. Error: {e}");
(vec![], Platform::default())
});
let (root, state) = Zygote::global()
.run(
|(id, cfg, modules, platform)| -> Result<_, WireError> {
let namespace = cfg.get_namespace();
let bundle = cfg.get_bundle().to_path_buf();
let rootdir = Path::new(DEFAULT_CONTAINER_ROOT_DIR).join(E::name());
let rootdir = determine_rootdir(&bundle, &namespace, rootdir)?;
let engine = E::default();
let mut builder = ContainerBuilder::new(id.clone(), SyscallType::Linux)
.with_executor(Executor::new(engine, modules, platform))
.with_root_path(rootdir.clone())?;
if let Ok(f) = open(cfg.get_stdin()) {
builder = builder.with_stdin(f);
}
if let Ok(f) = open(cfg.get_stdout()) {
builder = builder.with_stdout(f);
}
if let Ok(f) = open(cfg.get_stderr()) {
builder = builder.with_stderr(f);
}
let Container { root, state } = builder
.as_init(&bundle)
.as_sibling(true)
.with_systemd(false)
.build()?;
// Container is not serializable, but its parts are
Ok((root, state))
},
(id.clone(), cfg.clone(), modules, platform),
)
.map_err(|e| SandboxError::Others(e.to_string()))?;
let container = Container { root, state };
Ok(Self {
id,
exit_code: WaitableCell::new(),
container: Mutex::new(container),
_phantom: Default::default(),
})
}
/// Start the instance
/// The returned value should be a unique ID (such as a PID) for the instance.
/// Nothing internally should be using this ID, but it is returned to containerd where a user may want to use it.
#[cfg_attr(feature = "tracing", tracing::instrument(parent = tracing::Span::current(), skip_all, level = "Info"))]
fn start(&self) -> Result<u32, SandboxError> {
log::info!("starting instance: {}", self.id);
// make sure we have an exit code by the time we finish (even if there's a panic)
let guard = self.exit_code.set_guard_with(|| (137, Utc::now()));
let mut container = self.container.lock().expect("Poisoned mutex");
let pid = container.pid().context("failed to get pid")?.as_raw();
container.start()?;
let exit_code = self.exit_code.clone();
thread::spawn(move || {
// move the exit code guard into this thread
let _guard = guard;
let status = match waitid(WaitID::Pid(Pid::from_raw(pid)), WaitPidFlag::WEXITED) {
Ok(WaitStatus::Exited(_, status)) => status,
Ok(WaitStatus::Signaled(_, sig, _)) => sig as i32,
Ok(_) => 0,
Err(Errno::ECHILD) => {
log::info!("no child process");
0
}
Err(e) => {
log::error!("waitpid failed: {e}");
137
}
} as u32;
let _ = exit_code.set((status, Utc::now()));
});
Ok(pid as u32)
}
/// Send a signal to the instance
#[cfg_attr(feature = "tracing", tracing::instrument(parent = tracing::Span::current(), skip_all, level = "Info"))]
fn kill(&self, signal: u32) -> Result<(), SandboxError> {
log::info!("sending signal {signal} to instance: {}", self.id);
let signal = Signal::try_from(signal as i32).map_err(|err| {
SandboxError::InvalidArgument(format!("invalid signal number: {}", err))
})?;
self.container
.lock()
.expect("Poisoned mutex")
.kill(signal, true)?;
Ok(())
}
/// Delete any reference to the instance
/// This is called after the instance has exited.
#[cfg_attr(feature = "tracing", tracing::instrument(parent = tracing::Span::current(), skip_all, level = "Info"))]
fn delete(&self) -> Result<(), SandboxError> {
log::info!("deleting instance: {}", self.id);
self.container
.lock()
.expect("Poisoned mutex")
.delete(true)?;
Ok(())
}
/// Waits for the instance to finish and returns its exit code
/// Returns None if the timeout is reached before the instance has finished.
/// This is a blocking call.
#[cfg_attr(feature = "tracing", tracing::instrument(parent = tracing::Span::current(), skip(self, t), level = "Info"))]
fn wait_timeout(&self, t: impl Into<Option<Duration>>) -> Option<(u32, DateTime<Utc>)> {
self.exit_code.wait_timeout(t).copied()
}
}