alternative thread-safe vault state without requiring explicit synchronization

This commit is contained in:
Sebastian Stenzel
2021-04-08 11:23:57 +02:00
parent beba6490c3
commit c306d8df04
16 changed files with 150 additions and 154 deletions
@@ -13,9 +13,6 @@ import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
public class DokanyVolume extends AbstractVolume {
@@ -27,7 +27,6 @@ import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
@@ -44,7 +43,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.StampedLock;
import static org.cryptomator.common.Constants.MASTERKEY_FILENAME;
@@ -54,13 +52,11 @@ public class Vault {
private static final Logger LOG = LoggerFactory.getLogger(Vault.class);
private static final Path HOME_DIR = Paths.get(SystemUtils.USER_HOME);
private final StampedLock stateLock;
private final VaultSettings vaultSettings;
private final Provider<Volume> volumeProvider;
private final StringBinding defaultMountFlags;
private final AtomicReference<CryptoFileSystem> cryptoFileSystem;
private final ObjectProperty<VaultState> state;
private final VaultState state;
private final ObjectProperty<Exception> lastKnownException;
private final VaultStats stats;
private final StringBinding displayName;
@@ -78,7 +74,7 @@ public class Vault {
private volatile Volume volume;
@Inject
Vault(VaultSettings vaultSettings, Provider<Volume> volumeProvider, @DefaultMountFlags StringBinding defaultMountFlags, AtomicReference<CryptoFileSystem> cryptoFileSystem, ObjectProperty<VaultState> state, @Named("lastKnownException") ObjectProperty<Exception> lastKnownException, VaultStats stats) {
Vault(VaultSettings vaultSettings, Provider<Volume> volumeProvider, @DefaultMountFlags StringBinding defaultMountFlags, AtomicReference<CryptoFileSystem> cryptoFileSystem, VaultState state, @Named("lastKnownException") ObjectProperty<Exception> lastKnownException, VaultStats stats) {
this.vaultSettings = vaultSettings;
this.volumeProvider = volumeProvider;
this.defaultMountFlags = defaultMountFlags;
@@ -97,8 +93,6 @@ public class Vault {
this.accessPoint = Bindings.createStringBinding(this::getAccessPoint, state);
this.accessPointPresent = this.accessPoint.isNotEmpty();
this.showingStats = new SimpleBooleanProperty(false);
this.stateLock = new StampedLock();
}
// ******************************************************************************
@@ -146,12 +140,9 @@ public class Vault {
try {
volume = volumeProvider.get();
volume.mount(fs, getEffectiveMountFlags(), throwable -> {
LOG.info("Unmounted vault '{}'", getDisplayName());
destroyCryptoFileSystem();
new Thread(() -> { //TODO: maybe use the executor service
long stamp = stateLock.writeLock();
setState(VaultState.LOCKED, stamp);
stateLock.unlock(stamp);
}).start();
state.set(VaultState.Value.LOCKED);
if (throwable != null) {
LOG.warn("Unexpected unmount and lock of vault " + getDisplayName(), throwable);
}
@@ -182,32 +173,12 @@ public class Vault {
// Observable Properties
// *******************************************************************************
public ObjectProperty<VaultState> stateProperty() {
public VaultState stateProperty() {
return state;
}
public VaultState getState() {
return state.get();
}
public long lockVaultState() {
return stateLock.writeLock();
}
public void unlockVaultState(long stamp) {
stateLock.unlock(stamp);
}
public void setState(VaultState value, long stamp) {
if (stateLock.isWriteLockStamp(stamp)) {
if (Platform.isFxApplicationThread()) {
state.setValue(value);
} else {
Platform.runLater(() -> state.setValue(value));
}
} else {
throw new IllegalCallerException("Stamp is not a valid write lock.");
}
public VaultState.Value getState() {
return state.getValue();
}
public ObjectProperty<Exception> lastKnownExceptionProperty() {
@@ -227,7 +198,7 @@ public class Vault {
}
public boolean isLocked() {
return state.get() == VaultState.LOCKED;
return state.get() == VaultState.Value.LOCKED;
}
public BooleanBinding processingProperty() {
@@ -235,7 +206,7 @@ public class Vault {
}
public boolean isProcessing() {
return state.get() == VaultState.PROCESSING;
return state.get() == VaultState.Value.PROCESSING;
}
public BooleanBinding unlockedProperty() {
@@ -243,7 +214,7 @@ public class Vault {
}
public boolean isUnlocked() {
return state.get() == VaultState.UNLOCKED;
return state.get() == VaultState.Value.UNLOCKED;
}
public BooleanBinding missingProperty() {
@@ -251,7 +222,7 @@ public class Vault {
}
public boolean isMissing() {
return state.get() == VaultState.MISSING;
return state.get() == VaultState.Value.MISSING;
}
public BooleanBinding needsMigrationProperty() {
@@ -259,7 +230,7 @@ public class Vault {
}
public boolean isNeedsMigration() {
return state.get() == VaultState.NEEDS_MIGRATION;
return state.get() == VaultState.Value.NEEDS_MIGRATION;
}
public BooleanBinding unknownErrorProperty() {
@@ -267,7 +238,7 @@ public class Vault {
}
public boolean isUnknownError() {
return state.get() == VaultState.ERROR;
return state.get() == VaultState.Value.ERROR;
}
public StringBinding displayNameProperty() {
@@ -283,7 +254,7 @@ public class Vault {
}
public String getAccessPoint() {
if (state.get() == VaultState.UNLOCKED) {
if (state.getValue() == VaultState.Value.UNLOCKED) {
assert volume != null;
return volume.getMountPoint().orElse(Path.of("")).toString();
} else {
@@ -26,7 +26,7 @@ public interface VaultComponent {
Builder vaultSettings(VaultSettings vaultSettings);
@BindsInstance
Builder initialVaultState(VaultState vaultState);
Builder initialVaultState(VaultState.Value vaultState);
@BindsInstance
Builder initialErrorCause(@Nullable @Named("lastKnownException") Exception initialErrorCause);
@@ -93,45 +93,43 @@ public class VaultListManager {
private Vault create(VaultSettings vaultSettings) {
VaultComponent.Builder compBuilder = vaultComponentBuilder.vaultSettings(vaultSettings);
try {
VaultState vaultState = determineVaultState(vaultSettings.path().get());
VaultState.Value vaultState = determineVaultState(vaultSettings.path().get());
compBuilder.initialVaultState(vaultState);
} catch (IOException e) {
LOG.warn("Failed to determine vault state for " + vaultSettings.path().get(), e);
compBuilder.initialVaultState(VaultState.ERROR);
compBuilder.initialVaultState(VaultState.Value.ERROR);
compBuilder.initialErrorCause(e);
}
return compBuilder.build().vault();
}
public static VaultState redetermineVaultState(Vault vault) {
VaultState previousState = vault.getState();
public static VaultState.Value redetermineVaultState(Vault vault) {
VaultState state = vault.stateProperty();
VaultState.Value previousState = state.getValue();
return switch (previousState) {
case LOCKED, NEEDS_MIGRATION, MISSING -> {
long stamp = vault.lockVaultState();
try {
VaultState determinedState = determineVaultState(vault.getPath());
vault.setState(determinedState, stamp);
VaultState.Value determinedState = determineVaultState(vault.getPath());
state.set(determinedState);
yield determinedState;
} catch (IOException e) {
LOG.warn("Failed to determine vault state for " + vault.getPath(), e);
vault.setState(VaultState.ERROR, stamp);
state.set(VaultState.Value.ERROR);
vault.setLastKnownException(e);
yield VaultState.ERROR;
} finally {
vault.unlockVaultState(stamp);
yield VaultState.Value.ERROR;
}
}
case ERROR, UNLOCKED, PROCESSING -> previousState;
};
}
private static VaultState determineVaultState(Path pathToVault) throws IOException {
private static VaultState.Value determineVaultState(Path pathToVault) throws IOException {
if (!CryptoFileSystemProvider.containsVault(pathToVault, MASTERKEY_FILENAME)) {
return VaultState.MISSING;
return VaultState.Value.MISSING;
} else if (Migrators.get().needsMigration(pathToVault, MASTERKEY_FILENAME)) {
return VaultState.NEEDS_MIGRATION;
return VaultState.Value.NEEDS_MIGRATION;
} else {
return VaultState.LOCKED;
return VaultState.Value.LOCKED;
}
}
@@ -40,12 +40,6 @@ public class VaultModule {
return new AtomicReference<>();
}
@Provides
@PerVault
public ObjectProperty<VaultState> provideVaultState(VaultState initialState) {
return new SimpleObjectProperty<>(initialState);
}
@Provides
@Named("lastKnownException")
@PerVault
@@ -1,34 +1,92 @@
package org.cryptomator.common.vaults;
public enum VaultState {
/**
* No vault found at the provided path
*/
MISSING,
import com.google.common.base.Preconditions;
import javax.inject.Inject;
import javafx.application.Platform;
import javafx.beans.value.ObservableObjectValue;
import javafx.beans.value.ObservableValueBase;
import java.util.concurrent.atomic.AtomicReference;
@PerVault
public class VaultState extends ObservableValueBase<VaultState.Value> implements ObservableObjectValue<VaultState.Value> {
public enum Value {
/**
* No vault found at the provided path
*/
MISSING,
/**
* Vault requires migration to a newer vault format
*/
NEEDS_MIGRATION,
/**
* Vault ready to be unlocked
*/
LOCKED,
/**
* Vault in transition between two other states
*/
PROCESSING,
/**
* Vault is unlocked
*/
UNLOCKED,
/**
* Unknown state due to preceeding unrecoverable exceptions.
*/
ERROR;
}
private final AtomicReference<Value> value;
@Inject
public VaultState(VaultState.Value initialValue){
this.value = new AtomicReference<>(initialValue);
}
@Override
public Value get() {
return getValue();
}
@Override
public Value getValue() {
return value.get();
}
/**
* Vault requires migration to a newer vault format
* Transitions from <code>fromState</code> to <code>toState</code>.
* @param fromState Previous state
* @param toState New state
* @return <code>true</code> if successful
*/
NEEDS_MIGRATION,
public boolean transition(Value fromState, Value toState) {
Preconditions.checkArgument(fromState != toState, "fromState must be different than toState");
boolean success = value.compareAndSet(fromState, toState);
if (success) {
fireValueChangedEvent();
}
return success;
}
/**
* Vault ready to be unlocked
*/
LOCKED,
/**
* Vault in transition between two other states
*/
PROCESSING,
/**
* Vault is unlocked
*/
UNLOCKED,
/**
* Unknown state due to preceeding unrecoverable exceptions.
*/
ERROR;
public void set(Value newState) {
var oldState = value.getAndSet(newState);
if (oldState != newState) {
fireValueChangedEvent();
}
}
protected void fireValueChangedEvent() {
if (Platform.isFxApplicationThread()) {
super.fireValueChangedEvent();
} else {
Platform.runLater(super::fireValueChangedEvent);
}
}
}
@@ -26,7 +26,7 @@ public class VaultStats {
private static final Logger LOG = LoggerFactory.getLogger(VaultStats.class);
private final AtomicReference<CryptoFileSystem> fs;
private final ObjectProperty<VaultState> state;
private final VaultState state;
private final ScheduledService<Optional<CryptoFileSystemStats>> updateService;
private final LongProperty bytesPerSecondRead = new SimpleLongProperty();
private final LongProperty bytesPerSecondWritten = new SimpleLongProperty();
@@ -41,7 +41,7 @@ public class VaultStats {
private final LongProperty filesWritten = new SimpleLongProperty();
@Inject
VaultStats(AtomicReference<CryptoFileSystem> fs, ObjectProperty<VaultState> state, ExecutorService executor) {
VaultStats(AtomicReference<CryptoFileSystem> fs, VaultState state, ExecutorService executor) {
this.fs = fs;
this.state = state;
this.updateService = new UpdateStatsService();
@@ -52,7 +52,7 @@ public class VaultStats {
}
private void vaultStateChanged(@SuppressWarnings("unused") Observable observable) {
if (VaultState.UNLOCKED == state.get()) {
if (VaultState.Value.UNLOCKED == state.get()) {
assert fs.get() != null;
LOG.debug("start recording stats");
Platform.runLater(() -> updateService.restart());