andresbeckruiz commented on code in PR #359: URL: https://github.com/apache/cassandra-sidecar/pull/359#discussion_r3554875872
########## server/src/main/java/org/apache/cassandra/sidecar/job/DurableOperationalJobTracker.java: ########## @@ -0,0 +1,231 @@ +/* + * 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()); + this.storageProvider = storageProvider; + 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; + }).onSuccess(v -> job.asyncResult().onComplete(ar -> { + updateTerminalStatus(job); + liveJobs.remove(job.jobId()); + })).onFailure(e -> { + liveJobs.remove(jobId, job); + LOGGER.error("Failed to persist job {} to storage. Job will not be tracked durably.", + jobId, e); + }); + } + + 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) Review Comment: This is a good point. However, a caller wouldn't see `CREATED` for an actual running job in the first place: `get()` serves the live job from `liveJobs` first, so an in-progress job reports `RUNNING`, not the storage record. We only fall back to the stored CREATED after the job has truly finished (since `updateTerminalStatus` runs only on completion), or after a restart, when `liveJobs` is empty. Your comment above still holds true if Sidecar restarts-- we could resubmit an operation even if it's running and says "CREATED" in storage. However, this is not a regression, since the current in memory tracker returns `null` from `get()` once the job leaves memory, so it's equally capable of making a client think that the job has not started or does not exist and then resubmit. Given there is no regression, I would probably defer choosing between a) and b) until a PR is made for a reconciliation sweep later on that will actually use it. If this sounds good, I can make a JIRA documenting this follow up. I have also added a Javadoc documenting the limitation and follow up in [b238bd4](https://github.com/apache/cassandra-sidecar/pull/359/commits/b238bd41a68ea650ad30f98d83630ba523f49057) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

