3 namespace Friendica\Core;
6 * @file src/Core/Lock.php
7 * @brief Functions for preventing parallel execution of functions
10 use Friendica\Core\Logger;
11 use Friendica\Core\Cache\CacheDriverFactory;
12 use Friendica\Core\Cache\IMemoryCacheDriver;
15 * @brief This class contain Functions for preventing parallel execution of functions
20 * @var Lock\ILockDriver;
22 static $driver = null;
24 public static function init()
26 $lock_driver = Config::get('system', 'lock_driver', 'default');
29 switch ($lock_driver) {
33 $cache_driver = CacheDriverFactory::create($lock_driver);
34 if ($cache_driver instanceof IMemoryCacheDriver) {
35 self::$driver = new Lock\CacheLockDriver($cache_driver);
40 self::$driver = new Lock\DatabaseLockDriver();
44 self::$driver = new Lock\SemaphoreLockDriver();
48 self::useAutoDriver();
50 } catch (\Exception $exception) {
51 Logger::log('Driver \'' . $lock_driver . '\' failed - Fallback to \'useAutoDriver()\'');
52 self::useAutoDriver();
57 * @brief This method tries to find the best - local - locking method for Friendica
59 * The following sequence will be tried:
60 * 1. Semaphore Locking
65 private static function useAutoDriver() {
67 // 1. Try to use Semaphores for - local - locking
68 if (function_exists('sem_get')) {
70 self::$driver = new Lock\SemaphoreLockDriver();
72 } catch (\Exception $exception) {
73 Logger::log('Using Semaphore driver for locking failed: ' . $exception->getMessage());
77 // 2. Try to use Cache Locking (don't use the DB-Cache Locking because it works different!)
78 $cache_driver = Config::get('system', 'cache_driver', 'database');
79 if ($cache_driver != 'database') {
81 $lock_driver = CacheDriverFactory::create($cache_driver);
82 if ($lock_driver instanceof IMemoryCacheDriver) {
83 self::$driver = new Lock\CacheLockDriver($lock_driver);
86 } catch (\Exception $exception) {
87 Logger::log('Using Cache driver for locking failed: ' . $exception->getMessage());
91 // 3. Use Database Locking as a Fallback
92 self::$driver = new Lock\DatabaseLockDriver();
96 * Returns the current cache driver
98 * @return Lock\ILockDriver;
100 private static function getDriver()
102 if (self::$driver === null) {
106 return self::$driver;
110 * @brief Acquires a lock for a given name
112 * @param string $key Name of the lock
113 * @param integer $timeout Seconds until we give up
114 * @param integer $ttl The Lock lifespan, must be one of the Cache constants
116 * @return boolean Was the lock successful?
118 public static function acquire($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
120 return self::getDriver()->acquireLock($key, $timeout, $ttl);
124 * @brief Releases a lock if it was set by us
126 * @param string $key Name of the lock
129 public static function release($key)
131 self::getDriver()->releaseLock($key);
135 * @brief Releases all lock that were set by us
138 public static function releaseAll()
140 self::getDriver()->releaseAll();