use of javax.enterprise.context.control.ActivateRequestContext in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.
the class JobWrapper method execute.
@Override
@SneakyThrows
@ActivateRequestContext
public void execute(JobExecutionContext quartzJobContext) {
Task task = loadTask(quartzJobContext);
List<Worker> selectedWorkers = workers.stream().filter(w -> w.supports(task) && !workerExclusions.contains(w.getClass())).collect(toList());
for (Worker worker : selectedWorkers) {
WorkerContextImpl wCtx = loadWorkerContext(quartzJobContext, worker, task);
Instant next = null;
Exception lastException = null;
try {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Executing task.", task, worker, wCtx);
worker.execute(task, wCtx);
wCtx.getDelayedActions().forEach(Runnable::run);
// OK vvv
// Reset retry counter
wCtx.setRetryAttempts(0);
// Reset min retry counter
wCtx.setMinRetries(task.getSchedule().getMinRetries());
// Normal rescheduling
next = nextExecution(task);
} catch (Exception anEx) {
// TODO Throwable?
lastException = anEx;
if (anEx instanceof RetryExecutionControlException) {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Task requested a retry.", task, worker, wCtx, anEx);
RetryExecutionControlException ex = (RetryExecutionControlException) anEx;
if (ex.isForce() && wCtx.getMinRetries() < Integer.MAX_VALUE) {
// Make space for forced retry, no more than Integer.MAX_VALUE
wCtx.setMinRetries(wCtx.getMinRetries() + 1);
next = Instant.now().plus(Duration.ofSeconds(1));
}
if (ex.getMinRetries() > wCtx.getMinRetries()) {
wCtx.setMinRetries(ex.getMinRetries());
}
lastException = null;
}
if (wCtx.getRetryAttempts() < wCtx.getMinRetries() && (next == null)) {
// Reschedule if the minRetries is not reached
next = Instant.now().plus(backoff(wCtx.getRetryAttempts()));
}
if (anEx instanceof StopExecutionControlException) {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Task requested a stop.", task, worker, wCtx, anEx);
// Unschedule
next = null;
lastException = null;
}
if (lastException != null) {
log.warn("Task Manager (task = {}, worker = {}, workerContext = {}, nextExecution = {}): Task threw an exception during execution: {}", task, worker, wCtx, next, anEx);
}
wCtx.setRetryAttempts(wCtx.getRetryAttempts() + 1);
} finally {
// Unlikely used
wCtx.setDelayedActions(new ArrayList<>(0));
saveWorkerContext(quartzJobContext, wCtx, worker);
saveTask(quartzJobContext, task);
// Scheduling
if (next != null) {
if (wCtx.getRetryAttempts() == wCtx.getMinRetries()) {
log.info("Task Manager (task = {}, worker = {}, workerContext = {}): Last rescheduling at {}.", task, worker, wCtx, next);
} else {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Rescheduling task at {}.", task, worker, wCtx, next);
}
taskManager.rerigger(task, next);
} else {
try {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Executing finallyExecute. Last exception = {}", task, worker, wCtx, lastException);
worker.finallyExecute(task, wCtx, ofNullable(lastException));
wCtx.getDelayedActions().forEach(Runnable::run);
} catch (Exception ex) {
log.warn("Task Manager (task = {}, worker = {}, workerContext = {}): Ignoring an exception thrown in finallyExecute: {}", task, worker, wCtx, ex);
} finally {
log.debug("Task Manager (task = {}, worker = {}, workerContext = {}): Removing task.", task, worker, wCtx);
taskManager.remove(task);
}
}
}
}
}
use of javax.enterprise.context.control.ActivateRequestContext in project notifications-backend by RedHatInsights.
the class DailyEmailAggregationJob method processDailyEmail.
@ActivateRequestContext
public void processDailyEmail() {
CollectorRegistry registry = new CollectorRegistry();
Gauge duration = Gauge.build().name("aggregator_job_duration_seconds").help("Duration of the aggregator job in seconds.").register(registry);
Gauge.Timer durationTimer = duration.startTimer();
try {
LocalDateTime now = LocalDateTime.now(UTC);
List<AggregationCommand> aggregationCommands = processAggregateEmails(now, registry);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (AggregationCommand aggregationCommand : aggregationCommands) {
try {
final String payload = objectMapper.writeValueAsString(aggregationCommand);
futures.add(emitter.send(payload).toCompletableFuture());
} catch (JsonProcessingException e) {
LOG.warn("Could not transform AggregationCommand to JSON object.", e);
}
// resolve completable futures so the Quarkus main thread doesn't stop before everything has been sent
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
} catch (InterruptedException | ExecutionException ie) {
LOG.error("Writing AggregationCommands failed", ie);
}
}
emailAggregationResources.updateLastCronJobRun(now);
Gauge lastSuccess = Gauge.build().name("aggregator_job_last_success").help("Last time the aggregator job succeeded.").register(registry);
lastSuccess.setToCurrentTime();
} finally {
durationTimer.setDuration();
PushGateway pg = new PushGateway(prometheusPushGatewayUrl);
try {
pg.pushAdd(registry, "aggregator_job");
} catch (IOException e) {
LOG.warn("Could not push metrics to Prometheus Pushgateway.", e);
}
}
}
use of javax.enterprise.context.control.ActivateRequestContext in project quarkus by quarkusio.
the class MultiplePersistenceUnitsCdiTest method testPU1Session.
@Test
@ActivateRequestContext
public void testPU1Session() {
PU1Entity entity = new PU1Entity("someText");
inTransaction(() -> pu1Session.toEntityManager().persist(entity));
inTransaction(() -> assertThat(pu1Session.search(PU1Entity.class).where(f -> f.matchAll()).fetchHits(20)).hasSize(1).element(0).returns(entity.getId(), PU1Entity::getId));
}
use of javax.enterprise.context.control.ActivateRequestContext in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.
the class AuditingServletFilter method doFilter.
@Override
@ActivateRequestContext
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Activate Operation Context
if (opCtx.isContextDataLoaded()) {
throw new IllegalStateException("Unexpected state: Operation Context is already loaded");
}
opCtx.loadNewContextData();
var req = (HttpServletRequest) request;
var res = (HttpServletResponse) response;
// TODO Unify logic to extract this using parameter extractors
auditing.addTraceMetadata(KEY_REQUEST_SOURCE_IP, req.getRemoteAddr());
auditing.addTraceMetadata(KEY_REQUEST_FORWARDED_FOR, req.getHeader(HEADER_X_FORWARDED_FOR));
auditing.addTraceMetadata(KEY_REQUEST_METHOD, req.getMethod());
auditing.addTraceMetadata(KEY_REQUEST_PATH, req.getRequestURI());
AccountInfo accountInfo = authService.extractAccountInfo();
auditing.addTraceMetadata(KEY_USER_ACCOUNT_ID, accountInfo.getAccountId());
auditing.addTraceMetadata(KEY_USER_ACCOUNT_NAME, accountInfo.getAccountUsername());
auditing.addTraceMetadata(KEY_USER_ORG_ID, accountInfo.getOrganizationId());
auditing.addTraceMetadata(KEY_USER_IS_ORG_ADMIN, accountInfo.isAdmin());
chain.doFilter(request, response);
if (res.getStatus() >= 400) {
var event = new AuditingEvent();
event.setEventId("request_failure");
event.addData(KEY_RESPONSE_CODE, res.getStatus());
event.setSuccessful(false);
auditing.recordEvent(event);
}
}
Aggregations