Skip to content
Merged
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
9 changes: 9 additions & 0 deletions apps/piquelctl/src/editing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,11 @@ pub(crate) struct SetJobArgs {
/// access, or `read-only` for a new job.
#[arg(long, value_name = "ACCESS", value_parser = volume_access())]
volume_access: Option<JobVolumeAccess>,
/// `on` to stop the job's service before the job runs, once its startup
/// dependencies are ready, until the rollout; `off` to run it beside the
/// service. By default, the job's current setting, or `off` for a new job.
#[arg(long, value_name = "on|off", value_parser = on_off())]
stop_service: Option<bool>,
/// Environment variable for the job only, added to its service's. Repeat
/// it to set several. They replace the job's own variables, which it keeps
/// when you pass none.
Expand Down Expand Up @@ -1732,6 +1737,10 @@ impl JobCommand {
.volume_access
.or_else(|| current.map(|job| job.volume_access))
.unwrap_or_default(),
stop_service: args
.stop_service
.or_else(|| current.map(|job| job.stop_service))
.unwrap_or_default(),
};
match existing {
Some(index) => jobs[index] = job,
Expand Down
19 changes: 18 additions & 1 deletion apps/piqueld-ui/src/browser/management/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct JobDraft {
secrets: Vec<(String, String)>,
timeout: String,
volume_access: JobVolumeAccess,
stop_service: bool,
}

impl Default for JobDraft {
Expand All @@ -31,6 +32,7 @@ impl Default for JobDraft {
secrets: Vec::new(),
timeout: Job::DEFAULT_TIMEOUT_SECONDS.to_string(),
volume_access: JobVolumeAccess::default(),
stop_service: false,
}
}
}
Expand Down Expand Up @@ -67,6 +69,7 @@ impl JobDraft {
.parse()
.map_err(|_| "Job timeout must be a whole number of seconds".to_owned())?,
volume_access: self.volume_access,
stop_service: self.stop_service,
})
}
}
Expand All @@ -89,6 +92,7 @@ impl From<Job> for JobDraft {
.collect(),
timeout: job.timeout_seconds.to_string(),
volume_access: job.volume_access,
stop_service: job.stop_service,
}
}
}
Expand Down Expand Up @@ -297,7 +301,7 @@ pub(super) fn JobSettings() -> impl IntoView {
<div>
<h3>"Jobs"</h3>
<p>
"Each deployment runs these commands to completion, in order, after preparing images. A job reuses its service's image, environment, secrets, and volume mounts, and waits for that service's startup dependencies to be healthy. Environment variables and secrets added here reach only the job's container, never the service's replicas, and can't replace ones the service sets. Dependencies start or update first; other services roll out only after all jobs succeed. A failed job stops the deployment and dependencies return to the running deployment. Volumes are read-only unless the job has exclusive access, which stops every service using its writable volumes until the rollout. Each command element is one row; no shell parsing is applied."
"Each deployment runs these commands to completion, in order, after preparing images. A job reuses its service's image, environment, secrets, and volume mounts, and waits for that service's startup dependencies to be healthy. Environment variables and secrets added here reach only the job's container, never the service's replicas, and can't replace ones the service sets. Dependencies start or update first; other services roll out only after all jobs succeed. A failed job stops the deployment and dependencies return to the running deployment. Volumes are read-only unless the job has exclusive access, which stops every service using its writable volumes until the rollout. A job can also stop its own service, so its previous version never runs against what the job changes. Each command element is one row; no shell parsing is applied."
</p>
</div>
</header>
Expand Down Expand Up @@ -374,6 +378,19 @@ pub(super) fn JobSettings() -> impl IntoView {
.as_str()}>"Exclusive"</option>
</select>
</label>
<label class="checkbox">
<input
type="checkbox"
prop:checked={move || jobs.field(index, |j| j.stop_service)}
on:change={move |event| {
jobs.edit(
index,
|j| j.stop_service = event_target_checked(&event),
);
}}
/>
<span>"Stop service first"</span>
</label>
<div class="btn-group">
<button
type="button"
Expand Down
2 changes: 1 addition & 1 deletion apps/piqueld/src/docker/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,7 @@ impl DockerApi for FakeDocker {
Ok(())
}

async fn wait_volumes_released(
async fn wait_services_stopped(
&self,
_job: &piqueld_core::DesiredJobRun,
) -> Result<(), DockerError> {
Expand Down
76 changes: 50 additions & 26 deletions apps/piqueld/src/docker/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use bollard::{
use piqueld_core::{
DesiredJobRun,
api::LogStream,
resource::{APPLICATION_LABEL, JOB_LABEL, JOB_OPERATION_LABEL},
resource::{APPLICATION_LABEL, JOB_LABEL, JOB_OPERATION_LABEL, SERVICE_LABEL},
};
use std::time::{SystemTime, UNIX_EPOCH};

Expand All @@ -27,6 +27,8 @@ const JOB_OUTPUT_MAX_BYTES: usize = 1024 * 1024;
const JOB_STOP_POLL_INTERVAL: Duration = Duration::from_millis(250);
/// Label carrying when a run's timeout expires, in Unix milliseconds.
const JOB_DEADLINE_LABEL: &str = "io.piqueld.job-deadline";
/// Label Swarm sets on each task's container, naming its service.
const SWARM_SERVICE_LABEL: &str = "com.docker.swarm.service.name";

impl BollardDocker {
/// Converts a service specification into a single-completion job without
Expand Down Expand Up @@ -88,12 +90,12 @@ impl BollardDocker {

/// Replaces any existing service of the job with this operation's run,
/// labelled with when its timeout expires. Fails while a run of the job
/// is still live, or, for an exclusive run, while another service mounts
/// its volumes or their tasks and containers have not stopped; callers
/// wait for those with `DockerApi::wait_volumes_released` first. The
/// controller's mutation lock covers this and every service write, so
/// with [`Self::check_volumes_free`] a service never shares a volume with
/// an exclusive run.
/// is still live, or while a service the run stops exists or its tasks
/// and containers have not stopped; callers wait for those with
/// `DockerApi::wait_services_stopped` first. The controller's mutation
/// lock covers this and every service write, so with
/// [`Self::check_volumes_free`] a service never shares a volume with an
/// exclusive run.
pub(super) async fn create_job(&self, job: &DesiredJobRun) -> Result<(), DockerError> {
if !job.has_valid_identity() {
return Err(DockerError::OwnershipConflict);
Expand All @@ -110,10 +112,10 @@ impl BollardDocker {
"start a job while an earlier run is stopping",
));
}
self.check_volumes_unused(job).await?;
if !self.volumes_released(job).await? {
self.check_services_removed(job).await?;
if !self.services_stopped(job).await? {
return Err(DockerError::Request(
"start an exclusive job while its volume is in use",
"start a job while a service it stops is still running",
));
}
let node_id = self.local_node_id().await?;
Expand All @@ -129,22 +131,26 @@ impl BollardDocker {
self.create_service_wire(&spec).await
}

/// Fails while a service of the application, other than a job, mounts a
/// volume `job` holds exclusively: waiting cannot remove it.
async fn check_volumes_unused(&self, job: &DesiredJobRun) -> Result<(), DockerError> {
if job.exclusive_volumes().next().is_none() {
/// Fails while a service of the application, other than a job, that
/// `job` stops exists: waiting cannot remove it.
async fn check_services_removed(&self, job: &DesiredJobRun) -> Result<(), DockerError> {
if !job.stops_services() {
return Ok(());
}
let services = self
.labelled_services(Self::ownership_filter(&job.container.labels)?)
.await?;
if services.iter().any(|service| {
let labels = service.spec.as_ref().and_then(|spec| spec.labels.as_ref());
let name = service.spec.as_ref().and_then(|spec| spec.name.as_deref());
!labels.is_some_and(|labels| labels.contains_key(JOB_LABEL))
&& Self::spec_mounts(service).any(|(volume, _)| job.holds_volume(volume))
&& job.stops(
name.unwrap_or_default(),
Self::spec_mounts(service).map(|(volume, _)| volume),
)
}) {
return Err(DockerError::Request(
"start an exclusive job while a service mounts its volume",
"start a job while a service it stops exists",
));
}
Ok(())
Expand Down Expand Up @@ -302,20 +308,38 @@ impl BollardDocker {
.into())
}

/// Whether no task of the application's services that has not stopped,
/// and no running container, mounts a volume `job` holds exclusively.
/// Swarm stops the tasks of removed services asynchronously. Only the
/// application's services mount its volumes, so only their tasks are
/// listed.
pub(super) async fn volumes_released(&self, job: &DesiredJobRun) -> Result<bool, DockerError> {
/// Whether every service `job` stops has stopped: no task of the
/// application's services that has not stopped, and no running
/// container, belongs to its stopped service or mounts a volume it holds
/// exclusively. Swarm stops the tasks of removed services asynchronously.
/// Only the application's services mount its volumes, so only their
/// tasks are listed.
pub(super) async fn services_stopped(&self, job: &DesiredJobRun) -> Result<bool, DockerError> {
if !job.stops_services() {
return Ok(true);
}
let ownership = Self::ownership_filter(&job.container.labels)?;
// Tasks before containers: see `live_tasks`.
if job.stop_service {
let mut labels = ownership.clone();
labels.push(format!("{SERVICE_LABEL}={}", job.container.logical_name));
let service = job
.stopped_service()
.ok_or(DockerError::Validation("job ownership"))?;
if !self.live_tasks(&labels).await?.is_empty()
|| !self
.labelled_containers(vec![format!("{SWARM_SERVICE_LABEL}={service}")])
.await?
.is_empty()
{
return Ok(false);
}
}
let volumes = job.exclusive_volumes().collect::<Vec<_>>();
if volumes.is_empty() {
return Ok(true);
}
// Tasks before containers: see `live_tasks`.
let tasks = self
.live_tasks(&Self::ownership_filter(&job.container.labels)?)
.await?;
let tasks = self.live_tasks(&ownership).await?;
for volume in volumes {
let options = ListContainersOptionsBuilder::default()
.filters(&HashMap::from([("volume", vec![volume.to_string()])]))
Expand Down
4 changes: 2 additions & 2 deletions apps/piqueld/src/docker/limited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,11 @@ impl<D: DockerApi> DockerApi for LimitedDocker<D> {
) -> Result<(), DockerError> {
self.inner.wait_jobs_stopped(ownership, runs).await
}
async fn wait_volumes_released(
async fn wait_services_stopped(
&self,
job: &piqueld_core::DesiredJobRun,
) -> Result<(), DockerError> {
self.inner.wait_volumes_released(job).await
self.inner.wait_services_stopped(job).await
}
async fn remove_network(
&self,
Expand Down
17 changes: 9 additions & 8 deletions apps/piqueld/src/docker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,10 @@ pub trait DockerApi: Send + Sync + 'static {
) -> Result<(), DockerError>;
/// Starts the run of `job`. Any existing service of the same job, including
/// a finished run of the same operation, is removed first. Fails, without
/// waiting, while a run of the job or a task or container using a volume
/// it holds exclusively is still live, so two runs never overlap and an
/// exclusive run never shares its volume; callers wait for that first
/// with [`Self::wait_volumes_released`].
/// waiting, while a run of the job, or a task or container of a service
/// it stops, is still live, so two runs never overlap and a run never
/// overlaps a service it stops; callers wait for that first with
/// [`Self::wait_services_stopped`].
async fn start_job(&self, job: &piqueld_core::DesiredJobRun) -> Result<(), DockerError>;
/// Reads the progress of the run of `job` by its operation.
async fn job_status(&self, job: &piqueld_core::DesiredJobRun)
Expand Down Expand Up @@ -406,10 +406,11 @@ pub trait DockerApi: Send + Sync + 'static {
runs: JobRuns<'_>,
) -> Result<(), DockerError>;
/// Waits until no task of the application's services that has not
/// stopped, and no running container, mounts a volume `job` holds
/// exclusively. Like [`Self::wait_jobs_stopped`], it changes nothing and
/// the caller bounds it.
async fn wait_volumes_released(
/// stopped, and no running container, belongs to the service `job` stops
/// or mounts a volume it holds exclusively. Like
/// [`Self::wait_jobs_stopped`], it changes nothing and the caller bounds
/// it.
async fn wait_services_stopped(
&self,
job: &piqueld_core::DesiredJobRun,
) -> Result<(), DockerError>;
Expand Down
4 changes: 2 additions & 2 deletions apps/piqueld/src/docker/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -996,11 +996,11 @@ impl DockerApi for BollardDocker {
) -> Result<(), DockerError> {
Self::poll_until(|| self.jobs_stopped(ownership, None, runs)).await
}
async fn wait_volumes_released(
async fn wait_services_stopped(
&self,
job: &piqueld_core::DesiredJobRun,
) -> Result<(), DockerError> {
Self::poll_until(|| self.volumes_released(job)).await
Self::poll_until(|| self.services_stopped(job)).await
}
/// Removes the private network by its inspected ID after rechecking
/// ownership, role, and canonical name. A missing network counts as removed.
Expand Down
24 changes: 12 additions & 12 deletions apps/piqueld/src/reconcile/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,8 +544,8 @@ impl<D: DockerApi> Controller<D> {
/// ends the deployment once no job container can still be running, and
/// so does a failure whose own plan a conflict blocks: only an operator
/// resolves that, and reconsidering the deployment then rolls its
/// prerequisites out again. Unless an exclusive job of it succeeded: the
/// services it stopped would run against data in the new format, so they
/// prerequisites out again. Unless a job of it that stops services
/// succeeded: they would run against data in the new format, so they
/// stay stopped until the deployment continues. Other failures are
/// retried, or reconsidered as soon as their plan is unblocked, so
/// restoring the active target meanwhile would only churn their
Expand All @@ -564,7 +564,7 @@ impl<D: DockerApi> Controller<D> {
|| Self::job_failed(operation)
|| (operation.state == OperationState::Failed
&& self.conflict_blocks(&prepared, observed).await?
&& !self.migrated_exclusively(operation, &prepared).await?);
&& !self.migrated_while_stopped(operation, &prepared).await?);
let stopping = ended
&& !self
.store
Expand All @@ -574,18 +574,18 @@ impl<D: DockerApi> Controller<D> {
Ok((!ended || stopping).then_some(prepared))
}

/// Whether an exclusive job of `operation`, which prepared `target`,
/// succeeded, so the volumes it held are in their new format.
async fn migrated_exclusively(
/// Whether a job of `operation`, which prepared `target`, that stops
/// services succeeded, so what they use is in its new format.
async fn migrated_while_stopped(
&self,
operation: &Operation,
target: &piqueld_core::ResolvedApplication,
) -> Result<bool, StoreError> {
let succeeded = self.store.succeeded_jobs(&operation.id).await?;
Ok(target.jobs.iter().any(|job| {
job.exclusive_volumes().next().is_some()
&& succeeded.contains(job.logical_name.as_str())
}))
Ok(target
.jobs
.iter()
.any(|job| job.stops_services() && succeeded.contains(job.logical_name.as_str())))
}

/// Whether a conflict blocks planning `target` against `observed`: one
Expand Down Expand Up @@ -669,8 +669,8 @@ impl<D: DockerApi> Controller<D> {
/// or promoted since, environments stopped or started since, and
/// removals that would drop resources still
/// referenced by routes awaiting cutover. While the deployment may still
/// roll out, prepared job prerequisites and services stopped for an
/// exclusive job are left to it; once it has ended, repair restores them.
/// roll out, prepared job prerequisites and services stopped for a job
/// are left to it; once it has ended, repair restores them.
async fn repair_once(
&self,
id: &EnvironmentId,
Expand Down
12 changes: 6 additions & 6 deletions apps/piqueld/src/reconcile/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl<D: DockerApi> Controller<D> {

/// Uses the full rollout plan to check blockers, but executes only shared
/// infrastructure, this job's startup dependencies, and the removal of
/// services sharing its exclusive volumes. Replanning preserves dependency
/// the services it stops. Replanning preserves dependency
/// ordering without promoting the candidate or touching other services.
/// Each dependency receives its own convergence budget. Returns the run
/// as last planned, joined to the links its environment imports.
Expand Down Expand Up @@ -256,10 +256,10 @@ impl<D: DockerApi> Controller<D> {
let secrets = self
.service_secrets(&job.container.secrets, ownership)
.await?;
// An exclusive run starts once the services it stopped let go of its
// volumes; a newer deployment stops the wait. A run to resume holds
// them itself.
if job.exclusive_volumes().next().is_some() {
// A run that stops services starts once their tasks and containers
// have stopped; a newer deployment stops the wait. A run to resume
// already waited.
if job.stops_services() {
let resumable = AtomicBool::new(false);
self.retry(operation, journal, cancellation, || async {
let status = self.docker.job_status(job).await?;
Expand All @@ -270,7 +270,7 @@ impl<D: DockerApi> Controller<D> {
if !resumable.load(Ordering::Relaxed) {
tokio::select! {
() = cancellation.cancelled() => return Err(OperationError::Cancelled),
released = self.wait_unlocked(self.docker.wait_volumes_released(job)) => {
released = self.wait_unlocked(self.docker.wait_services_stopped(job)) => {
released?;
}
}
Expand Down
1 change: 1 addition & 0 deletions apps/piqueld/tests/api_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3449,6 +3449,7 @@ async fn job_field_edit_replaces_jobs_in_order_and_validates_atomically() {
run: JobRun::BeforeRollout,
timeout_seconds: 60,
volume_access: JobVolumeAccess::ReadOnly,
stop_service: false,
};
let options = |generation| EditOptions {
expected_generation: Some(generation),
Expand Down
Loading
Loading