Skip to content
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
0.5.0
-----
* Implement durable operational job tracker (CASSSIDECAR-374)
* Remove filesystem path from Http response (CASSSIDECAR-477)
* Add basic configuration retrieval logic to ConfigurationManager (CASSSIDECAR-427)
* RPM package is created with wrong version (CASSSIDECAR-472)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.cassandra.sidecar.job;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
import org.apache.cassandra.sidecar.config.ServiceConfiguration;
import org.apache.cassandra.sidecar.job.storage.OperationalJobRecord;
import org.apache.cassandra.sidecar.job.storage.StorageProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* A durable implementation of {@link OperationalJobTracker} that persists job state
* via a {@link StorageProvider}. A local {@link ConcurrentHashMap} caches live
* {@link OperationalJob} references for the current process, since executing jobs
* with Vert.x promises cannot be reconstituted from storage. Once a job completes,
* it is removed from the local map, and subsequent lookups are served from storage.
*/
@Singleton
public class DurableOperationalJobTracker implements OperationalJobTracker
{
private static final Logger LOGGER = LoggerFactory.getLogger(DurableOperationalJobTracker.class);
private static final int MAX_STATUS_UPDATE_ATTEMPTS = 3;
private static final long RETRY_DELAY_MS = 100;

private final ConcurrentHashMap<UUID, OperationalJob> liveJobs;
private final StorageProvider storageProvider;
private final TaskExecutorPool executor;

@Inject
public DurableOperationalJobTracker(ServiceConfiguration serviceConfiguration,
StorageProvider storageProvider,
TaskExecutorPool executor)
{
this.liveJobs = new ConcurrentHashMap<>(serviceConfiguration.operationalJobTrackerSize());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike InMemoryOperationalJobTracker which has removeEldestEntry, the durable tracker has no eviction. If
asyncResult() never completes (e.g., executeBlocking fails to submit due to full pool), the entry stays in the map forever. Is this expected?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. If executeBlocking fails to submit due to a full pool, the entry will stay in the map forever. As mentioned in the comment below, I will defer a cleanup job for stale entries to a follow up PR, unless you think it should be addressed here.

this.storageProvider = storageProvider;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

who is expected to initialize the storage provider ? can this class assume it's already initialized or do we want to initialize here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The StorageProvider will be initialized externally. DurableOperationalJobTracker assumes it's already initialized and guards against unavailability with the isAvailable() check added in 464f03e.

The idea is that an operator will choose between the durable or in-memory tracker via configuration. I'm deferring these edits to sidecar.yaml to a follow up PR once the config is actually being used by a cluster-wide operation.

this.executor = executor;
}

/**
* {@inheritDoc}
*/
@Override
public OperationalJob computeIfAbsent(UUID jobId, Function<UUID, OperationalJob> mappingFunction)
{
if (!storageProvider.isAvailable())
{
throw new IllegalStateException("Storage provider is not available");
}

boolean[] created = {false};
OperationalJob job = liveJobs.computeIfAbsent(jobId, id -> {
created[0] = true;
return mappingFunction.apply(id);
});

if (created[0])
{
executor.executeBlocking(() -> {
storageProvider.persistJob(OperationalJobRecord.fromOperationalJob(job));
return null;
}).onFailure(e -> {
liveJobs.remove(jobId, job);
LOGGER.error("Failed to persist job {} to storage. Job will not be tracked durably.",
jobId, e);
});

job.asyncResult().onComplete(ar -> {
updateTerminalStatus(job);
liveJobs.remove(job.jobId());
});
}

return job;
}

@Nullable
@Override
public OperationalJobInfo get(UUID jobId)
{
OperationalJob liveJob = liveJobs.get(jobId);
if (liveJob != null)
{
return liveJob;
}

OperationalJobRecord record = storageProvider.findJob(jobId);
if (record == null)
{
return null;
}
return enrichWithNodeStatuses(record);
}

@NotNull
@Override
public Map<UUID, OperationalJob> jobsView()
{
return Collections.unmodifiableMap(liveJobs);
}

@NotNull
@Override
public List<OperationalJob> inflightJobsByOperation(String operation)
{
return liveJobs.values()
.stream()
.filter(j -> j.name().equals(operation) &&
(j.status() == OperationalJobStatus.RUNNING ||
j.status() == OperationalJobStatus.CREATED))
.collect(Collectors.toList());
}

/**
* Enriches an {@link OperationalJobRecord} with per-node status data from storage.
* If the record already has non-empty node lists (e.g. populated by a storage provider
* that joins the data in a single query), the record is returned as is.
*/
private OperationalJobRecord enrichWithNodeStatuses(OperationalJobRecord record)
{
if (!record.nodesPending().isEmpty()
|| !record.nodesExecuting().isEmpty()
|| !record.nodesSucceeded().isEmpty()
|| !record.nodesFailed().isEmpty())
{
return record;
}

Map<UUID, OperationalJobStatus> nodeStatuses =
storageProvider.getNodeStatusesForOperation(record.jobId());
if (nodeStatuses.isEmpty())
{
return record;
}

List<UUID> pending = new ArrayList<>();
List<UUID> executing = new ArrayList<>();
List<UUID> succeeded = new ArrayList<>();
List<UUID> failed = new ArrayList<>();

for (Map.Entry<UUID, OperationalJobStatus> entry : nodeStatuses.entrySet())
{
switch (entry.getValue())
{
case CREATED:
pending.add(entry.getKey());
break;
case RUNNING:
executing.add(entry.getKey());
break;
case SUCCEEDED:
succeeded.add(entry.getKey());
break;
case FAILED:
failed.add(entry.getKey());
break;
default:
break;
}
}

return new OperationalJobRecord(record.jobId(), record.operationType(), record.status(),
record.startTime(), record.lastUpdate(), record.failureReason(),
record.nodeExecutionOrder(), record.operationMetadata(),
Collections.unmodifiableList(pending),
Collections.unmodifiableList(executing),
Collections.unmodifiableList(succeeded),
Collections.unmodifiableList(failed));
}

/**
* Attempts to update the terminal status in storage with retry.
* If all attempts fail, logs a warning and continues.
*/
private void updateTerminalStatus(OperationalJob job)
{
updateTerminalStatus(job, 1);
}

private void updateTerminalStatus(OperationalJob job, int attempt)
{
try
{
storageProvider.updateJobStatus(job.jobId(), job.operationType(), job.status(), job.failureReason());
}
catch (RuntimeException e)
{
LOGGER.warn("Failed to update terminal status for job {} (attempt {}/{}). error={}",
job.jobId(), attempt, MAX_STATUS_UPDATE_ATTEMPTS, e.getMessage());
if (attempt < MAX_STATUS_UPDATE_ATTEMPTS)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • This method is called from above method with attempt=1, if 1st attempt fails, we are doing only one more retry. Should we increase value of MAX_STATUS_UPDATE_ATTEMPTS ?
  • Also, if retries also failed to update, we will have stale entries in CREATED stated. We need a periodic thread running once in a while and removing stale entries (this can be deferred to later as not a blocker).

@andresbeckruiz andresbeckruiz Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Increased MAX_STATUS_UPDATE_ATTEMPTS to 3 in d8a6bf9.

Agreed that there should be a periodic thread to remove stale entries in a later patch.

{
executor.setTimer(RETRY_DELAY_MS * attempt,
id -> updateTerminalStatus(job, attempt + 1));
}
else
{
LOGGER.error("Exhausted retries when updating terminal status for job {}. " +
"Manual intervention may be required to correct job metadata.", job.jobId(), e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.slf4j.LoggerFactory;

import io.vertx.core.Future;
import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -103,6 +104,15 @@ protected Future<Void> executeInternal()
return Future.succeededFuture();
}

/**
* {@inheritDoc}
*/
@Override
public OperationType operationType()
{
return OperationType.DECOMMISSION;
}

/**
* {@inheritDoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.slf4j.LoggerFactory;

import io.vertx.core.Future;
import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.common.server.exceptions.OperationalJobException;
Expand Down Expand Up @@ -136,6 +137,15 @@ protected Future<Void> executeInternal()
return Future.succeededFuture();
}

/**
* {@inheritDoc}
*/
@Override
public OperationType operationType()
{
return OperationType.DRAIN;
}

/**
* {@inheritDoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.slf4j.LoggerFactory;

import io.vertx.core.Future;
import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.common.server.exceptions.OperationalJobException;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -83,6 +84,15 @@ protected Future<Void> executeInternal() throws Exception
return Future.succeededFuture();
}

/**
* {@inheritDoc}
*/
@Override
public OperationType operationType()
{
return OperationType.MOVE;
}

/**
* {@inheritDoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.datastax.driver.core.utils.UUIDs;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.common.server.exceptions.OperationalJobException;
import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
Expand Down Expand Up @@ -239,6 +240,12 @@ public String name()
return simpleName.isEmpty() ? this.getClass().getName() : simpleName;
}

/**
* {@inheritDoc}
*/
@Override
public abstract OperationType operationType();

/**
* Determines the status of the job. OperationalJob subclasses could choose to override the method.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.List;
import java.util.UUID;

import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
Expand All @@ -48,6 +49,11 @@ public interface OperationalJobInfo
*/
String name();

/**
* @return the {@link OperationType} of this job
*/
OperationType operationType();

/**
* @return the current status of the job
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,12 @@ public void trySubmitJob(OperationalJob job,
{
checkConflict(job);

// New job is submitted for all cases when we do not have a corresponding downstream job
jobTracker.computeIfAbsent(job.jobId(), jobId -> {
// Track the job first, then start execution separately
OperationalJob tracked = jobTracker.computeIfAbsent(job.jobId(), jobId -> job);
if (tracked == job)
{
internalExecutorPool.executeBlocking(job::execute);
return job;
});
}
}
catch (OperationalJobConflictException oje)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import io.vertx.core.Future;
import io.vertx.core.Promise;
import org.apache.cassandra.sidecar.adapters.base.RepairOptions;
import org.apache.cassandra.sidecar.common.data.OperationType;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.common.request.data.RepairPayload;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
Expand Down Expand Up @@ -184,6 +185,15 @@ public OperationalJobStatus status()
return currentStatus != null ? currentStatus : super.status();
}

/**
* {@inheritDoc}
*/
@Override
public OperationType operationType()
{
return OperationType.REPAIR;
}

/**
* {@inheritDoc}
*/
Expand Down
Loading