use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Number, Value};
use crate::did::DidNostr;
use crate::encoding;
use crate::pod_path::{ParsePodPathError, PodPath};
pub const MAX_CONTAINERS: usize = 8;
pub const MIN_TIMEOUT_SECS: u64 = 240;
pub const MIN_MEMORY_BYTES: u64 = 6 * 1024 * 1024;
pub const MEMORY_STEP_BYTES: u64 = 4096;
pub const MAX_LABEL_CHARS: usize = 128;
const IMAGE_ID_PREFIX: &str = "sha256:";
const STAND_IN_OWNER: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ImageId(String);
impl ImageId {
pub fn from_digest(digest: [u8; 32]) -> Self {
Self(format!("{IMAGE_ID_PREFIX}{}", hex::encode(digest)))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn hex(&self) -> &str {
&self.0[IMAGE_ID_PREFIX.len()..]
}
}
impl FromStr for ImageId {
type Err = ParseImageIdError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let digits = text
.strip_prefix(IMAGE_ID_PREFIX)
.ok_or(ParseImageIdError)?;
if digits.len() == 64 && encoding::is_lower_hex(digits) {
Ok(Self(text.to_owned()))
} else {
Err(ParseImageIdError)
}
}
}
impl fmt::Display for ImageId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for ImageId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ImageId({})", self.0)
}
}
impl Serialize for ImageId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for ImageId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("image id is not sha256: followed by 64 lower-case hex digits")]
pub struct ParseImageIdError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MilliCpus(u32);
impl MilliCpus {
pub const fn new(millicpus: u32) -> Self {
Self(millicpus)
}
pub const fn get(self) -> u32 {
self.0
}
pub fn cpu_max(self) -> String {
format!("{} 100000", u64::from(self.0) * 100)
}
pub fn nano_cpus(self) -> u64 {
u64::from(self.0) * 1_000_000
}
fn from_number(number: &Number) -> Result<Self, CpusError> {
if let Some(whole) = number.as_u64() {
return whole
.checked_mul(1000)
.and_then(|m| u32::try_from(m).ok())
.map(Self)
.ok_or(CpusError::TooLarge);
}
if number.as_i64().is_some() {
return Err(CpusError::NotPositive);
}
let value = number.as_f64().ok_or(CpusError::Precision)?;
if value.is_sign_negative() {
return Err(CpusError::NotPositive);
}
let text = value.to_string();
let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
if fraction.len() > 3 {
return Err(CpusError::Precision);
}
let whole: u32 = whole.parse().map_err(|_| CpusError::TooLarge)?;
let mut thousandths = 0u32;
for (place, digit) in fraction.bytes().enumerate() {
let scale = match place {
0 => 100,
1 => 10,
_ => 1,
};
thousandths += u32::from(digit - b'0') * scale;
}
whole
.checked_mul(1000)
.and_then(|m| m.checked_add(thousandths))
.map(Self)
.ok_or(CpusError::TooLarge)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CpusError {
NotPositive,
Precision,
TooLarge,
}
impl Serialize for MilliCpus {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let whole = self.0 / 1000;
let thousandths = self.0 % 1000;
if thousandths == 0 {
return serializer.serialize_u32(whole);
}
serializer.serialize_f64(f64::from(self.0) / 1000.0)
}
}
impl<'de> Deserialize<'de> for MilliCpus {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let number = Number::deserialize(deserializer)?;
Self::from_number(&number).map_err(|e| {
serde::de::Error::custom(match e {
CpusError::NotPositive => "cpus is negative",
CpusError::Precision => "cpus has more than three decimal places",
CpusError::TooLarge => "cpus is too large",
})
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ManifestProfile {
Job,
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum WorkspaceMode {
#[default]
None,
Read,
Write,
}
impl WorkspaceMode {
pub const ALL: [Self; 3] = [Self::None, Self::Read, Self::Write];
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Read => "read",
Self::Write => "write",
}
}
}
impl fmt::Display for WorkspaceMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for WorkspaceMode {
type Err = ParseNameError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::ALL
.into_iter()
.find(|m| m.as_str() == text)
.ok_or(ParseNameError)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AclMode {
Read,
Write,
}
impl AclMode {
pub fn as_str(self) -> &'static str {
match self {
Self::Read => "Read",
Self::Write => "Write",
}
}
pub fn iri(self) -> &'static str {
match self {
Self::Read => "acl:Read",
Self::Write => "acl:Write",
}
}
}
impl fmt::Display for AclMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum PodMethod {
Get,
Head,
Put,
Delete,
}
impl PodMethod {
pub const ALL: [Self; 4] = [Self::Get, Self::Head, Self::Put, Self::Delete];
pub fn as_str(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Head => "HEAD",
Self::Put => "PUT",
Self::Delete => "DELETE",
}
}
pub fn needs_write(self) -> bool {
matches!(self, Self::Put | Self::Delete)
}
}
impl fmt::Display for PodMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for PodMethod {
type Err = ParseNameError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::ALL
.into_iter()
.find(|m| m.as_str() == text)
.ok_or(ParseNameError)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("not a recognised name")]
pub struct ParseNameError;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContainerPath(String);
impl ContainerPath {
pub fn parse(text: &str) -> Result<Self, ContainerPathError> {
if text.is_empty() {
return Err(ContainerPathError::Empty);
}
if text.starts_with('/') {
return Err(ContainerPathError::LeadingSlash);
}
if text.contains('%') {
return Err(ContainerPathError::Percent);
}
if !text.ends_with('/') {
return Err(ContainerPathError::NotAContainer);
}
let full = PodPath::parse(&format!("/pods/{STAND_IN_OWNER}/{text}"))
.map_err(ContainerPathError::Shape)?;
if !full.is_container() {
return Err(ContainerPathError::NotAContainer);
}
if full.is_acl() {
return Err(ContainerPathError::Acl);
}
if text.split('/').next() == Some("profile") {
return Err(ContainerPathError::Profile);
}
Ok(Self(text.to_owned()))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn under(&self, owner: &DidNostr) -> PodPath {
PodPath::parse(&format!("/pods/{}/{}", owner.to_hex(), self.0))
.expect("a checked container path is valid under every owner")
}
}
impl FromStr for ContainerPath {
type Err = ContainerPathError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::parse(text)
}
}
impl fmt::Display for ContainerPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for ContainerPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ContainerPath({})", self.0)
}
}
impl AsRef<str> for ContainerPath {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Serialize for ContainerPath {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for ContainerPath {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ContainerPathError {
#[error("container path is empty")]
Empty,
#[error("container path starts with /")]
LeadingSlash,
#[error("container path holds %")]
Percent,
#[error("container path does not name a container")]
NotAContainer,
#[error("container path breaks the pod path rule: {0}")]
Shape(ParsePodPathError),
#[error("container path is an ACL")]
Acl,
#[error("container path is under profile/")]
Profile,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContainerGrant {
pub path: ContainerPath,
pub modes: Vec<AclMode>,
pub operations: Vec<PodMethod>,
}
impl ContainerGrant {
pub fn allows(&self, method: PodMethod) -> bool {
self.operations.contains(&method)
}
pub fn writes(&self) -> bool {
self.modes.contains(&AclMode::Write)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestLimits {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpus: Option<MilliCpus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory_bytes: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pids: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tmp_bytes: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_secs: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JobLimits {
pub cpus: MilliCpus,
pub memory_bytes: u64,
pub pids: u64,
pub tmp_bytes: u64,
pub timeout_secs: u64,
}
impl JobLimits {
pub const DEFAULT: Self = Self {
cpus: MilliCpus::new(1000),
memory_bytes: 512 * 1024 * 1024,
pids: 128,
tmp_bytes: 64 * 1024 * 1024,
timeout_secs: 600,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct JobCeilings {
pub cpus: MilliCpus,
pub memory_bytes: u64,
pub pids: u64,
pub tmp_bytes: u64,
pub timeout_secs: u64,
}
impl JobCeilings {
pub const DEFAULT: Self = Self {
cpus: MilliCpus::new(4000),
memory_bytes: 4 * 1024 * 1024 * 1024,
pids: 512,
tmp_bytes: 1024 * 1024 * 1024,
timeout_secs: 3600,
};
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub name: String,
pub version: String,
pub image_id: ImageId,
pub profile: ManifestProfile,
pub containers: Vec<ContainerGrant>,
pub workspace: WorkspaceMode,
pub max_body_bytes: u64,
#[serde(default)]
pub limits: ManifestLimits,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ValidManifest {
manifest: Manifest,
limits: JobLimits,
}
impl ValidManifest {
pub fn parse(json: &[u8], ceilings: &JobCeilings) -> Result<Self, ManifestError> {
let value: Value =
serde_json::from_slice(json).map_err(|_| ManifestError::new(ManifestRule::Json, ""))?;
Self::from_value(&value, ceilings)
}
pub fn from_value(value: &Value, ceilings: &JobCeilings) -> Result<Self, ManifestError> {
let manifest = read_manifest(value)?;
let limits = effective_limits(&manifest.limits);
check_limits(&limits, ceilings)?;
Ok(Self { manifest, limits })
}
pub fn check_ceilings(&self, ceilings: &JobCeilings) -> Result<(), ManifestError> {
check_limits(&self.limits, ceilings)
}
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
pub fn limits(&self) -> JobLimits {
self.limits
}
pub fn into_manifest(self) -> Manifest {
self.manifest
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self.manifest).expect("a manifest always serialises")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ManifestRule {
Json,
UnknownMember,
MissingMember,
WrongType,
Label,
ImageId,
Profile,
ContainerCount,
Path,
Mode,
ModeSet,
Operation,
OperationSet,
WriteOperationWithoutWrite,
DuplicatePath,
Workspace,
MaxBodyBytes,
LimitNotPositive,
LimitAboveCeiling,
MemoryNotUsable,
TmpNotBelowMemory,
TimeoutTooShort,
}
impl ManifestRule {
pub fn as_str(self) -> &'static str {
match self {
Self::Json => "json",
Self::UnknownMember => "unknown_member",
Self::MissingMember => "missing_member",
Self::WrongType => "wrong_type",
Self::Label => "label",
Self::ImageId => "image_id",
Self::Profile => "profile",
Self::ContainerCount => "container_count",
Self::Path => "path",
Self::Mode => "mode",
Self::ModeSet => "mode_set",
Self::Operation => "operation",
Self::OperationSet => "operation_set",
Self::WriteOperationWithoutWrite => "write_operation_without_write",
Self::DuplicatePath => "duplicate_path",
Self::Workspace => "workspace",
Self::MaxBodyBytes => "max_body_bytes",
Self::LimitNotPositive => "limit_not_positive",
Self::LimitAboveCeiling => "limit_above_ceiling",
Self::MemoryNotUsable => "memory_not_usable",
Self::TmpNotBelowMemory => "tmp_not_below_memory",
Self::TimeoutTooShort => "timeout_too_short",
}
}
}
impl fmt::Display for ManifestRule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
#[error("manifest refused at {field}: {rule}")]
pub struct ManifestError {
rule: ManifestRule,
field: String,
}
impl ManifestError {
fn new(rule: ManifestRule, field: impl Into<String>) -> Self {
Self {
rule,
field: field.into(),
}
}
pub fn rule(&self) -> ManifestRule {
self.rule
}
pub fn field(&self) -> &str {
&self.field
}
}
const MANIFEST_MEMBERS: [&str; 8] = [
"name",
"version",
"image_id",
"profile",
"containers",
"workspace",
"max_body_bytes",
"limits",
];
const CONTAINER_MEMBERS: [&str; 3] = ["path", "modes", "operations"];
const LIMIT_MEMBERS: [&str; 5] = ["cpus", "memory_bytes", "pids", "tmp_bytes", "timeout_secs"];
fn object<'v>(value: &'v Value, field: &str) -> Result<&'v Map<String, Value>, ManifestError> {
value
.as_object()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))
}
fn no_unknown(map: &Map<String, Value>, known: &[&str], prefix: &str) -> Result<(), ManifestError> {
match map.keys().find(|k| !known.contains(&k.as_str())) {
Some(key) => Err(ManifestError::new(
ManifestRule::UnknownMember,
join_field(prefix, key),
)),
None => Ok(()),
}
}
fn join_field(prefix: &str, key: &str) -> String {
if prefix.is_empty() {
key.to_owned()
} else {
format!("{prefix}.{key}")
}
}
fn required<'v>(
map: &'v Map<String, Value>,
key: &str,
field: &str,
) -> Result<&'v Value, ManifestError> {
map.get(key)
.ok_or_else(|| ManifestError::new(ManifestRule::MissingMember, field))
}
fn string<'v>(value: &'v Value, field: &str) -> Result<&'v str, ManifestError> {
value
.as_str()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))
}
fn label(value: &Value, field: &str) -> Result<String, ManifestError> {
let text = string(value, field)?;
if text.is_empty()
|| text.chars().count() > MAX_LABEL_CHARS
|| text.chars().any(char::is_control)
{
return Err(ManifestError::new(ManifestRule::Label, field));
}
Ok(text.to_owned())
}
fn positive(value: &Value, field: &str, not_positive: ManifestRule) -> Result<u64, ManifestError> {
let number = value
.as_number()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))?;
number
.as_u64()
.filter(|n| *n > 0)
.ok_or_else(|| ManifestError::new(not_positive, field))
}
fn read_manifest(value: &Value) -> Result<Manifest, ManifestError> {
let map = value
.as_object()
.ok_or_else(|| ManifestError::new(ManifestRule::Json, ""))?;
no_unknown(map, &MANIFEST_MEMBERS, "")?;
let name = label(required(map, "name", "name")?, "name")?;
let version = label(required(map, "version", "version")?, "version")?;
let image_id = string(required(map, "image_id", "image_id")?, "image_id")?
.parse()
.map_err(|_| ManifestError::new(ManifestRule::ImageId, "image_id"))?;
let profile = match string(required(map, "profile", "profile")?, "profile")? {
"job" => ManifestProfile::Job,
_ => return Err(ManifestError::new(ManifestRule::Profile, "profile")),
};
let containers = read_containers(required(map, "containers", "containers")?)?;
let workspace = string(required(map, "workspace", "workspace")?, "workspace")?
.parse()
.map_err(|_| ManifestError::new(ManifestRule::Workspace, "workspace"))?;
let max_body_bytes = positive(
required(map, "max_body_bytes", "max_body_bytes")?,
"max_body_bytes",
ManifestRule::MaxBodyBytes,
)?;
let limits = match map.get("limits") {
Some(limits) => read_limits(limits)?,
None => ManifestLimits::default(),
};
Ok(Manifest {
name,
version,
image_id,
profile,
containers,
workspace,
max_body_bytes,
limits,
})
}
fn read_containers(value: &Value) -> Result<Vec<ContainerGrant>, ManifestError> {
let entries = value
.as_array()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, "containers"))?;
if entries.is_empty() || entries.len() > MAX_CONTAINERS {
return Err(ManifestError::new(
ManifestRule::ContainerCount,
"containers",
));
}
let mut grants: Vec<ContainerGrant> = Vec::with_capacity(entries.len());
for (index, entry) in entries.iter().enumerate() {
let prefix = format!("containers[{index}]");
let grant = read_container(entry, &prefix)?;
if grants.iter().any(|g| g.path == grant.path) {
return Err(ManifestError::new(
ManifestRule::DuplicatePath,
format!("{prefix}.path"),
));
}
grants.push(grant);
}
Ok(grants)
}
fn read_container(value: &Value, prefix: &str) -> Result<ContainerGrant, ManifestError> {
let map = object(value, prefix)?;
no_unknown(map, &CONTAINER_MEMBERS, prefix)?;
let path_field = format!("{prefix}.path");
let path = string(required(map, "path", &path_field)?, &path_field)?
.parse()
.map_err(|_| ManifestError::new(ManifestRule::Path, path_field.as_str()))?;
let modes = read_modes(map, prefix)?;
let operations = read_operations(map, prefix)?;
if operations.iter().any(|op| op.needs_write()) && !modes.contains(&AclMode::Write) {
return Err(ManifestError::new(
ManifestRule::WriteOperationWithoutWrite,
format!("{prefix}.operations"),
));
}
Ok(ContainerGrant {
path,
modes,
operations,
})
}
fn string_list<'v>(
map: &'v Map<String, Value>,
key: &str,
field: &str,
) -> Result<Vec<&'v str>, ManifestError> {
let list = required(map, key, field)?
.as_array()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))?;
list.iter().map(|item| string(item, field)).collect()
}
fn read_modes(map: &Map<String, Value>, prefix: &str) -> Result<Vec<AclMode>, ManifestError> {
let field = format!("{prefix}.modes");
let names = string_list(map, "modes", &field)?;
let mut modes = Vec::with_capacity(names.len());
for name in names {
modes.push(match name {
"Read" => AclMode::Read,
"Write" => AclMode::Write,
_ => return Err(ManifestError::new(ManifestRule::Mode, field)),
});
}
if modes != [AclMode::Read] && modes != [AclMode::Read, AclMode::Write] {
return Err(ManifestError::new(ManifestRule::ModeSet, field));
}
Ok(modes)
}
fn read_operations(
map: &Map<String, Value>,
prefix: &str,
) -> Result<Vec<PodMethod>, ManifestError> {
let field = format!("{prefix}.operations");
let names = string_list(map, "operations", &field)?;
let mut operations: Vec<PodMethod> = Vec::with_capacity(names.len());
for name in names {
let op: PodMethod = name
.parse()
.map_err(|_| ManifestError::new(ManifestRule::Operation, field.as_str()))?;
if operations.contains(&op) {
return Err(ManifestError::new(ManifestRule::OperationSet, field));
}
operations.push(op);
}
if operations.is_empty() {
return Err(ManifestError::new(ManifestRule::OperationSet, field));
}
Ok(operations)
}
fn read_limits(value: &Value) -> Result<ManifestLimits, ManifestError> {
let map = object(value, "limits")?;
no_unknown(map, &LIMIT_MEMBERS, "limits")?;
let cpus = match map.get("cpus") {
None => None,
Some(value) => {
let number = value
.as_number()
.ok_or_else(|| ManifestError::new(ManifestRule::WrongType, "limits.cpus"))?;
let cpus = MilliCpus::from_number(number)
.ok()
.filter(|c| c.get() > 0)
.ok_or_else(|| ManifestError::new(ManifestRule::LimitNotPositive, "limits.cpus"))?;
Some(cpus)
}
};
let int = |key: &str| -> Result<Option<u64>, ManifestError> {
let field = format!("limits.{key}");
map.get(key)
.map(|v| positive(v, &field, ManifestRule::LimitNotPositive))
.transpose()
};
Ok(ManifestLimits {
cpus,
memory_bytes: int("memory_bytes")?,
pids: int("pids")?,
tmp_bytes: int("tmp_bytes")?,
timeout_secs: int("timeout_secs")?,
})
}
fn effective_limits(limits: &ManifestLimits) -> JobLimits {
let d = JobLimits::DEFAULT;
JobLimits {
cpus: limits.cpus.unwrap_or(d.cpus),
memory_bytes: limits.memory_bytes.unwrap_or(d.memory_bytes),
pids: limits.pids.unwrap_or(d.pids),
tmp_bytes: limits.tmp_bytes.unwrap_or(d.tmp_bytes),
timeout_secs: limits.timeout_secs.unwrap_or(d.timeout_secs),
}
}
fn check_limits(limits: &JobLimits, ceilings: &JobCeilings) -> Result<(), ManifestError> {
let above = |field: &str| ManifestError::new(ManifestRule::LimitAboveCeiling, field);
if limits.cpus > ceilings.cpus {
return Err(above("limits.cpus"));
}
if limits.memory_bytes > ceilings.memory_bytes {
return Err(above("limits.memory_bytes"));
}
if limits.pids > ceilings.pids {
return Err(above("limits.pids"));
}
if limits.tmp_bytes > ceilings.tmp_bytes {
return Err(above("limits.tmp_bytes"));
}
if limits.timeout_secs > ceilings.timeout_secs {
return Err(above("limits.timeout_secs"));
}
if limits.memory_bytes < MIN_MEMORY_BYTES
|| !limits.memory_bytes.is_multiple_of(MEMORY_STEP_BYTES)
{
return Err(ManifestError::new(
ManifestRule::MemoryNotUsable,
"limits.memory_bytes",
));
}
if limits.tmp_bytes >= limits.memory_bytes {
return Err(ManifestError::new(
ManifestRule::TmpNotBelowMemory,
"limits.tmp_bytes",
));
}
if limits.timeout_secs < MIN_TIMEOUT_SECS {
return Err(ManifestError::new(
ManifestRule::TimeoutTooShort,
"limits.timeout_secs",
));
}
Ok(())
}