memcachelockingprovider.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * @author Robin Appelman <icewind@owncloud.com>
  4. *
  5. * @copyright Copyright (c) 2015, ownCloud, Inc.
  6. * @license AGPL-3.0
  7. *
  8. * This code is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License, version 3,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License, version 3,
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>
  19. *
  20. */
  21. namespace OC\Lock;
  22. use OCP\Lock\ILockingProvider;
  23. use OCP\Lock\LockedException;
  24. use OCP\IMemcache;
  25. class MemcacheLockingProvider implements ILockingProvider {
  26. /**
  27. * @var \OCP\IMemcache
  28. */
  29. private $memcache;
  30. /**
  31. * @param \OCP\IMemcache $memcache
  32. */
  33. public function __construct(IMemcache $memcache) {
  34. $this->memcache = $memcache;
  35. }
  36. /**
  37. * @param string $path
  38. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  39. * @return bool
  40. */
  41. public function isLocked($path, $type) {
  42. $lockValue = $this->memcache->get($path);
  43. if ($type === self::LOCK_SHARED) {
  44. return $lockValue > 0;
  45. } else if ($type === self::LOCK_EXCLUSIVE) {
  46. return $lockValue === 'exclusive';
  47. } else {
  48. return false;
  49. }
  50. }
  51. /**
  52. * @param string $path
  53. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  54. * @throws \OCP\Lock\LockedException
  55. */
  56. public function acquireLock($path, $type) {
  57. if ($type === self::LOCK_SHARED) {
  58. if (!$this->memcache->inc($path)) {
  59. throw new LockedException($path);
  60. }
  61. } else {
  62. $this->memcache->add($path, 0);
  63. if (!$this->memcache->cas($path, 0, 'exclusive')) {
  64. throw new LockedException($path);
  65. }
  66. }
  67. }
  68. /**
  69. * @param string $path
  70. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  71. */
  72. public function releaseLock($path, $type) {
  73. if ($type === self::LOCK_SHARED) {
  74. $this->memcache->dec($path);
  75. } else if ($type === self::LOCK_EXCLUSIVE) {
  76. $this->memcache->cas($path, 'exclusive', 0);
  77. }
  78. }
  79. }