mutex.class.inc.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. // Copyright (C) 2013-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class iTopMutex
  20. * A class to serialize the execution of some code sections
  21. * Emulates the API of PECL Mutex class
  22. * Relies on MySQL locks because the API sem_get is not always present in the
  23. * installed PHP.
  24. *
  25. * @copyright Copyright (C) 2013-2017 Combodo SARL
  26. * @license http://opensource.org/licenses/AGPL-3.0
  27. */
  28. class iTopMutex
  29. {
  30. protected $sName;
  31. protected $hDBLink;
  32. protected $bLocked; // Whether or not this instance of the Mutex is locked
  33. static protected $aAcquiredLocks = array(); // Number of instances of the Mutex, having the lock, in this page
  34. public function __construct($sName, $sDBHost = null, $sDBUser = null, $sDBPwd = null)
  35. {
  36. // Compute the name of a lock for mysql
  37. // Note: names are server-wide!!! So let's make the name specific to this iTop instance
  38. $oConfig = MetaModel::GetConfig();
  39. if ($oConfig === null)
  40. {
  41. $oConfig = utils::GetConfig(); // Will return an empty config when called during the setup
  42. }
  43. $sDBName = $oConfig->GetDBName();
  44. $sDBSubname = $oConfig->GetDBSubname();
  45. $this->sName = 'itop.'.$sName;
  46. if (substr($sName, -strlen($sDBName.$sDBSubname)) != $sDBName.$sDBSubname)
  47. {
  48. // If the name supplied already ends with the expected suffix
  49. // don't add it twice, since the setup may try to detect an already
  50. // running cron job by its mutex, without knowing if the config already exists or not
  51. $this->sName .= $sDBName.$sDBSubname;
  52. }
  53. $this->bLocked = false; // Not yet locked
  54. if (!array_key_exists($this->sName, self::$aAcquiredLocks))
  55. {
  56. self::$aAcquiredLocks[$this->sName] = 0;
  57. }
  58. // It is a MUST to create a dedicated session each time a lock is required, because
  59. // using GET_LOCK anytime on the same session will RELEASE the current and unique session lock (known issue)
  60. $sDBHost = is_null($sDBHost) ? $oConfig->GetDBHost() : $sDBHost;
  61. $sDBUser = is_null($sDBUser) ? $oConfig->GetDBUser() : $sDBUser;
  62. $sDBPwd = is_null($sDBPwd) ? $oConfig->GetDBPwd() : $sDBPwd;
  63. $this->InitMySQLSession($sDBHost, $sDBUser, $sDBPwd);
  64. }
  65. public function __destruct()
  66. {
  67. if ($this->bLocked)
  68. {
  69. $this->Unlock();
  70. }
  71. mysqli_close($this->hDBLink);
  72. }
  73. /**
  74. * Acquire the mutex
  75. */
  76. public function Lock()
  77. {
  78. if ($this->bLocked)
  79. {
  80. // Lock already acquired
  81. return;
  82. }
  83. if (self::$aAcquiredLocks[$this->sName] == 0)
  84. {
  85. do
  86. {
  87. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 3600)");
  88. if (is_null($res))
  89. {
  90. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  91. }
  92. // $res === '1' means I hold the lock
  93. // $res === '0' means it timed out
  94. }
  95. while ($res !== '1');
  96. }
  97. $this->bLocked = true;
  98. self::$aAcquiredLocks[$this->sName]++;
  99. }
  100. /**
  101. * Attempt to acquire the mutex
  102. * @returns bool True if the mutex is acquired, false if already locked elsewhere
  103. */
  104. public function TryLock()
  105. {
  106. if ($this->bLocked)
  107. {
  108. return true; // Already acquired
  109. }
  110. if (self::$aAcquiredLocks[$this->sName] > 0)
  111. {
  112. self::$aAcquiredLocks[$this->sName]++;
  113. $this->bLocked = true;
  114. return true;
  115. }
  116. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 0)");
  117. if (is_null($res))
  118. {
  119. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  120. }
  121. // $res === '1' means I hold the lock
  122. // $res === '0' means it timed out
  123. if ($res === '1')
  124. {
  125. $this->bLocked = true;
  126. self::$aAcquiredLocks[$this->sName]++;
  127. }
  128. if (($res !== '1') && ($res !== '0'))
  129. {
  130. $sMsg = 'GET_LOCK('.$this->sName.', 0) returned: '.var_export($res, true).'. Expected values are: 0, 1 or null';
  131. IssueLog::Error($sMsg);
  132. throw new Exception($sMsg);
  133. }
  134. return ($res !== '0');
  135. }
  136. /**
  137. * Check if the mutex is locked WITHOUT TRYING TO ACQUIRE IT
  138. * @returns bool True if the mutex is in use, false otherwise
  139. */
  140. public function IsLocked()
  141. {
  142. if ($this->bLocked)
  143. {
  144. return true; // Already acquired
  145. }
  146. if (self::$aAcquiredLocks[$this->sName] > 0)
  147. {
  148. return true;
  149. }
  150. $res = $this->QueryToScalar("SELECT IS_FREE_LOCK('".$this->sName."')"); // IS_FREE_LOCK detects some error cases that IS_USED_LOCK do not detect
  151. if (is_null($res))
  152. {
  153. $sMsg = "MySQL Error, IS_FREE_LOCK('".$this->sName."') returned null. Error (".mysqli_errno($this->hDBLink).") = '".mysqli_error($this->hDBLink)."'";
  154. IssueLog::Error($sMsg);
  155. throw new Exception($sMsg);
  156. }
  157. else if ($res == '1')
  158. {
  159. // Lock is free
  160. return false;
  161. }
  162. return true;
  163. }
  164. /**
  165. * Release the mutex
  166. */
  167. public function Unlock()
  168. {
  169. if (!$this->bLocked)
  170. {
  171. // ??? the lock is not acquired, exit
  172. return;
  173. }
  174. if (self::$aAcquiredLocks[$this->sName] == 0)
  175. {
  176. return; // Safety net
  177. }
  178. if (self::$aAcquiredLocks[$this->sName] == 1)
  179. {
  180. $res = $this->QueryToScalar("SELECT RELEASE_LOCK('".$this->sName."')");
  181. }
  182. $this->bLocked = false;
  183. self::$aAcquiredLocks[$this->sName]--;
  184. }
  185. public function InitMySQLSession($sHost, $sUser, $sPwd)
  186. {
  187. $aConnectInfo = explode(':', $sHost);
  188. if (count($aConnectInfo) > 1)
  189. {
  190. // Override the default port
  191. $sServer = $aConnectInfo[0];
  192. $iPort = $aConnectInfo[1];
  193. $this->hDBLink = @mysqli_connect($sServer, $sUser, $sPwd, '', $iPort);
  194. }
  195. else
  196. {
  197. $this->hDBLink = @mysqli_connect($sHost, $sUser, $sPwd);
  198. }
  199. if (!$this->hDBLink)
  200. {
  201. throw new Exception("Could not connect to the DB server (host=$sHost, user=$sUser): ".mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno().')');
  202. }
  203. }
  204. protected function QueryToScalar($sSql)
  205. {
  206. $result = mysqli_query($this->hDBLink, $sSql);
  207. if (!$result)
  208. {
  209. throw new Exception("Failed to issue MySQL query '".$sSql."': ".mysqli_error($this->hDBLink).' (mysql errno: '.mysqli_errno($this->hDBLink).')');
  210. }
  211. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  212. {
  213. $res = $aRow[0];
  214. }
  215. else
  216. {
  217. mysqli_free_result($result);
  218. throw new Exception("No result for query '".$sSql."'");
  219. }
  220. mysqli_free_result($result);
  221. return $res;
  222. }
  223. }