Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 80
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
QuorumLockManager
0.00% covered (danger)
0.00%
0 / 79
0.00% covered (danger)
0.00%
0 / 7
930
0.00% covered (danger)
0.00%
0 / 1
 doLockByType
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
72
 doUnlockByType
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 doLockingRequestBucket
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
42
 doUnlockingRequestBucket
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 getBucketFromPath
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 isServerUp
n/a
0 / 0
n/a
0 / 0
0
 getLocksOnServer
n/a
0 / 0
n/a
0 / 0
0
 freeLocksOnServer
n/a
0 / 0
n/a
0 / 0
0
 releaseAllLocks
n/a
0 / 0
n/a
0 / 0
0
 doLock
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 doUnlock
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6namespace Wikimedia\LockManager;
7
8use LogicException;
9use StatusValue;
10
11/**
12 * Base class for lock managers that use a quorum of peer servers for locks.
13 *
14 * The resource space can also be sharded into separate peer groups.
15 *
16 * See MemcLockManager and RedisLockManager.
17 *
18 * @stable to extend
19 * @ingroup LockManager
20 * @since 1.20
21 */
22abstract class QuorumLockManager extends LockManager {
23    /** @var array Map of bucket indexes to peer server lists */
24    protected $srvsByBucket = []; // (bucket index => (lsrv1, lsrv2, ...))
25
26    /** @var array Map of degraded buckets */
27    protected $degradedBuckets = []; // (bucket index => UNIX timestamp)
28
29    /** @inheritDoc */
30    final protected function doLockByType( array $pathsByType ) {
31        $status = StatusValue::newGood();
32
33        $pathsByTypeByBucket = []; // (bucket => type => paths)
34        // Get locks that need to be acquired (buckets => locks)...
35        foreach ( $pathsByType as $type => $paths ) {
36            foreach ( $paths as $path ) {
37                if ( isset( $this->locksHeld[$path][$type] ) ) {
38                    ++$this->locksHeld[$path][$type];
39                } else {
40                    $bucket = $this->getBucketFromPath( $path );
41                    $pathsByTypeByBucket[$bucket][$type][] = $path;
42                }
43            }
44        }
45
46        // Acquire locks in each bucket in bucket order to reduce contention. Any blocking
47        // mutexes during the acquisition step will not involve circular waiting on buckets.
48        ksort( $pathsByTypeByBucket );
49
50        $lockedPaths = []; // files locked in this attempt (type => paths)
51        // Attempt to acquire these locks...
52        foreach ( $pathsByTypeByBucket as $bucket => $bucketPathsByType ) {
53            // Try to acquire the locks for this bucket
54            $status->merge( $this->doLockingRequestBucket( $bucket, $bucketPathsByType ) );
55            if ( !$status->isOK() ) {
56                $status->merge( $this->doUnlockByType( $lockedPaths ) );
57
58                return $status;
59            }
60            // Record these locks as active
61            foreach ( $bucketPathsByType as $type => $paths ) {
62                foreach ( $paths as $path ) {
63                    $this->locksHeld[$path][$type] = 1; // locked
64                    // Keep track of what locks were made in this attempt
65                    $lockedPaths[$type][] = $path;
66                }
67            }
68        }
69
70        return $status;
71    }
72
73    /**
74     * @stable to override
75     *
76     * @param array $pathsByType
77     *
78     * @return StatusValue
79     */
80    protected function doUnlockByType( array $pathsByType ) {
81        $status = StatusValue::newGood();
82
83        $pathsByTypeByBucket = []; // (bucket => type => paths)
84        foreach ( $pathsByType as $type => $paths ) {
85            foreach ( $paths as $path ) {
86                if ( !isset( $this->locksHeld[$path][$type] ) ) {
87                    $status->warning( 'lockmanager-notlocked', $path );
88                } else {
89                    --$this->locksHeld[$path][$type];
90                    // Reference count the locks held and release locks when zero
91                    if ( $this->locksHeld[$path][$type] <= 0 ) {
92                        unset( $this->locksHeld[$path][$type] );
93                        $bucket = $this->getBucketFromPath( $path );
94                        $pathsByTypeByBucket[$bucket][$type][] = $path;
95                    }
96                    if ( $this->locksHeld[$path] === [] ) {
97                        unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
98                    }
99                }
100            }
101        }
102
103        // Remove these specific locks if possible, or at least release
104        // all locks once this process is currently not holding any locks.
105        foreach ( $pathsByTypeByBucket as $bucket => $bucketPathsByType ) {
106            $status->merge( $this->doUnlockingRequestBucket( $bucket, $bucketPathsByType ) );
107        }
108        if ( $this->locksHeld === [] ) {
109            $status->merge( $this->releaseAllLocks() );
110            $this->degradedBuckets = []; // safe to retry the normal quorum
111        }
112
113        return $status;
114    }
115
116    /**
117     * Attempt to acquire locks with the peers for a bucket.
118     * This is all or nothing; if any key is locked then this totally fails.
119     *
120     * @param int $bucket
121     * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
122     * @return StatusValue
123     */
124    final protected function doLockingRequestBucket( $bucket, array $pathsByType ) {
125        $status = StatusValue::newGood();
126
127        $yesVotes = 0; // locks made on trustable servers
128        $votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
129        $quorum = floor( $votesLeft / 2 + 1 ); // simple majority
130        // Get votes for each peer, in order, until we have enough...
131        foreach ( $this->srvsByBucket[$bucket] as $lockSrv ) {
132            if ( !$this->isServerUp( $lockSrv ) ) {
133                --$votesLeft;
134                $status->warning( 'lockmanager-fail-svr-acquire', $lockSrv );
135                $this->degradedBuckets[$bucket] = time();
136                continue; // server down?
137            }
138            // Attempt to acquire the lock on this peer
139            $status->merge( $this->getLocksOnServer( $lockSrv, $pathsByType ) );
140            if ( !$status->isOK() ) {
141                return $status; // vetoed; resource locked
142            }
143            ++$yesVotes; // success for this peer
144            if ( $yesVotes >= $quorum ) {
145                return $status; // lock obtained
146            }
147            --$votesLeft;
148            $votesNeeded = $quorum - $yesVotes;
149            if ( $votesNeeded > $votesLeft ) {
150                break; // short-circuit
151            }
152        }
153        // At this point, we must not have met the quorum
154        $status->setResult( false );
155
156        return $status;
157    }
158
159    /**
160     * Attempt to release locks with the peers for a bucket
161     *
162     * @param int $bucket
163     * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
164     * @return StatusValue
165     */
166    final protected function doUnlockingRequestBucket( $bucket, array $pathsByType ) {
167        $status = StatusValue::newGood();
168
169        $yesVotes = 0; // locks freed on trustable servers
170        $votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
171        $quorum = floor( $votesLeft / 2 + 1 ); // simple majority
172        $isDegraded = isset( $this->degradedBuckets[$bucket] ); // not the normal quorum?
173        foreach ( $this->srvsByBucket[$bucket] as $lockSrv ) {
174            if ( !$this->isServerUp( $lockSrv ) ) {
175                $status->warning( 'lockmanager-fail-svr-release', $lockSrv );
176            } else {
177                // Attempt to release the lock on this peer
178                $status->merge( $this->freeLocksOnServer( $lockSrv, $pathsByType ) );
179                ++$yesVotes; // success for this peer
180                // Normally the first peers form the quorum, and the others are ignored.
181                // Ignore them in this case, but not when an alternative quorum was used.
182                if ( $yesVotes >= $quorum && !$isDegraded ) {
183                    break; // lock released
184                }
185            }
186        }
187        // Set a bad StatusValue if the quorum was not met.
188        // Assumes the same "up" servers as during the acquire step.
189        $status->setResult( $yesVotes >= $quorum );
190
191        return $status;
192    }
193
194    /**
195     * Get the bucket for resource path.
196     * This should avoid throwing any exceptions.
197     *
198     * @param string $path
199     * @return int
200     */
201    protected function getBucketFromPath( $path ) {
202        $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
203        return (int)base_convert( $prefix, 16, 10 ) % count( $this->srvsByBucket );
204    }
205
206    /**
207     * Check if a lock server is up.
208     * This should process cache results to reduce RTT.
209     *
210     * @param string $lockSrv
211     * @return bool
212     */
213    abstract protected function isServerUp( $lockSrv );
214
215    /**
216     * Get a connection to a lock server and acquire locks
217     *
218     * @param string $lockSrv
219     * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
220     * @return StatusValue
221     */
222    abstract protected function getLocksOnServer( $lockSrv, array $pathsByType );
223
224    /**
225     * Get a connection to a lock server and release locks on $paths.
226     *
227     * Subclasses must effectively implement this or releaseAllLocks().
228     *
229     * @param string $lockSrv
230     * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
231     * @return StatusValue
232     */
233    abstract protected function freeLocksOnServer( $lockSrv, array $pathsByType );
234
235    /**
236     * Release all locks that this session is holding.
237     *
238     * Subclasses must effectively implement this or freeLocksOnServer().
239     *
240     * @return StatusValue
241     */
242    abstract protected function releaseAllLocks();
243
244    /** @inheritDoc */
245    final protected function doLock( array $paths, $type ) {
246        // @phan-suppress-previous-line PhanPluginNeverReturnMethod
247        throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
248    }
249
250    /** @inheritDoc */
251    final protected function doUnlock( array $paths, $type ) {
252        // @phan-suppress-previous-line PhanPluginNeverReturnMethod
253        throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
254    }
255}
256/** @deprecated class alias since 1.46 */
257class_alias( QuorumLockManager::class, 'QuorumLockManager' );