Search in sources :

Example 1 with CronRule

use of io.lumeer.api.model.rule.CronRule in project engine by Lumeer.

the class CollectionFacade method runRule.

public void runRule(final Collection collection, final String ruleId) {
    if (adapter.getDocumentsCountByCollection(collection.getId()) > 2_000) {
        throw new UnsuccessfulOperationException("Too many documents in the source collection");
    }
    final Rule rule = collection.getRules().get(ruleId);
    if (rule != null && rule.getType() == Rule.RuleType.AUTO_LINK) {
        final AutoLinkRule autoLinkRule = new AutoLinkRule(rule);
        final String otherCollectionId = autoLinkRule.getCollection2().equals(collection.getId()) ? autoLinkRule.getCollection1() : autoLinkRule.getCollection2();
        final String attributeId = autoLinkRule.getCollection1().equals(collection.getId()) ? autoLinkRule.getAttribute1() : autoLinkRule.getAttribute2();
        final Attribute attribute = collection.getAttributes().stream().filter(a -> a.getId().equals(attributeId)).findFirst().orElse(null);
        final Collection otherCollection = getCollection(otherCollectionId);
        final String otherAttributeId = autoLinkRule.getCollection2().equals(collection.getId()) ? autoLinkRule.getAttribute1() : autoLinkRule.getAttribute2();
        final Attribute otherAttribute = otherCollection.getAttributes().stream().filter(a -> a.getId().equals(otherAttributeId)).findFirst().orElse(null);
        final Map<String, AllowedPermissions> permissions = permissionsChecker.getCollectionsPermissions(List.of(collection, otherCollection));
        if (adapter.getDocumentsCountByCollection(otherCollectionId) > 10_000) {
            throw new UnsuccessfulOperationException("Too many documents in the target collection");
        }
        final LinkType linkType = linkTypeDao.getLinkType(autoLinkRule.getLinkType());
        final AutoLinkBatchTask task = taskFactory.getInstance(AutoLinkBatchTask.class);
        task.setupBatch(autoLinkRule, linkType, collection, attribute, otherCollection, otherAttribute, getCurrentUser(), permissions);
        taskExecutor.submitTask(task);
    } else if (rule != null && rule.getType() == Rule.RuleType.CRON) {
        final CronRule cronRule = new CronRule(rule);
        List<Document> documents = new ArrayList<>();
        if (cronRule.getViewId() != null) {
            try {
                final View view = viewDao.getViewById(cronRule.getViewId());
                final User user = AuthenticatedUser.getMachineUser();
                final AllowedPermissions allowedPermissions = AllowedPermissions.allAllowed();
                documents = DocumentUtils.getDocuments(collectionDao, documentDao, dataDao, userDao, groupDao, selectionListDao, getOrganization(), getProject(), view.getQuery(), user, cronRule.getLanguage(), allowedPermissions, null);
                documents = documents.stream().filter(document -> document.getCollectionId().equals(collection.getId())).collect(Collectors.toList());
            } catch (ResourceNotFoundException ignore) {
            }
        }
        RuleTask task = taskFactory.getInstance(RuleTask.class);
        task.setRule(rule.getName(), rule, collection, documents);
        taskExecutor.submitTask(task);
    }
}
Also used : AutoLinkBatchTask(io.lumeer.core.task.AutoLinkBatchTask) TaskExecutor(io.lumeer.core.task.TaskExecutor) CollectionUtil(io.lumeer.api.util.CollectionUtil) ZonedDateTime(java.time.ZonedDateTime) User(io.lumeer.api.model.User) AuthenticatedUser(io.lumeer.core.auth.AuthenticatedUser) LinkTypeDao(io.lumeer.storage.api.dao.LinkTypeDao) AutoLinkRule(io.lumeer.api.model.rule.AutoLinkRule) CollectionDao(io.lumeer.storage.api.dao.CollectionDao) ResourceType(io.lumeer.api.model.ResourceType) DefaultViewConfigDao(io.lumeer.storage.api.dao.DefaultViewConfigDao) Map(java.util.Map) ResourceCommentDao(io.lumeer.storage.api.dao.ResourceCommentDao) CollectionAdapter(io.lumeer.core.adapter.CollectionAdapter) Permission(io.lumeer.api.model.Permission) RoleType(io.lumeer.api.model.RoleType) View(io.lumeer.api.model.View) ResourceNotFoundException(io.lumeer.storage.api.exception.ResourceNotFoundException) Document(io.lumeer.api.model.Document) Set(java.util.Set) NoResourcePermissionException(io.lumeer.core.exception.NoResourcePermissionException) Collectors(java.util.stream.Collectors) LinkType(io.lumeer.api.model.LinkType) Objects(java.util.Objects) AttributesResource(io.lumeer.api.model.common.AttributesResource) List(java.util.List) ResourceUtils(io.lumeer.api.util.ResourceUtils) PostConstruct(javax.annotation.PostConstruct) FavoriteItemDao(io.lumeer.storage.api.dao.FavoriteItemDao) Attribute(io.lumeer.api.model.Attribute) ContextualTaskFactory(io.lumeer.core.task.ContextualTaskFactory) UserDao(io.lumeer.storage.api.dao.UserDao) HashMap(java.util.HashMap) SelectionListDao(io.lumeer.storage.api.dao.SelectionListDao) AllowedPermissions(io.lumeer.api.model.AllowedPermissions) Function(java.util.function.Function) CollectionPurpose(io.lumeer.api.model.CollectionPurpose) GroupDao(io.lumeer.storage.api.dao.GroupDao) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) DataDao(io.lumeer.storage.api.dao.DataDao) ViewDao(io.lumeer.storage.api.dao.ViewDao) CodeGenerator(io.lumeer.core.util.CodeGenerator) Rule(io.lumeer.api.model.Rule) DocumentDao(io.lumeer.storage.api.dao.DocumentDao) Permissions(io.lumeer.api.model.Permissions) ResourceAdapter(io.lumeer.core.adapter.ResourceAdapter) DocumentUtils(io.lumeer.core.util.DocumentUtils) FileAttachment(io.lumeer.api.model.FileAttachment) Project(io.lumeer.api.model.Project) LinkInstanceDao(io.lumeer.storage.api.dao.LinkInstanceDao) UnsuccessfulOperationException(io.lumeer.engine.api.exception.UnsuccessfulOperationException) ConversionFacade(io.lumeer.core.facade.conversion.ConversionFacade) RuleTask(io.lumeer.core.task.RuleTask) RequestScoped(javax.enterprise.context.RequestScoped) CronRule(io.lumeer.api.model.rule.CronRule) AutoLinkBatchTask(io.lumeer.core.task.AutoLinkBatchTask) Collection(io.lumeer.api.model.Collection) User(io.lumeer.api.model.User) AuthenticatedUser(io.lumeer.core.auth.AuthenticatedUser) Attribute(io.lumeer.api.model.Attribute) View(io.lumeer.api.model.View) AllowedPermissions(io.lumeer.api.model.AllowedPermissions) UnsuccessfulOperationException(io.lumeer.engine.api.exception.UnsuccessfulOperationException) Collection(io.lumeer.api.model.Collection) List(java.util.List) ArrayList(java.util.ArrayList) RuleTask(io.lumeer.core.task.RuleTask) AutoLinkRule(io.lumeer.api.model.rule.AutoLinkRule) Rule(io.lumeer.api.model.Rule) CronRule(io.lumeer.api.model.rule.CronRule) LinkType(io.lumeer.api.model.LinkType) ResourceNotFoundException(io.lumeer.storage.api.exception.ResourceNotFoundException) AutoLinkRule(io.lumeer.api.model.rule.AutoLinkRule) CronRule(io.lumeer.api.model.rule.CronRule)

