MySqlLockBackend.php
121 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Matomo - free/libre analytics platform |
| 5 | * |
| 6 | * @link https://matomo.org |
| 7 | * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later |
| 8 | */ |
| 9 | namespace Piwik\Concurrency\LockBackend; |
| 10 | |
| 11 | use Piwik\Common; |
| 12 | use Piwik\Concurrency\LockBackend; |
| 13 | use Piwik\Db; |
| 14 | class MySqlLockBackend implements LockBackend |
| 15 | { |
| 16 | public const TABLE_NAME = 'locks'; |
| 17 | /** |
| 18 | * fyi: does not support list keys at the moment just because not really needed so much just yet |
| 19 | */ |
| 20 | public function getKeysMatchingPattern($pattern) |
| 21 | { |
| 22 | $sql = sprintf('SELECT SQL_NO_CACHE distinct `key` FROM `%s` WHERE `key` like ? and %s', self::getTableName(), $this->getQueryPartExpiryTime()); |
| 23 | $pattern = str_replace('*', '%', $pattern); |
| 24 | $keys = Db::fetchAll($sql, array($pattern)); |
| 25 | $raw = array_column($keys, 'key'); |
| 26 | return $raw; |
| 27 | } |
| 28 | public function setIfNotExists($key, $value, $ttlInSeconds) |
| 29 | { |
| 30 | if (empty($ttlInSeconds)) { |
| 31 | $ttlInSeconds = 999999999; |
| 32 | } |
| 33 | // FYI: We used to have an INSERT INTO ... ON DUPLICATE UPDATE ... However, this can be problematic in concurrency issues |
| 34 | // because the ON DUPLICATE UPDATE may work successfully for 2 jobs at the same time but only one of them got the lock then. |
| 35 | // This would be perfectly fine if we did something like `return $this->get($key) === $value` to 100% detect which process |
| 36 | // got the lock as we do now. However, maybe the expireTime gets overwritten with a wrong value or so. That's why we |
| 37 | // rather try to get the lock with the insert only because only one job can succeed with this. If below flow with the |
| 38 | // delete becomes to slow, we may be able to use the INSERT INTO ... ON DUPLICATE UPDATE again. |
| 39 | if ($this->get($key)) { |
| 40 | return \false; |
| 41 | // a value is set, won't be possible to insert |
| 42 | } |
| 43 | $tablePrefixed = self::getTableName(); |
| 44 | // remove any existing but expired lock |
| 45 | // todo: we could combine get() and keyExists() in one query! |
| 46 | if ($this->keyExists($key)) { |
| 47 | // most of the time an expired key should not exist... we don't want to lock the row unnecessarily therefore we check first |
| 48 | // if value exists... |
| 49 | $sql = sprintf('DELETE FROM `%s` WHERE `key` = ? and not (%s)', $tablePrefixed, $this->getQueryPartExpiryTime()); |
| 50 | Db::query($sql, array($key)); |
| 51 | } |
| 52 | $query = sprintf('INSERT INTO `%s` (`key`, `value`, `expiry_time`) |
| 53 | VALUES (?,?,(UNIX_TIMESTAMP() + ?))', $tablePrefixed); |
| 54 | // we make sure to update the row if the key is expired and consider it as "deleted" |
| 55 | try { |
| 56 | Db::query($query, array($key, $value, (int) $ttlInSeconds)); |
| 57 | } catch (\Exception $e) { |
| 58 | if ($e->getCode() == 23000 || strpos($e->getMessage(), 'Duplicate entry') !== \false || strpos($e->getMessage(), ' 1062 ') !== \false) { |
| 59 | return \false; |
| 60 | } |
| 61 | throw $e; |
| 62 | } |
| 63 | // we make sure we got the lock |
| 64 | return $this->get($key) === $value; |
| 65 | } |
| 66 | public function get($key) |
| 67 | { |
| 68 | $sql = sprintf('SELECT SQL_NO_CACHE `value` FROM `%s` WHERE `key` = ? AND %s LIMIT 1', self::getTableName(), $this->getQueryPartExpiryTime()); |
| 69 | return Db::fetchOne($sql, array($key)); |
| 70 | } |
| 71 | public function deleteIfKeyHasValue($key, $value) |
| 72 | { |
| 73 | if (empty($value)) { |
| 74 | return \false; |
| 75 | } |
| 76 | $sql = sprintf('DELETE FROM `%s` WHERE `key` = ? and `value` = ?', self::getTableName()); |
| 77 | return $this->queryDidMakeChange($sql, array($key, $value)); |
| 78 | } |
| 79 | public function expireIfKeyHasValue($key, $value, $ttlInSeconds) |
| 80 | { |
| 81 | if (empty($value)) { |
| 82 | return \false; |
| 83 | } |
| 84 | // we need to use unix_timestamp in mysql and not time() in php since the local time might be different on each server |
| 85 | // better to rely on one central DB server time only |
| 86 | $sql = sprintf('UPDATE `%s` SET expiry_time = (UNIX_TIMESTAMP() + ?) WHERE `key` = ? and `value` = ?', self::getTableName()); |
| 87 | $success = $this->queryDidMakeChange($sql, array((int) $ttlInSeconds, $key, $value)); |
| 88 | if (!$success) { |
| 89 | // the above update did not work because the same time was already set and we just tried to set the same ttl |
| 90 | // again too fast within one second |
| 91 | return $value === $this->get($key); |
| 92 | } |
| 93 | return \true; |
| 94 | } |
| 95 | public function keyExists($key) |
| 96 | { |
| 97 | $sql = sprintf('SELECT SQL_NO_CACHE 1 FROM `%s` WHERE `key` = ? LIMIT 1', self::getTableName()); |
| 98 | $value = Db::fetchOne($sql, array($key)); |
| 99 | return !empty($value); |
| 100 | } |
| 101 | private function queryDidMakeChange($sql, $bind = array()) |
| 102 | { |
| 103 | $query = Db::query($sql, $bind); |
| 104 | if (is_object($query) && method_exists($query, 'rowCount')) { |
| 105 | // anything else but mysqli in tracker mode |
| 106 | return (bool) $query->rowCount(); |
| 107 | } else { |
| 108 | // mysqli in tracker mode |
| 109 | return (bool) Db::get()->rowCount($query); |
| 110 | } |
| 111 | } |
| 112 | private static function getTableName() |
| 113 | { |
| 114 | return Common::prefixTable(self::TABLE_NAME); |
| 115 | } |
| 116 | private function getQueryPartExpiryTime() |
| 117 | { |
| 118 | return 'UNIX_TIMESTAMP() <= expiry_time'; |
| 119 | } |
| 120 | } |
| 121 |