Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Flock based file locking factory.
  19   *
  20   * The file lock factory returns file locks locked with the flock function. Works OK, except on some
  21   * NFS, exotic shared storage and exotic server OSes (like windows). On windows, a second attempt to get a
  22   * lock will block indefinitely instead of timing out.
  23   *
  24   * @package    core
  25   * @category   lock
  26   * @copyright  Damyon Wiese 2013
  27   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  28   */
  29  
  30  namespace core\lock;
  31  
  32  defined('MOODLE_INTERNAL') || die();
  33  
  34  /**
  35   * Flock based file locking factory.
  36   *
  37   * The file lock factory returns file locks locked with the flock function. Works OK, except on some
  38   * NFS, exotic shared storage and exotic server OSes (like windows). On windows, a second attempt to get a
  39   * lock will block indefinitely instead of timing out.
  40   *
  41   * @package   core
  42   * @category  lock
  43   * @copyright Damyon Wiese 2013
  44   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  45   */
  46  class file_lock_factory implements lock_factory {
  47  
  48      /** @var string $type - The type of lock, e.g. cache, cron, session. */
  49      protected $type;
  50  
  51      /** @var string $lockdirectory - Full system path to the directory used to store file locks. */
  52      protected $lockdirectory;
  53  
  54      /** @var boolean $verbose - If true, debugging info about the owner of the lock will be written to the lock file. */
  55      protected $verbose;
  56  
  57      /**
  58       * Create this lock factory.
  59       *
  60       * @param string $type - The type, e.g. cron, cache, session
  61       * @param string|null $lockdirectory - Optional path to the lock directory, to override defaults.
  62       */
  63      public function __construct($type, ?string $lockdirectory = null) {
  64          global $CFG;
  65  
  66          $this->type = $type;
  67          if (!is_null($lockdirectory)) {
  68              $this->lockdirectory = $lockdirectory;
  69          } else if (!isset($CFG->file_lock_root)) {
  70              $this->lockdirectory = $CFG->dataroot . '/lock';
  71          } else {
  72              $this->lockdirectory = $CFG->file_lock_root;
  73          }
  74          $this->verbose = false;
  75          if ($CFG->debugdeveloper) {
  76              $this->verbose = true;
  77          }
  78      }
  79  
  80      /**
  81       * Return information about the blocking behaviour of the lock type on this platform.
  82       * @return boolean - False if attempting to get a lock will block indefinitely.
  83       */
  84      public function supports_timeout() {
  85          global $CFG;
  86  
  87          return $CFG->ostype !== 'WINDOWS';
  88      }
  89  
  90      /**
  91       * This lock type will be automatically released when a process ends.
  92       * @return boolean - True
  93       */
  94      public function supports_auto_release() {
  95          return true;
  96      }
  97  
  98      /**
  99       * Is available.
 100       * @return boolean - True if preventfilelocking is not set - or the file_lock_root is not in dataroot.
 101       */
 102      public function is_available() {
 103          global $CFG;
 104          $preventfilelocking = !empty($CFG->preventfilelocking);
 105          $lockdirisdataroot = true;
 106          if (strpos($this->lockdirectory, $CFG->dataroot) !== 0) {
 107              $lockdirisdataroot = false;
 108          }
 109          return !$preventfilelocking || !$lockdirisdataroot;
 110      }
 111  
 112      /**
 113       * Multiple locks for the same resource cannot be held from a single process.
 114       *
 115       * @deprecated since Moodle 3.10.
 116       * @return boolean - False
 117       */
 118      public function supports_recursion() {
 119          debugging('The function supports_recursion() is deprecated, please do not use it anymore.',
 120              DEBUG_DEVELOPER);
 121          return false;
 122      }
 123  
 124      /**
 125       * Get some info that might be useful for debugging.
 126       * @return boolean - string
 127       */
 128      protected function get_debug_info() {
 129          return 'host:' . php_uname('n') . ', pid:' . getmypid() . ', time:' . time();
 130      }
 131  
 132      /**
 133       * Get a lock within the specified timeout or return false.
 134       * @param string $resource - The identifier for the lock. Should use frankenstyle prefix.
 135       * @param int $timeout - The number of seconds to wait for a lock before giving up.
 136       * @param int $maxlifetime - Unused by this lock type.
 137       * @return boolean - true if a lock was obtained.
 138       */
 139      public function get_lock($resource, $timeout, $maxlifetime = 86400) {
 140          $giveuptime = time() + $timeout;
 141  
 142          $hash = md5($this->type . '_' . $resource);
 143          $lockdir = $this->lockdirectory . '/' . substr($hash, 0, 2);
 144  
 145          if (!check_dir_exists($lockdir, true, true)) {
 146              return false;
 147          }
 148  
 149          $lockfilename = $lockdir . '/' . $hash;
 150  
 151          $filehandle = fopen($lockfilename, "wb");
 152  
 153          // Could not open the lock file.
 154          if (!$filehandle) {
 155              return false;
 156          }
 157  
 158          do {
 159              // Will block on windows. So sad.
 160              $wouldblock = false;
 161              $locked = flock($filehandle, LOCK_EX | LOCK_NB, $wouldblock);
 162              if (!$locked && $wouldblock && $timeout > 0) {
 163                  usleep(rand(10000, 250000)); // Sleep between 10 and 250 milliseconds.
 164              }
 165              // Try until the giveup time.
 166          } while (!$locked && $wouldblock && time() < $giveuptime);
 167  
 168          if (!$locked) {
 169              fclose($filehandle);
 170              return false;
 171          }
 172          if ($this->verbose) {
 173              fwrite($filehandle, $this->get_debug_info());
 174          }
 175          return new lock($filehandle, $this);
 176      }
 177  
 178      /**
 179       * Release a lock that was previously obtained with @lock.
 180       * @param lock $lock - A lock obtained from this factory.
 181       * @return boolean - true if the lock is no longer held (including if it was never held).
 182       */
 183      public function release_lock(lock $lock) {
 184          $handle = $lock->get_key();
 185  
 186          if (!$handle) {
 187              // We didn't have a lock.
 188              return false;
 189          }
 190  
 191          $result = flock($handle, LOCK_UN);
 192          fclose($handle);
 193          return $result;
 194      }
 195  
 196      /**
 197       * Extend a lock that was previously obtained with @lock.
 198       *
 199       * @deprecated since Moodle 3.10.
 200       * @param lock $lock - not used
 201       * @param int $maxlifetime - not used
 202       * @return boolean - true if the lock was extended.
 203       */
 204      public function extend_lock(lock $lock, $maxlifetime = 86400) {
 205          debugging('The function extend_lock() is deprecated, please do not use it anymore.',
 206              DEBUG_DEVELOPER);
 207          // Not supported by this factory.
 208          return false;
 209      }
 210  
 211  }