Example 2 with CronRule

use of io.lumeer.api.model.rule.CronRule in project engine by Lumeer.

the class CronTaskProcessor method processRules.

private void processRules(final DaoContextSnapshot dao, final Collection collection) {
    var rules = collection.getRules().entrySet().stream().filter(e -> e.getValue().getType() == Rule.RuleType.CRON).collect(Collectors.toList());
    if (rules.size() > 0) {
        final ContextualTaskFactory taskFactory = getTaskFactory(dao);
        final String signature = UUID.randomUUID().toString();
        final ZonedDateTime now = ZonedDateTime.now();
        final Map<String, CronRule> rulesToExecute = new HashMap<>();
        rules.forEach(entry -> {
            final CronRule rule = new CronRule(entry.getValue());
            if (checker.shouldExecute(rule, ZonedDateTime.now())) {
                // this is a sign of an error in previous execution, let's revert normal state and let it pass to another round
                if (rule.getExecuting() != null && !"".equals(rule.getExecuting())) {
                    log.info(String.format("Fixing rule execution signature on %s/%s, %s, '%s'.", dao.getOrganization().getCode(), dao.getProject().getCode(), collection.getName(), rule.getRule().getName()));
                    rule.setExecuting(null);
                } else {
                    log.info(String.format("Planning to run rule on %s/%s, %s, '%s'.", dao.getOrganization().getCode(), dao.getProject().getCode(), collection.getName(), rule.getRule().getName()));
                    rule.setLastRun(now);
                    rule.setExecuting(signature);
                    if (rule.getExecutionsLeft() != null) {
                        rule.setExecutionsLeft(Math.max(rule.getExecutionsLeft() - 1, 0));
                    }
                    rulesToExecute.put(entry.getKey(), rule);
                }
            }
        });
        // bookedCollection is the previous version of collection before updating the rules!!!
        final Collection bookedCollection = dao.getCollectionDao().updateCollectionRules(collection);
        rulesToExecute.forEach((key, rule) -> {
            log.info(String.format("Running cron rule on %s/%s, %s, '%s'.", dao.getOrganization().getCode(), dao.getProject().getCode(), collection.getName(), rule.getRule().getName()));
            // is it us who tried last?
            final String executing = new CronRule(bookedCollection.getRules().get(key)).getExecuting();
            if (executing == null || "".equals(executing)) {
                final List<Document> documents = getDocuments(rule, collection, dao);
                taskExecutor.submitTask(getTask(taskFactory, rule.getRule().getName() != null ? rule.getRule().getName() : key, rule.getRule(), collection, documents));
            }
        });
        // Make sure we have the rules with updated lastRun and simply clean the signatures no matter what (lastRun is updated anyway)
        final Collection latestCollection = dao.getCollectionDao().getCollectionById(collection.getId());
        rulesToExecute.keySet().forEach(key -> new CronRule(latestCollection.getRules().get(key)).setExecuting(null));
        dao.getCollectionDao().updateCollectionRules(latestCollection);
    }
}
Also used : WorkspaceContext(io.lumeer.core.WorkspaceContext) DaoContextSnapshot(io.lumeer.storage.api.dao.context.DaoContextSnapshot) CronTaskChecker(io.lumeer.core.util.CronTaskChecker) ResourceNotFoundException(io.lumeer.storage.api.exception.ResourceNotFoundException) ZonedDateTime(java.time.ZonedDateTime) AuthenticatedUser(io.lumeer.core.auth.AuthenticatedUser) HashMap(java.util.HashMap) UUID(java.util.UUID) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Level(java.util.logging.Level) io.lumeer.api.model(io.lumeer.api.model) DocumentUtils(io.lumeer.core.util.DocumentUtils) Inject(javax.inject.Inject) OrganizationDao(io.lumeer.storage.api.dao.OrganizationDao) List(java.util.List) Singleton(javax.ejb.Singleton) Map(java.util.Map) Schedule(javax.ejb.Schedule) DataStorage(io.lumeer.engine.api.data.DataStorage) Startup(javax.ejb.Startup) CronRule(io.lumeer.api.model.rule.CronRule) ZonedDateTime(java.time.ZonedDateTime) HashMap(java.util.HashMap) CronRule(io.lumeer.api.model.rule.CronRule)

