Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/stackable-operator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Changed

- BREAKING: `ContainerBuilder::new` and `ContainerBuilder::default` are removed. Use
`ContainerBuilder::with_stackable_defaults`, which sets the container `securityContext` to
`SecurityContextBuilder::with_stackable_defaults`. Vector, git-sync and
`v2::builder::pod::container::new_container_builder` go through it. `ContainerBuilder::security_context`
replaces it ([#1347]).

[#1347]: https://github.com/stackabletech/operator-rs/pull/1347

## [0.123.0] - 2026-12-02

### Added
Expand Down
93 changes: 73 additions & 20 deletions crates/stackable-operator/src/builder/pod/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use snafu::{ResultExt as _, Snafu};
use {k8s_openapi::api::core::v1::PodSpec, std::collections::BTreeMap};

use crate::{
builder::pod::security::SecurityContextBuilder,
commons::product_image_selection::ResolvedProductImage,
validation::{self, is_lowercase_rfc_1123_label},
};
Expand Down Expand Up @@ -44,7 +45,7 @@ pub enum Error {
/// We are also choosing it over a [`BTreeMap`], because it is easier to debug for users, as logically
/// grouped volumeMounts (e.g. all volumeMounts related to S3) are near each other in the list instead of "just" being
/// sorted alphabetically.
#[derive(Clone, Default)]
#[derive(Clone)]
pub struct ContainerBuilder {
args: Option<Vec<String>>,
container_ports: Option<Vec<ContainerPort>>,
Expand All @@ -65,12 +66,36 @@ pub struct ContainerBuilder {
}

impl ContainerBuilder {
pub fn new(name: &str) -> Result<Self> {
Self::validate_container_name(name)?;
Ok(Self {
name: name.to_string(),
..Self::default()
})
/// Starts the container with [`SecurityContextBuilder::with_stackable_defaults`] as its security
/// context. [`Self::security_context`] replaces the whole context, so a caller that needs another
/// field starts from [`SecurityContextBuilder::with_stackable_defaults`] and adds it.
///
/// Returns an error if `name` is not a lowercase RFC 1123 label.
pub fn with_stackable_defaults(name: impl Into<String>) -> Result<Self> {
let name = name.into();
Self::validate_container_name(&name)?;

let mut builder = Self {
name,
args: None,
container_ports: None,
command: None,
env: None,
image: None,
image_pull_policy: None,
resources: None,
volume_mounts: IndexMap::new(),
readiness_probe: None,
liveness_probe: None,
startup_probe: None,
lifecycle: None,
security_context: None,
};

// Set through the builder function, so that the same function can override it.
builder.security_context(SecurityContextBuilder::with_stackable_defaults().build());

Ok(builder)
}

pub fn image(&mut self, image: impl Into<String>) -> &mut Self {
Expand Down Expand Up @@ -438,7 +463,7 @@ impl fmt::Display for FieldPathEnvVar {

#[cfg(test)]
mod tests {
use k8s_openapi::api::core::v1::ExecAction;
use k8s_openapi::api::core::v1::{Capabilities, ExecAction};

use super::*;
use crate::{
Expand All @@ -465,7 +490,7 @@ mod tests {
.with_resource(ResourceRequirementsType::Limits, "nvidia.com/gpu", "1")
.build();

let container = ContainerBuilder::new("testcontainer")
let container = ContainerBuilder::with_stackable_defaults("testcontainer")
.expect("ContainerBuilder not created")
.add_env_var("foo", "bar")
.add_env_var_from_config_map("envFromConfigMap", "my-configmap", "my-key")
Expand Down Expand Up @@ -527,7 +552,7 @@ mod tests {
}),
..Default::default()
};
let container = ContainerBuilder::new("testcontainer")
let container = ContainerBuilder::with_stackable_defaults("testcontainer")
.expect("ContainerBuilder not created")
.lifecycle_post_start(post_start.clone())
.lifecycle_pre_stop(pre_stop.clone())
Expand Down Expand Up @@ -580,7 +605,7 @@ mod tests {
let long_container_name =
"lengthexceededlengthexceededlengthexceededlengthexceededlengthex";
assert_eq!(long_container_name.len(), 64); // 63 characters is the limit for container names
let result = ContainerBuilder::new(long_container_name);
let result = ContainerBuilder::with_stackable_defaults(long_container_name);
if let Error::InvalidContainerName {
container_name,
source,
Expand All @@ -597,37 +622,37 @@ mod tests {
// One characters shorter name is valid
let max_len_container_name: String = long_container_name.chars().skip(1).collect();
assert_eq!(max_len_container_name.len(), 63);
assert!(ContainerBuilder::new(&max_len_container_name).is_ok());
assert!(ContainerBuilder::with_stackable_defaults(&max_len_container_name).is_ok());
}

#[test]
fn name_alphabet_only() {
ContainerBuilder::new("okname").unwrap();
ContainerBuilder::with_stackable_defaults("okname").unwrap();
}

#[test]
fn name_hyphen() {
assert!(ContainerBuilder::new("name-with-hyphen").is_ok());
assert!(ContainerBuilder::with_stackable_defaults("name-with-hyphen").is_ok());
assert_container_builder_err(
ContainerBuilder::new("ends-with-hyphen-"),
ContainerBuilder::with_stackable_defaults("ends-with-hyphen-"),
&format!(r#"regex used for validation is "{LOWERCASE_RFC_1123_LABEL_FMT}""#),
);
assert_container_builder_err(
ContainerBuilder::new("-starts-with-hyphen"),
ContainerBuilder::with_stackable_defaults("-starts-with-hyphen"),
&format!(r#"regex used for validation is "{LOWERCASE_RFC_1123_LABEL_FMT}""#),
);
}

#[test]
fn name_contains_number() {
assert!(ContainerBuilder::new("1name-0-name1").is_ok());
assert!(ContainerBuilder::with_stackable_defaults("1name-0-name1").is_ok());
}

#[test]
fn name_contains_underscore() {
assert!(ContainerBuilder::new("name_name").is_err());
assert!(ContainerBuilder::with_stackable_defaults("name_name").is_err());
assert_container_builder_err(
ContainerBuilder::new("name_name"),
ContainerBuilder::with_stackable_defaults("name_name"),
&format!(
r#"(e.g. "example-label", or "1-label-1", regex used for validation is "{LOWERCASE_RFC_1123_LABEL_FMT}""#
),
Expand All @@ -644,14 +669,42 @@ mod tests {
.with_resource(ResourceRequirementsType::Limits, "nvidia.com/gpu", "1")
.build();

let container = ContainerBuilder::new("testcontainer")
let container = ContainerBuilder::with_stackable_defaults("testcontainer")
.expect("ContainerBuilder not created")
.resources(resources.clone())
.build();

assert_eq!(container.resources, Some(resources));
}

#[test]
fn security_context_defaults_and_override() {
let container = ContainerBuilder::with_stackable_defaults("hardened")
.expect("valid container name")
.build();
assert_eq!(
container.security_context,
Some(SecurityContext {
allow_privilege_escalation: Some(false),
capabilities: Some(Capabilities {
drop: Some(vec!["ALL".to_owned()]),
..Default::default()
}),
..Default::default()
})
);

let privileged = SecurityContext {
privileged: Some(true),
..Default::default()
};
let container = ContainerBuilder::with_stackable_defaults("privileged")
.expect("valid container name")
.security_context(privileged.clone())
.build();
assert_eq!(container.security_context, Some(privileged));
}

/// Panics if given container builder constructor result is not [Err] with error message
/// containing expected violation.
fn assert_container_builder_err(
Expand Down
18 changes: 14 additions & 4 deletions crates/stackable-operator/src/builder/pod/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ impl PodBuilder {
/// let pod = PodBuilder::new()
/// .metadata_default()
/// .add_container(
/// ContainerBuilder::new("container")
/// ContainerBuilder::with_stackable_defaults("container")
/// .unwrap()
/// .add_volume_mount("listener", "/path/to/volume")
/// .unwrap()
Expand All @@ -368,6 +368,11 @@ impl PodBuilder {
/// affinity: {}
/// containers:
/// - name: container
/// securityContext:
/// allowPrivilegeEscalation: false
/// capabilities:
/// drop:
/// - ALL
/// volumeMounts:
/// - mountPath: /path/to/volume
/// name: listener
Expand Down Expand Up @@ -438,7 +443,7 @@ impl PodBuilder {
/// let pod = PodBuilder::new()
/// .metadata_default()
/// .add_container(
/// ContainerBuilder::new("container")
/// ContainerBuilder::with_stackable_defaults("container")
/// .unwrap()
/// .add_volume_mount("listener", "/path/to/volume")
/// .unwrap()
Expand All @@ -458,6 +463,11 @@ impl PodBuilder {
/// affinity: {}
/// containers:
/// - name: container
/// securityContext:
/// allowPrivilegeEscalation: false
/// capabilities:
/// drop:
/// - ALL
/// volumeMounts:
/// - mountPath: /path/to/volume
/// name: listener
Expand Down Expand Up @@ -661,7 +671,7 @@ mod tests {
.with_memory_limit("128Mi")
.build();

ContainerBuilder::new("container")
ContainerBuilder::with_stackable_defaults("container")
.expect("ContainerBuilder not created")
.image("private-company/product:2.4.14")
.resources(resources)
Expand Down Expand Up @@ -718,7 +728,7 @@ mod tests {

#[rstest]
fn builder(pod_affinity: PodAffinity, dummy_container: Container) {
let init_container = ContainerBuilder::new("init-containername")
let init_container = ContainerBuilder::with_stackable_defaults("init-containername")
.expect("ContainerBuilder not created")
.image("stackable/zookeeper:2.4.14")
.build();
Expand Down
6 changes: 4 additions & 2 deletions crates/stackable-operator/src/builder/pod/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ impl SecurityContextBuilder {
/// * `allowPrivilegeEscalation: false`
/// * `capabilities.drop: [ALL]`
///
/// Neither field exists on [`PodSecurityContext`],
/// so both have to be set on every container to take effect.
/// Neither field exists on [`PodSecurityContext`], so both have to be set on every container
/// to take effect. [`ContainerBuilder::with_stackable_defaults`] starts every container with them.
///
/// [`ContainerBuilder::with_stackable_defaults`]: crate::builder::pod::container::ContainerBuilder::with_stackable_defaults
///
/// We intentionally don't set `runAsNonRoot` or `seccompProfile`, as we set those in
/// [`PodSecurityContextBuilder::with_stackable_defaults`] already and don't want to confuse
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading