aboutsummaryrefslogtreecommitdiffstats
path: root/zkfacade/src/main/java/com/yahoo/vespa/curator/Lock.java
blob: a5d2397dadb8b4c114ca0e55389104f389b33f0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.curator;

import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.path.Path;
import com.yahoo.transaction.Mutex;
import com.yahoo.vespa.curator.stats.LockStats;
import com.yahoo.vespa.curator.stats.ThreadLockStats;
import org.apache.curator.framework.recipes.locks.InterProcessLock;

import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * A cluster-wide re-entrant mutex which is released on (the last symmetric) close.
 *
 * Re-entrancy is limited to the instance of this. To ensure re-entrancy callers should access the lock through
 * {@link Curator#lock(Path, Duration)} instead of constructing this directly.
 *
 * @author bratseth
 */
public class Lock implements Mutex {

    // TODO(hakon): Remove once debugging is done
    private final Object monitor = new Object();
    private long nextSequenceNumber = 0;
    private final Map<Long, Long> reentriesByThreadId = new HashMap<>();
    private final Instant created = Instant.now();
    private Curator curator;

    private final InterProcessLock mutex;
    private final String lockPath;

    public Lock(String lockPath, Curator curator) {
        this(lockPath, curator.createMutex(lockPath));
        this.curator = curator;
    }

    /** Public for testing only */
    public Lock(String lockPath, InterProcessLock mutex) {
        this.lockPath = lockPath;
        this.mutex = mutex;
        this.curator = null;
    }

    /** Take the lock with the given timeout. This may be called multiple times from the same thread - each matched by a close */
    public void acquire(Duration timeout) throws UncheckedTimeoutException {
        ThreadLockStats threadLockStats = LockStats.getForCurrentThread();
        threadLockStats.invokingAcquire(lockPath, timeout);

        final boolean acquired;
        try {
            acquired = mutex.acquire(timeout.toMillis(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            threadLockStats.acquireFailed();
            throw new RuntimeException("Exception acquiring lock '" + lockPath + "'", e);
        }

        if (!acquired) {
            threadLockStats.acquireTimedOut();
            throw new UncheckedTimeoutException("Timed out after waiting " + timeout +
                    " to acquire lock '" + lockPath + "'");
        }

        invoke(+1L, (lockPath, debug) -> threadLockStats.lockAcquired(debug), lockPath);
    }

    @FunctionalInterface
    private interface BiConsumer2 {
        void accept(String lockPath, String debug);
    }

    // TODO(hakon): Remove once debugging is unnecessary
    private void invoke(long reentryCountDiff, BiConsumer2 consumer, String lockPath) {
        long threadId = Thread.currentThread().getId();
        final long sequenceNumber;
        final Map<Long, Long> reentriesByThreadIdCopy;
        synchronized (monitor) {
            sequenceNumber = nextSequenceNumber++;
            reentriesByThreadId.merge(threadId, reentryCountDiff, (oldValue, argumentValue) -> {
                long sum = oldValue + argumentValue /* == reentryCountDiff */;
                if (sum == 0) {
                    // Remove from map
                    return null;
                } else {
                    return sum;
                }
            });
            reentriesByThreadIdCopy = Map.copyOf(reentriesByThreadId);
        }

        String debug = "thread " + threadId + " Lock 0x" + Integer.toHexString(System.identityHashCode(this)) +
                       "@" + created + " Curator 0x" + Integer.toHexString(System.identityHashCode(curator)) +
                       " lock " + lockPath + " #" + sequenceNumber +
                       ", reentries by thread ID = " + reentriesByThreadIdCopy;
        consumer.accept(lockPath, debug);
    }

    @Override
    public void close() {
        ThreadLockStats threadLockStats = LockStats.getForCurrentThread();
        // Update metrics now before release() to avoid double-counting time in locked state.
        // The lockPath must be sent down as close() may be invoked in an order not necessarily
        // equal to the reverse order of acquires.
        invoke(-1L, threadLockStats::preRelease, lockPath);
        try {
            mutex.release();
            threadLockStats.postRelease(lockPath);
        }
        catch (Exception e) {
            threadLockStats.releaseFailed(lockPath);
            throw new RuntimeException("Exception releasing lock '" + lockPath + "'", e);
        }
    }

    protected String lockPath() { return lockPath; }

    @Override
    public String toString() {
        return "Lock{" + lockPath + "}";
    }
}