mutex.class.inc.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. // Copyright (C) 2013-2016 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-2016 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 = utils::GetConfig(); // Will return an empty config when called during the setup
  39. $sDBName = $oConfig->GetDBName();
  40. $sDBSubname = $oConfig->GetDBSubname();
  41. $this->sName = 'itop.'.$sName;
  42. if (substr($sName, -strlen($sDBName.$sDBSubname)) != $sDBName.$sDBSubname)
  43. {
  44. // If the name supplied already ends with the expected suffix
  45. // don't add it twice, since the setup may try to detect an already
  46. // running cron job by its mutex, without knowing if the config already exists or not
  47. $this->sName .= $sDBName.$sDBSubname;
  48. }
  49. $this->bLocked = false; // Not yet locked
  50. if (!array_key_exists($this->sName, self::$aAcquiredLocks))
  51. {
  52. self::$aAcquiredLocks[$this->sName] = 0;
  53. }
  54. // It is a MUST to create a dedicated session each time a lock is required, because
  55. // using GET_LOCK anytime on the same session will RELEASE the current and unique session lock (known issue)
  56. $sDBHost = is_null($sDBHost) ? $oConfig->GetDBHost() : $sDBHost;
  57. $sDBUser = is_null($sDBUser) ? $oConfig->GetDBUser() : $sDBUser;
  58. $sDBPwd = is_null($sDBPwd) ? $oConfig->GetDBPwd() : $sDBPwd;
  59. $this->InitMySQLSession($sDBHost, $sDBUser, $sDBPwd);
  60. }
  61. public function __destruct()
  62. {
  63. if ($this->bLocked)
  64. {
  65. $this->Unlock();
  66. }
  67. mysqli_close($this->hDBLink);
  68. }
  69. /**
  70. * Acquire the mutex
  71. */
  72. public function Lock()
  73. {
  74. if ($this->bLocked)
  75. {
  76. // Lock already acquired
  77. return;
  78. }
  79. if (self::$aAcquiredLocks[$this->sName] == 0)
  80. {
  81. do
  82. {
  83. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 3600)");
  84. if (is_null($res))
  85. {
  86. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  87. }
  88. // $res === '1' means I hold the lock
  89. // $res === '0' means it timed out
  90. }
  91. while ($res !== '1');
  92. }
  93. $this->bLocked = true;
  94. self::$aAcquiredLocks[$this->sName]++;
  95. }
  96. /**
  97. * Attempt to acquire the mutex
  98. * @returns bool True if the mutex is acquired, false if already locked elsewhere
  99. */
  100. public function TryLock()
  101. {
  102. if ($this->bLocked)
  103. {
  104. return true; // Already acquired
  105. }
  106. if (self::$aAcquiredLocks[$this->sName] > 0)
  107. {
  108. self::$aAcquiredLocks[$this->sName]++;
  109. $this->bLocked = true;
  110. return true;
  111. }
  112. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 0)");
  113. if (is_null($res))
  114. {
  115. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  116. }
  117. // $res === '1' means I hold the lock
  118. // $res === '0' means it timed out
  119. if ($res === '1')
  120. {
  121. $this->bLocked = true;
  122. self::$aAcquiredLocks[$this->sName]++;
  123. }
  124. if (($res !== '1') && ($res !== '0'))
  125. {
  126. $sMsg = 'GET_LOCK('.$this->sName.', 0) returned: '.var_export($res, true).'. Expected values are: 0, 1 or null';
  127. IssueLog::Error($sMsg);
  128. throw new Exception($sMsg);
  129. }
  130. return ($res !== '0');
  131. }
  132. /**
  133. * Check if the mutex is locked WITHOUT TRYING TO ACQUIRE IT
  134. * @returns bool True if the mutex is in use, false otherwise
  135. */
  136. public function IsLocked()
  137. {
  138. if ($this->bLocked)
  139. {
  140. return true; // Already acquired
  141. }
  142. if (self::$aAcquiredLocks[$this->sName] > 0)
  143. {
  144. return true;
  145. }
  146. $res = $this->QueryToScalar("SELECT IS_FREE_LOCK('".$this->sName."')"); // IS_FREE_LOCK detects some error cases that IS_USED_LOCK do not detect
  147. if (is_null($res))
  148. {
  149. $sMsg = "MySQL Error, IS_FREE_LOCK('".$this->sName."') returned null. Error (".mysqli_errno($this->hDBLink).") = '".mysqli_error($this->hDBLink)."'";
  150. IssueLog::Error($sMsg);
  151. throw new Exception($sMsg);
  152. }
  153. else if ($res == '1')
  154. {
  155. // Lock is free
  156. return false;
  157. }
  158. return true;
  159. }
  160. /**
  161. * Release the mutex
  162. */
  163. public function Unlock()
  164. {
  165. if (!$this->bLocked)
  166. {
  167. // ??? the lock is not acquired, exit
  168. return;
  169. }
  170. if (self::$aAcquiredLocks[$this->sName] == 0)
  171. {
  172. return; // Safety net
  173. }
  174. if (self::$aAcquiredLocks[$this->sName] == 1)
  175. {
  176. $res = $this->QueryToScalar("SELECT RELEASE_LOCK('".$this->sName."')");
  177. }
  178. $this->bLocked = false;
  179. self::$aAcquiredLocks[$this->sName]--;
  180. }
  181. public function InitMySQLSession($sHost, $sUser, $sPwd)
  182. {
  183. $aConnectInfo = explode(':', $sHost);
  184. if (count($aConnectInfo) > 1)
  185. {
  186. // Override the default port
  187. $sServer = $aConnectInfo[0];
  188. $iPort = $aConnectInfo[1];
  189. $this->hDBLink = @mysqli_connect($sServer, $sUser, $sPwd, '', $iPort);
  190. }
  191. else
  192. {
  193. $this->hDBLink = @mysqli_connect($sHost, $sUser, $sPwd);
  194. }
  195. if (!$this->hDBLink)
  196. {
  197. throw new Exception("Could not connect to the DB server (host=$sHost, user=$sUser): ".mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno().')');
  198. }
  199. }
  200. protected function QueryToScalar($sSql)
  201. {
  202. $result = mysqli_query($this->hDBLink, $sSql);
  203. if (!$result)
  204. {
  205. throw new Exception("Failed to issue MySQL query '".$sSql."': ".mysqli_error($this->hDBLink).' (mysql errno: '.mysqli_errno($this->hDBLink).')');
  206. }
  207. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  208. {
  209. $res = $aRow[0];
  210. }
  211. else
  212. {
  213. mysqli_free_result($result);
  214. throw new Exception("No result for query '".$sSql."'");
  215. }
  216. mysqli_free_result($result);
  217. return $res;
  218. }
  219. }