FileMutex.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mutex;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\FileHelper;
  11. /**
  12. * FileMutex implements mutex "lock" mechanism via local file system files.
  13. *
  14. * This component relies on PHP `flock()` function.
  15. *
  16. * Application configuration example:
  17. *
  18. * ```php
  19. * [
  20. * 'components' => [
  21. * 'mutex' => [
  22. * 'class' => 'yii\mutex\FileMutex'
  23. * ],
  24. * ],
  25. * ]
  26. * ```
  27. *
  28. * > Note: this component can maintain the locks only for the single web server,
  29. * > it probably will not suffice in case you are using cloud server solution.
  30. *
  31. * > Warning: due to `flock()` function nature this component is unreliable when
  32. * > using a multithreaded server API like ISAPI.
  33. *
  34. * @see Mutex
  35. *
  36. * @author resurtm <resurtm@gmail.com>
  37. * @since 2.0
  38. */
  39. class FileMutex extends Mutex
  40. {
  41. /**
  42. * @var string the directory to store mutex files. You may use [path alias](guide:concept-aliases) here.
  43. * Defaults to the "mutex" subdirectory under the application runtime path.
  44. */
  45. public $mutexPath = '@runtime/mutex';
  46. /**
  47. * @var int the permission to be set for newly created mutex files.
  48. * This value will be used by PHP chmod() function. No umask will be applied.
  49. * If not set, the permission will be determined by the current environment.
  50. */
  51. public $fileMode;
  52. /**
  53. * @var int the permission to be set for newly created directories.
  54. * This value will be used by PHP chmod() function. No umask will be applied.
  55. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  56. * but read-only for other users.
  57. */
  58. public $dirMode = 0775;
  59. /**
  60. * @var resource[] stores all opened lock files. Keys are lock names and values are file handles.
  61. */
  62. private $_files = [];
  63. /**
  64. * Initializes mutex component implementation dedicated for UNIX, GNU/Linux, Mac OS X, and other UNIX-like
  65. * operating systems.
  66. * @throws InvalidConfigException
  67. */
  68. public function init()
  69. {
  70. parent::init();
  71. $this->mutexPath = Yii::getAlias($this->mutexPath);
  72. if (!is_dir($this->mutexPath)) {
  73. FileHelper::createDirectory($this->mutexPath, $this->dirMode, true);
  74. }
  75. }
  76. /**
  77. * Acquires lock by given name.
  78. * @param string $name of the lock to be acquired.
  79. * @param int $timeout time (in seconds) to wait for lock to become released.
  80. * @return bool acquiring result.
  81. */
  82. protected function acquireLock($name, $timeout = 0)
  83. {
  84. $filePath = $this->getLockFilePath($name);
  85. $waitTime = 0;
  86. while (true) {
  87. $file = fopen($filePath, 'w+');
  88. if ($file === false) {
  89. return false;
  90. }
  91. if ($this->fileMode !== null) {
  92. @chmod($filePath, $this->fileMode);
  93. }
  94. if (!flock($file, LOCK_EX | LOCK_NB)) {
  95. fclose($file);
  96. if (++$waitTime > $timeout) {
  97. return false;
  98. }
  99. sleep(1);
  100. continue;
  101. }
  102. // Under unix we delete the lock file before releasing the related handle. Thus it's possible that we've acquired a lock on
  103. // a non-existing file here (race condition). We must compare the inode of the lock file handle with the inode of the actual lock file.
  104. // If they do not match we simply continue the loop since we can assume the inodes will be equal on the next try.
  105. // Example of race condition without inode-comparison:
  106. // Script A: locks file
  107. // Script B: opens file
  108. // Script A: unlinks and unlocks file
  109. // Script B: locks handle of *unlinked* file
  110. // Script C: opens and locks *new* file
  111. // In this case we would have acquired two locks for the same file path.
  112. if (DIRECTORY_SEPARATOR !== '\\' && fstat($file)['ino'] !== @fileinode($filePath)) {
  113. clearstatcache(true, $filePath);
  114. flock($file, LOCK_UN);
  115. fclose($file);
  116. continue;
  117. }
  118. $this->_files[$name] = $file;
  119. return true;
  120. }
  121. // Should not be reached normally.
  122. return false;
  123. }
  124. /**
  125. * Releases lock by given name.
  126. * @param string $name of the lock to be released.
  127. * @return bool release result.
  128. */
  129. protected function releaseLock($name)
  130. {
  131. if (!isset($this->_files[$name])) {
  132. return false;
  133. }
  134. if (DIRECTORY_SEPARATOR === '\\') {
  135. // Under windows it's not possible to delete a file opened via fopen (either by own or other process).
  136. // That's why we must first unlock and close the handle and then *try* to delete the lock file.
  137. flock($this->_files[$name], LOCK_UN);
  138. fclose($this->_files[$name]);
  139. @unlink($this->getLockFilePath($name));
  140. } else {
  141. // Under unix it's possible to delete a file opened via fopen (either by own or other process).
  142. // That's why we must unlink (the currently locked) lock file first and then unlock and close the handle.
  143. unlink($this->getLockFilePath($name));
  144. flock($this->_files[$name], LOCK_UN);
  145. fclose($this->_files[$name]);
  146. }
  147. unset($this->_files[$name]);
  148. return true;
  149. }
  150. /**
  151. * Generate path for lock file.
  152. * @param string $name
  153. * @return string
  154. * @since 2.0.10
  155. */
  156. protected function getLockFilePath($name)
  157. {
  158. return $this->mutexPath . DIRECTORY_SEPARATOR . md5($name) . '.lock';
  159. }
  160. }