use crate::error::Error;
use crate::model::{BootSpec, ExecRequest};
use crate::store::{INITFS_REFERENCE, Store, StoreError};
use crate::{checked, ffi, wire};
use std::os::fd::RawFd;
pub struct Session {
store: Store,
}
impl Session {
pub fn new(store: Store) -> Self {
Self { store }
}
pub fn store(&self) -> &Store {
&self.store
}
pub fn boot(&self, spec: &BootSpec) -> Result<(), Error> {
let _ = std::fs::remove_dir_all(self.store.container_dir(&spec.name));
let code = ffi::czbridge_boot(
&spec.name,
&self.store.root().display().to_string(),
&self.store.kernel().display().to_string(),
INITFS_REFERENCE,
&spec.image,
spec.resources.cpus as i32,
spec.resources.memory_in_bytes,
spec.rootfs_capacity_in_bytes,
&wire::lines(&wire::mounts(&spec.mounts)),
&wire::lines(&wire::sockets(&spec.sockets)),
&wire::lines(&spec.environment),
&wire::lines(&spec.arguments),
&wire::working_directory(spec.workdir.as_deref()),
&spec.network.ipv4_address,
&spec.network.ipv4_gateway,
);
checked(code)
.map(|_| ())
.map_err(|error| Error::failed(format!("boot {}", spec.name), error))
}
pub fn exec(&self, request: &ExecRequest) -> Result<i32, Error> {
let code = ffi::czbridge_exec(
&request.name,
&request.id,
&wire::lines(&request.arguments),
&wire::lines(&request.environment),
request.user.as_deref().unwrap_or(""),
&wire::working_directory(request.workdir.as_deref()),
request.term.as_deref().unwrap_or(""),
request.stdio.terminal,
request.stdio.stdin,
request.stdio.stdout,
request.stdio.stderr,
);
checked(code).map_err(|error| Error::failed("exec", error))
}
pub fn resize(&self, id: &str, terminal: RawFd) -> Result<(), Error> {
checked(ffi::czbridge_resize(id, terminal))
.map(|_| ())
.map_err(|error| Error::failed(format!("resize {id}"), error))
}
pub fn is_running(&self, name: &str) -> bool {
ffi::czbridge_is_running(name)
}
pub fn is_unpacked(&self, image: &str) -> Result<bool, Error> {
let code = ffi::czbridge_is_unpacked(&self.store.root().display().to_string(), image);
Ok(checked(code).map_err(|error| Error::failed("find the image", error))? == 1)
}
pub fn images(&self) -> Result<Vec<String>, StoreError> {
self.store.images()
}
pub fn version() -> String {
format!(
"Containerization {}, kernel {}",
crate::INITFS_VERSION,
crate::KERNEL_VERSION
)
}
}