3 * @file src/Util/Lock.php
5 namespace Friendica\Core;
8 * @file src/Core/Lock.php
9 * @brief Functions for preventing parallel execution of functions
12 use Friendica\Core\Cache\CacheDriverFactory;
13 use Friendica\Core\Cache\IMemoryCacheDriver;
16 * @brief This class contain Functions for preventing parallel execution of functions
21 * @var Lock\ILockDriver;
23 static $driver = null;
25 public static function init()
27 $lock_driver = Config::get('system', 'lock_driver', 'default');
30 switch ($lock_driver) {
34 $cache_driver = CacheDriverFactory::create($lock_driver);
35 if ($cache_driver instanceof IMemoryCacheDriver) {
36 self::$driver = new Lock\CacheLockDriver($cache_driver);
41 self::$driver = new Lock\DatabaseLockDriver();
45 self::$driver = new Lock\SemaphoreLockDriver();
49 self::useAutoDriver();
51 } catch (\Exception $exception) {
52 logger ('Driver \'' . $lock_driver . '\' failed - Fallback to \'useAutoDriver()\'');
53 self::useAutoDriver();
58 * @brief This method tries to find the best - local - locking method for Friendica
60 * The following sequence will be tried:
61 * 1. Semaphore Locking
66 private static function useAutoDriver() {
68 // 1. Try to use Semaphores for - local - locking
69 if (function_exists('sem_get')) {
71 self::$driver = new Lock\SemaphoreLockDriver();
73 } catch (\Exception $exception) {
74 logger ('Using Semaphore driver for locking failed: ' . $exception->getMessage());
78 // 2. Try to use Cache Locking (don't use the DB-Cache Locking because it works different!)
79 $cache_driver = Config::get('system', 'cache_driver', 'database');
80 if ($cache_driver != 'database') {
82 $lock_driver = CacheDriverFactory::create($cache_driver);
83 if ($lock_driver instanceof IMemoryCacheDriver) {
84 self::$driver = new Lock\CacheLockDriver($lock_driver);
87 } catch (\Exception $exception) {
88 logger('Using Cache driver for locking failed: ' . $exception->getMessage());
92 // 3. Use Database Locking as a Fallback
93 self::$driver = new Lock\DatabaseLockDriver();
97 * Returns the current cache driver
99 * @return Lock\ILockDriver;
101 private static function getDriver()
103 if (self::$driver === null) {
107 return self::$driver;
111 * @brief Acquires a lock for a given name
113 * @param string $key Name of the lock
114 * @param integer $timeout Seconds until we give up
116 * @return boolean Was the lock successful?
118 public static function acquireLock($key, $timeout = 120)
120 return self::getDriver()->acquire($key, $timeout);
124 * @brief Releases a lock if it was set by us
126 * @param string $key Name of the lock
129 public static function releaseLock($key)
131 return self::getDriver()->release($key);
135 * @brief Releases all lock that were set by us
138 public static function releaseAll()
140 self::getDriver()->releaseAll();