4 * @file src/Core/Lock.php
5 * @brief Functions for preventing parallel execution of functions
8 namespace Friendica\Core;
10 use Friendica\Core\Cache\CacheDriverFactory;
11 use Friendica\Core\Cache\IMemoryCacheDriver;
14 * @brief This class contain Functions for preventing parallel execution of functions
19 * @var Lock\ILockDriver;
21 static $driver = null;
23 public static function init()
25 $lock_driver = Config::get('system', 'lock_driver', 'default');
28 switch ($lock_driver) {
32 $cache_driver = CacheDriverFactory::create($lock_driver);
33 if ($cache_driver instanceof IMemoryCacheDriver) {
34 self::$driver = new Lock\CacheLockDriver($cache_driver);
39 self::$driver = new Lock\DatabaseLockDriver();
43 self::$driver = new Lock\SemaphoreLockDriver();
47 self::useAutoDriver();
49 } catch (\Exception $exception) {
50 Logger::log('Driver \'' . $lock_driver . '\' failed - Fallback to \'useAutoDriver()\'');
51 self::useAutoDriver();
56 * @brief This method tries to find the best - local - locking method for Friendica
58 * The following sequence will be tried:
59 * 1. Semaphore Locking
64 private static function useAutoDriver() {
66 // 1. Try to use Semaphores for - local - locking
67 if (function_exists('sem_get')) {
69 self::$driver = new Lock\SemaphoreLockDriver();
71 } catch (\Exception $exception) {
72 Logger::log('Using Semaphore driver for locking failed: ' . $exception->getMessage());
76 // 2. Try to use Cache Locking (don't use the DB-Cache Locking because it works different!)
77 $cache_driver = Config::get('system', 'cache_driver', 'database');
78 if ($cache_driver != 'database') {
80 $lock_driver = CacheDriverFactory::create($cache_driver);
81 if ($lock_driver instanceof IMemoryCacheDriver) {
82 self::$driver = new Lock\CacheLockDriver($lock_driver);
85 } catch (\Exception $exception) {
86 Logger::log('Using Cache driver for locking failed: ' . $exception->getMessage());
90 // 3. Use Database Locking as a Fallback
91 self::$driver = new Lock\DatabaseLockDriver();
95 * Returns the current cache driver
97 * @return Lock\ILockDriver;
99 private static function getDriver()
101 if (self::$driver === null) {
105 return self::$driver;
109 * @brief Acquires a lock for a given name
111 * @param string $key Name of the lock
112 * @param integer $timeout Seconds until we give up
113 * @param integer $ttl The Lock lifespan, must be one of the Cache constants
115 * @return boolean Was the lock successful?
117 public static function acquire($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
119 return self::getDriver()->acquireLock($key, $timeout, $ttl);
123 * @brief Releases a lock if it was set by us
125 * @param string $key Name of the lock
128 public static function release($key)
130 self::getDriver()->releaseLock($key);
134 * @brief Releases all lock that were set by us
137 public static function releaseAll()
139 self::getDriver()->releaseAll();