001/*
002 * (C) Copyright 2015-2019 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.blob;
020
021import java.util.HashSet;
022import java.util.Set;
023
024import org.nuxeo.ecm.core.api.NuxeoException;
025import org.nuxeo.ecm.core.blob.binary.BinaryGarbageCollector;
026import org.nuxeo.ecm.core.blob.binary.BinaryManagerStatus;
027
028/**
029 * Basic implementation for a garbage collector recording marked blobs in memory.
030 */
031public abstract class AbstractBlobGarbageCollector implements BinaryGarbageCollector {
032
033    // volatile as this is designed to be called from another thread
034    protected volatile long startTime;
035
036    protected BinaryManagerStatus status;
037
038    protected Set<String> marked;
039
040    @Override
041    public boolean isInProgress() {
042        return startTime != 0;
043    }
044
045    @Override
046    public void start() {
047        if (startTime != 0) {
048            throw new NuxeoException("Already started");
049        }
050        startTime = System.currentTimeMillis();
051        status = new BinaryManagerStatus();
052        marked = new HashSet<>();
053    }
054
055    @Override
056    public void stop(boolean delete) {
057        if (startTime == 0) {
058            throw new NuxeoException("Not started");
059        }
060        try {
061            removeUnmarkedBlobsAndUpdateStatus(delete);
062        } finally {
063            status.gcDuration = System.currentTimeMillis() - startTime;
064            startTime = 0;
065        }
066    }
067
068    public void removeUnmarkedBlobsAndUpdateStatus(boolean delete) {
069        Set<String> unmarked = getUnmarkedBlobsAndUpdateStatus();
070        marked = null;
071        if (delete) {
072            removeBlobs(unmarked);
073        }
074    }
075
076    public Set<String> getUnmarkedBlobsAndUpdateStatus() {
077        throw new UnsupportedOperationException();
078    }
079
080    public void removeBlobs(Set<String> keys) {
081        throw new UnsupportedOperationException();
082    }
083
084    @Override
085    public void mark(String digest) {
086        marked.add(digest);
087    }
088
089    @Override
090    public BinaryManagerStatus getStatus() {
091        return status;
092    }
093
094}