+ public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
+ // Avoid deadlocks and allow lock reentry if specified
+ if ( isset( $this->locks[$key] ) ) {
+ if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
+ ++$this->locks[$key]['depth'];
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ list( $serverIndex ) = $this->getTableByKey( $key );
+ try {
+ $db = $this->getDB( $serverIndex );
+ $ok = $db->lock( $key, __METHOD__, $timeout );
+ if ( $ok ) {
+ $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
+ }
+
+ $this->logger->warning(
+ __METHOD__ . " failed due to timeout for {key}.",
+ [ 'key' => $key, 'timeout' => $timeout ]
+ );
+
+ return $ok;
+ } catch ( DBError $e ) {
+ $this->handleWriteError( $e, $db, $serverIndex );
+ $ok = false;
+ }
+
+ return $ok;
+ }
+
+ public function unlock( $key ) {
+ if ( !isset( $this->locks[$key] ) ) {
+ return false;
+ }
+
+ if ( --$this->locks[$key]['depth'] <= 0 ) {
+ unset( $this->locks[$key] );
+
+ list( $serverIndex ) = $this->getTableByKey( $key );
+ try {
+ $db = $this->getDB( $serverIndex );
+ $ok = $db->unlock( $key, __METHOD__ );
+ if ( !$ok ) {
+ $this->logger->warning(
+ __METHOD__ . ' failed to release lock for {key}.',
+ [ 'key' => $key ]
+ );
+ }
+ } catch ( DBError $e ) {
+ $this->handleWriteError( $e, $db, $serverIndex );
+ $ok = false;
+ }
+ } else {
+ $ok = false;
+ }
+
+ return $ok;
+ }
+