Search in sources :

Example 6 with ActivateRequestContext

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);
                }
            }
        }
    }
}
Also used : Task(org.bf2.srs.fleetmanager.execution.manager.Task) Instant.now(java.time.Instant.now) SneakyThrows(lombok.SneakyThrows) OperationContext(org.bf2.srs.fleetmanager.operation.OperationContext) LoggerFactory(org.slf4j.LoggerFactory) Job(org.quartz.Job) Duration.ofSeconds(java.time.Duration.ofSeconds) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) WorkerContext(org.bf2.srs.fleetmanager.execution.manager.WorkerContext) DisallowConcurrentExecution(org.quartz.DisallowConcurrentExecution) Duration(java.time.Duration) Objects.requireNonNull(java.util.Objects.requireNonNull) PersistJobDataAfterExecution(org.quartz.PersistJobDataAfterExecution) SerDesObjectMapperProducer(org.bf2.srs.fleetmanager.common.SerDesObjectMapperProducer) Instance(javax.enterprise.inject.Instance) JobExecutionContext(org.quartz.JobExecutionContext) Logger(org.slf4j.Logger) Optional.ofNullable(java.util.Optional.ofNullable) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) QuartzIDs.jobDetailKeyForTask(org.bf2.srs.fleetmanager.execution.manager.impl.QuartzIDs.jobDetailKeyForTask) Instant(java.time.Instant) QuartzIDs.jobDetailKeyForWorker(org.bf2.srs.fleetmanager.execution.manager.impl.QuartzIDs.jobDetailKeyForWorker) ActivateRequestContext(javax.enterprise.context.control.ActivateRequestContext) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Worker(org.bf2.srs.fleetmanager.execution.manager.Worker) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Task(org.bf2.srs.fleetmanager.execution.manager.Task) QuartzIDs.jobDetailKeyForTask(org.bf2.srs.fleetmanager.execution.manager.impl.QuartzIDs.jobDetailKeyForTask) Instant(java.time.Instant) QuartzIDs.jobDetailKeyForWorker(org.bf2.srs.fleetmanager.execution.manager.impl.QuartzIDs.jobDetailKeyForWorker) Worker(org.bf2.srs.fleetmanager.execution.manager.Worker) ActivateRequestContext(javax.enterprise.context.control.ActivateRequestContext) SneakyThrows(lombok.SneakyThrows)

Example 7 with ActivateRequestContext

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);
        }
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ArrayList(java.util.ArrayList) CollectorRegistry(io.prometheus.client.CollectorRegistry) IOException(java.io.IOException) Gauge(io.prometheus.client.Gauge) CompletableFuture(java.util.concurrent.CompletableFuture) AggregationCommand(com.redhat.cloud.notifications.models.AggregationCommand) PushGateway(io.prometheus.client.exporter.PushGateway) ExecutionException(java.util.concurrent.ExecutionException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ActivateRequestContext(javax.enterprise.context.control.ActivateRequestContext)

Example 8 with ActivateRequestContext

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));
}
Also used : PU1Entity(io.quarkus.hibernate.search.elasticsearch.test.multiplepersistenceunits.pu1.PU1Entity) ActivateRequestContext(javax.enterprise.context.control.ActivateRequestContext) QuarkusUnitTest(io.quarkus.test.QuarkusUnitTest) Test(org.junit.jupiter.api.Test)

Example 9 with ActivateRequestContext

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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AccountInfo(org.bf2.srs.fleetmanager.spi.common.model.AccountInfo) AuditingEvent(org.bf2.srs.fleetmanager.operation.auditing.AuditingEvent) ActivateRequestContext(javax.enterprise.context.control.ActivateRequestContext)

Aggregations

ActivateRequestContext (javax.enterprise.context.control.ActivateRequestContext)9 QuarkusUnitTest (io.quarkus.test.QuarkusUnitTest)6 Test (org.junit.jupiter.api.Test)6 RunOptions (io.quarkus.narayana.jta.RunOptions)3 ArrayList (java.util.ArrayList)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 AggregationCommand (com.redhat.cloud.notifications.models.AggregationCommand)1 CollectorRegistry (io.prometheus.client.CollectorRegistry)1 Gauge (io.prometheus.client.Gauge)1 PushGateway (io.prometheus.client.exporter.PushGateway)1 DefaultPUEntity (io.quarkus.hibernate.search.elasticsearch.test.multiplepersistenceunits.defaultpu.DefaultPUEntity)1 PU1Entity (io.quarkus.hibernate.search.elasticsearch.test.multiplepersistenceunits.pu1.PU1Entity)1 PU2Entity (io.quarkus.hibernate.search.elasticsearch.test.multiplepersistenceunits.pu2.PU2Entity)1 IOException (java.io.IOException)1 Duration (java.time.Duration)1 Duration.ofSeconds (java.time.Duration.ofSeconds)1 Instant (java.time.Instant)1 Instant.now (java.time.Instant.now)1 LocalDateTime (java.time.LocalDateTime)1