All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sirius.biz.jobs.Jobs Maven / Gradle / Ivy

There is a newer version: 9.6
Show newest version
/*
 * Made with all the love in the world
 * by scireum in Remshalden, Germany
 *
 * Copyright by scireum GmbH
 * http://www.scireum.de - [email protected]
 */

package sirius.biz.jobs;

import com.google.common.collect.Lists;
import sirius.biz.model.TraceData;
import sirius.biz.tenants.UserAccount;
import sirius.db.mixing.OMA;
import sirius.db.mixing.SmartQuery;
import sirius.kernel.async.CallContext;
import sirius.kernel.di.GlobalContext;
import sirius.kernel.di.std.ConfigValue;
import sirius.kernel.di.std.Context;
import sirius.kernel.di.std.Part;
import sirius.kernel.di.std.Parts;
import sirius.kernel.di.std.Register;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.Log;
import sirius.web.security.UserContext;
import sirius.web.tasks.ManagedTaskContext;
import sirius.web.tasks.ManagedTasks;

import javax.annotation.Nullable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * Created by aha on 22.07.16.
 */
@Register(classes = Jobs.class)
public class Jobs {

    public static final Log LOG = Log.get("jobs");

    @Parts(JobsFactory.class)
    private Collection factories;

    @Context
    private GlobalContext ctx;

    @Part
    private ManagedTasks tasks;

    @Part
    private OMA oma;

    @ConfigValue("jobs.max-logs")
    private int maxLogs;

    @ConfigValue("jobs.keep-logs-days")
    private int keepLogInDays;

    public List findJobs(@Nullable String query) {
        List result = Lists.newArrayList();
        for (JobsFactory factory : factories) {
            factory.collectJobs(query, result::add);
        }

        Collections.sort(result,
                         Comparator.comparingInt(JobDescription::getPriority).thenComparing(JobDescription::getTitle));
        return result;
    }

    public JobDescription resolve(String factory, String name) {
        JobsFactory jobsFactory = ctx.findPart(factory, JobsFactory.class);
        return jobsFactory.resolve(name);
    }

    public String execute(JobDescription job, sirius.kernel.commons.Context context) {
        return tasks.createManagedTaskSetup(job.getTaskTitle(context))
                    .withCategory(job.getPreferredExecutor())
                    .execute(mtc -> executeInOwnThread(job, mtc, context))
                    .getId();
    }

    private void executeInOwnThread(JobDescription job, ManagedTaskContext mtc, sirius.kernel.commons.Context context) {
        JobProtocol protocol = new JobProtocol();
        protocol.setJob(job.getName());
        protocol.setFactory(job.getFactory());
        protocol.setUser(UserContext.getCurrentUser().getUserId());
        String userName = Optional.ofNullable(UserContext.getCurrentUser().getUserObject(UserAccount.class))
                                  .map(UserAccount::toString)
                                  .orElse(UserContext.getCurrentUser().getUserName());
        protocol.setUserName(userName);
        protocol.setTenant(UserContext.getCurrentUser().getTenantId());
        protocol.setSuccessful(true);
        protocol.setJobTitle(job.getTaskTitle(context));
        oma.update(protocol);
        try {
            job.execute(context, mtc);
        } catch (Throwable e) {
            mtc.log(Exceptions.handle(LOG, e).getMessage());
            mtc.markErroneous();
        } finally {
            protocol.setDurationInSeconds(CallContext.getCurrent().getWatch().elapsedMillis() / 1000);
            oma.update(protocol);
            deleteOldLogs(job.getFactory(), job.getName());
        }
    }

    private void deleteOldLogs(String factory, String name) {
        try {
            SmartQuery qry = oma.select(JobProtocol.class)
                                             .eq(JobProtocol.FACTORY, factory)
                                             .eq(JobProtocol.JOB, name)
                                             .orderAsc(JobProtocol.TRACE.inner(TraceData.CREATED_AT));
            while (qry.count() > maxLogs) {
                JobProtocol protocolToDelete = qry.queryFirst();
                if (protocolToDelete == null) {
                    return;
                }
                LocalDateTime minAge = LocalDate.now().minusDays(keepLogInDays).atStartOfDay();
                if (protocolToDelete.getTrace().getChangedAt().isAfter(minAge)) {
                    return;
                }
                oma.forceDelete(protocolToDelete);
            }
        } catch (Exception e) {
            Exceptions.handle(LOG, e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy