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 *     Nuxeo
018 */
019
020package org.nuxeo.ecm.blob;
021
022import java.util.HashSet;
023import java.util.Set;
024
025import org.nuxeo.ecm.core.blob.binary.BinaryGarbageCollector;
026import org.nuxeo.ecm.core.blob.binary.BinaryManagerStatus;
027import org.nuxeo.ecm.core.blob.binary.CachingBinaryManager;
028
029/**
030 * @author <a href="mailto:ak@nuxeo.com">Arnaud Kervern</a>
031 * @since 7.10
032 */
033public abstract class AbstractBinaryGarbageCollector<T extends CachingBinaryManager> implements BinaryGarbageCollector {
034
035    protected T binaryManager;
036
037    protected BinaryManagerStatus status;
038
039    protected volatile long startTime;
040
041    protected Set<String> marked;
042
043    protected AbstractBinaryGarbageCollector(T binaryManager) {
044        this.binaryManager = binaryManager;
045    }
046
047    @Override
048    public void start() {
049        if (startTime != 0) {
050            throw new RuntimeException("Already started");
051        }
052        startTime = System.currentTimeMillis();
053        status = new BinaryManagerStatus();
054        marked = new HashSet<>();
055
056        // XXX : we should be able to do better
057        // and only remove the cache entry that will be removed from S3
058        binaryManager.fileCache.clear();
059    }
060
061    @Override
062    public void stop(boolean delete) {
063        if (startTime == 0) {
064            throw new RuntimeException("Not started");
065        }
066        try {
067            Set<String> unmarked = getUnmarkedBlobs();
068            marked = null;
069
070            if (delete) {
071                binaryManager.removeBinaries(unmarked);
072            }
073        } finally {
074            status.gcDuration = System.currentTimeMillis() - startTime;
075            startTime = 0;
076        }
077    }
078
079    public abstract Set<String> getUnmarkedBlobs();
080
081    @Override
082    public void mark(String digest) {
083        marked.add(digest);
084    }
085
086    @Override
087    public BinaryManagerStatus getStatus() {
088        return status;
089    }
090
091    @Override
092    public boolean isInProgress() {
093        // volatile as this is designed to be called from another thread
094        return startTime != 0;
095    }
096}