Example 3 with CronRule

use of io.lumeer.api.model.rule.CronRule in project engine by Lumeer.

the class CronTaskProcessor method getDocuments.

private List<Document> getDocuments(final CronRule rule, final Collection collection, final DaoContextSnapshot dao) {
    if (dao.getSelectedWorkspace().getOrganization().isPresent() && rule.getViewId() != null) {
        try {
            final View view = dao.getViewDao().getViewById(rule.getViewId());
            final User user = AuthenticatedUser.getMachineUser();
            final AllowedPermissions allowedPermissions = AllowedPermissions.allAllowed();
            final List<Document> documents = DocumentUtils.getDocuments(dao, view.getQuery(), user, rule.getLanguage(), allowedPermissions, null);
            return documents.stream().filter(document -> document.getCollectionId().equals(collection.getId())).collect(Collectors.toList());
        } catch (ResourceNotFoundException e) {
            return List.of();
        }
    }
    return List.of();
}
Also used : WorkspaceContext(io.lumeer.core.WorkspaceContext) DaoContextSnapshot(io.lumeer.storage.api.dao.context.DaoContextSnapshot) CronTaskChecker(io.lumeer.core.util.CronTaskChecker) ResourceNotFoundException(io.lumeer.storage.api.exception.ResourceNotFoundException) ZonedDateTime(java.time.ZonedDateTime) AuthenticatedUser(io.lumeer.core.auth.AuthenticatedUser) HashMap(java.util.HashMap) UUID(java.util.UUID) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Level(java.util.logging.Level) io.lumeer.api.model(io.lumeer.api.model) DocumentUtils(io.lumeer.core.util.DocumentUtils) Inject(javax.inject.Inject) OrganizationDao(io.lumeer.storage.api.dao.OrganizationDao) List(java.util.List) Singleton(javax.ejb.Singleton) Map(java.util.Map) Schedule(javax.ejb.Schedule) DataStorage(io.lumeer.engine.api.data.DataStorage) Startup(javax.ejb.Startup) CronRule(io.lumeer.api.model.rule.CronRule) AuthenticatedUser(io.lumeer.core.auth.AuthenticatedUser) ResourceNotFoundException(io.lumeer.storage.api.exception.ResourceNotFoundException)

Aggregations

CronRule (io.lumeer.api.model.rule.CronRule)3 AuthenticatedUser (io.lumeer.core.auth.AuthenticatedUser)3 DocumentUtils (io.lumeer.core.util.DocumentUtils)3 ResourceNotFoundException (io.lumeer.storage.api.exception.ResourceNotFoundException)3 ZonedDateTime (java.time.ZonedDateTime)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 Inject (javax.inject.Inject)3 io.lumeer.api.model (io.lumeer.api.model)2 WorkspaceContext (io.lumeer.core.WorkspaceContext)2 AllowedPermissions (io.lumeer.api.model.AllowedPermissions)1 Attribute (io.lumeer.api.model.Attribute)1 Collection (io.lumeer.api.model.Collection)1 CollectionPurpose (io.lumeer.api.model.CollectionPurpose)1 Document (io.lumeer.api.model.Document)1 FileAttachment (io.lumeer.api.model.FileAttachment)1 LinkType (io.lumeer.api.model.LinkType)1 Permission (io.lumeer.api.model.Permission)1