001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Benoit Delbosc
018 */
019package org.nuxeo.ecm.automation.elasticsearch;
020
021import static java.lang.Long.max;
022
023import java.util.concurrent.ExecutionException;
024import java.util.concurrent.TimeUnit;
025import java.util.concurrent.TimeoutException;
026
027import org.nuxeo.common.utils.ExceptionUtils;
028import org.nuxeo.ecm.automation.core.Constants;
029import org.nuxeo.ecm.automation.core.annotations.Context;
030import org.nuxeo.ecm.automation.core.annotations.Operation;
031import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
032import org.nuxeo.ecm.automation.core.annotations.Param;
033import org.nuxeo.ecm.core.api.CoreSession;
034import org.nuxeo.ecm.core.work.api.WorkManager;
035import org.nuxeo.ecm.platform.audit.api.AuditLogger;
036import org.nuxeo.elasticsearch.ElasticSearchConstants;
037import org.nuxeo.elasticsearch.api.ElasticSearchAdmin;
038import org.nuxeo.runtime.api.Framework;
039
040/**
041 * Wait for Elasticsearch indexing background job
042 *
043 * @since 8.1
044 */
045@Operation(id = ElasticsearchWaitForIndexingOperation.ID, category = Constants.CAT_SERVICES, label = "Wait for Elasticsearch Indexing",
046        since = "8.1",
047        description = "Wait until Elasticsearch indexing is done.")
048public class ElasticsearchWaitForIndexingOperation {
049
050    public static final String ID = "Elasticsearch.WaitForIndexing";
051
052    /**
053     * @since 9.10
054     */
055    public static final String AUDIT_ELASTICSEARCH_ENABLED = "audit.elasticsearch.enabled";
056
057    @Context
058    protected ElasticSearchAdmin esa;
059
060    @Context
061    protected CoreSession repo;
062
063    @Param(name = "timeoutSecond", required = false)
064    protected Integer timeout = 60;
065
066    @Param(name = "refresh", required = false)
067    protected Boolean refresh = false;
068
069    @Param(name = "waitForAudit", required = false)
070    protected Boolean waitForAudit = false;
071
072    @OperationMethod
073    public Boolean run() {
074        long start = System.currentTimeMillis();
075        WorkManager workManager = Framework.getService(WorkManager.class);
076        AuditLogger auditLogger = Framework.getService(AuditLogger.class);
077        boolean waitForAuditStoredInEs = waitForAudit && Framework.isBooleanPropertyTrue(AUDIT_ELASTICSEARCH_ENABLED);
078        try {
079            if (!workManager.awaitCompletion(timeout, TimeUnit.SECONDS)) {
080                throw new TimeoutException();
081            }
082            if (waitForAuditStoredInEs && !auditLogger.await(computeRemainingTime(start), TimeUnit.SECONDS)) {
083                throw new TimeoutException();
084            }
085            esa.prepareWaitForIndexing().get(computeRemainingTime(start), TimeUnit.SECONDS);
086        } catch (InterruptedException e) {
087            Thread.currentThread().interrupt();
088            return Boolean.FALSE;
089        } catch (TimeoutException | ExecutionException e) {
090            if (ExceptionUtils.hasInterruptedCause(e)) {
091                // reset interrupted status
092                Thread.currentThread().interrupt();
093            }
094            return Boolean.FALSE;
095        }
096        if (refresh) {
097            esa.refreshRepositoryIndex(repo.getRepositoryName());
098            if (waitForAuditStoredInEs) {
099                esa.getClient().refresh(esa.getIndexNameForType(ElasticSearchConstants.ENTRY_TYPE));
100            }
101        }
102        return Boolean.TRUE;
103    }
104
105    protected long computeRemainingTime(long start) {
106        long elapsed = System.currentTimeMillis() - start;
107        // at least one second
108        return max(timeout - TimeUnit.MILLISECONDS.toSeconds(elapsed), 1);
109    }
110
111}