001/*
002 * (C) Copyright 2017-2018 Nuxeo (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 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.versioning;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.core.CoreService;
024import org.nuxeo.ecm.core.event.EventBundle;
025import org.nuxeo.ecm.core.event.PostCommitEventListener;
026import org.nuxeo.runtime.api.Framework;
027import org.nuxeo.runtime.services.config.ConfigurationService;
028
029/**
030 * Asynchronous listener that calls the orphan versions cleanup service. Designed to be called periodically by a
031 * scheduler.
032 *
033 * @since 9.1
034 */
035public class OrphanVersionCleanupListener implements PostCommitEventListener {
036
037    private static final Log log = LogFactory.getLog(OrphanVersionCleanupListener.class);
038
039    public static final long DEFAULT_COMMIT_SIZE = 1000;
040
041    /**
042     * Configuration property for the maximum number of orphan versions to delete in one transaction. Default is
043     * {@value #DEFAULT_COMMIT_SIZE}.
044     */
045    public static final String DEFAULT_COMMIT_SIZE_PROP = "org.nuxeo.orphanVersionsCleanup.commitSize";
046
047    /**
048     * Gets the maximum number of orphan versions to delete in one transaction.
049     */
050    protected long getCommitSize() {
051        ConfigurationService configurationService = Framework.getService(ConfigurationService.class);
052        return configurationService.getLong(DEFAULT_COMMIT_SIZE_PROP, DEFAULT_COMMIT_SIZE);
053    }
054
055    @Override
056    public void handleEvent(EventBundle events) {
057        CoreService coreService = Framework.getService(CoreService.class);
058        if (coreService == null) {
059            // CoreService failed to start, no need to go further
060            return;
061        }
062        log.debug("Starting orphan versions cleanup");
063        long n = coreService.cleanupOrphanVersions(getCommitSize());
064        log.debug("Number of orphan versions deleted: " + n);
065    }
066
067}