mutex.class.inc.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. // Copyright (C) 2013 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 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: the name is server-wide!!!
  38. $this->sName = 'itop.'.$sName;
  39. $this->bLocked = false; // Not yet locked
  40. if (!array_key_exists($this->sName, self::$aAcquiredLocks))
  41. {
  42. self::$aAcquiredLocks[$this->sName] = 0;
  43. }
  44. // It is a MUST to create a dedicated session each time a lock is required, because
  45. // using GET_LOCK anytime on the same session will RELEASE the current and unique session lock (known issue)
  46. $oConfig = utils::GetConfig();
  47. $sDBHost = is_null($sDBHost) ? $oConfig->GetDBHost() : $sDBHost;
  48. $sDBUser = is_null($sDBUser) ? $oConfig->GetDBUser() : $sDBUser;
  49. $sDBPwd = is_null($sDBPwd) ? $oConfig->GetDBPwd() : $sDBPwd;
  50. $this->InitMySQLSession($sDBHost, $sDBUser, $sDBPwd);
  51. }
  52. public function __destruct()
  53. {
  54. if ($this->bLocked)
  55. {
  56. $this->Unlock();
  57. }
  58. mysqli_close($this->hDBLink);
  59. }
  60. /**
  61. * Acquire the mutex
  62. */
  63. public function Lock()
  64. {
  65. if ($this->bLocked)
  66. {
  67. // Lock already acquired
  68. return;
  69. }
  70. if (self::$aAcquiredLocks[$this->sName] == 0)
  71. {
  72. do
  73. {
  74. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 3600)");
  75. if (is_null($res))
  76. {
  77. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  78. }
  79. // $res === '1' means I hold the lock
  80. // $res === '0' means it timed out
  81. }
  82. while ($res !== '1');
  83. }
  84. $this->bLocked = true;
  85. self::$aAcquiredLocks[$this->sName]++;
  86. }
  87. /**
  88. * Attempt to acquire the mutex
  89. * @returns bool True if the mutex is acquired, false if already locked elsewhere
  90. */
  91. public function TryLock()
  92. {
  93. if ($this->bLocked)
  94. {
  95. return true; // Already acquired
  96. }
  97. if (self::$aAcquiredLocks[$this->sName] > 0)
  98. {
  99. self::$aAcquiredLocks[$this->sName]++;
  100. $this->bLocked = true;
  101. return true;
  102. }
  103. $res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 0)");
  104. if (is_null($res))
  105. {
  106. throw new Exception("Failed to acquire the lock '".$this->sName."'");
  107. }
  108. // $res === '1' means I hold the lock
  109. // $res === '0' means it timed out
  110. if ($res === '1')
  111. {
  112. $this->bLocked = true;
  113. self::$aAcquiredLocks[$this->sName]++;
  114. }
  115. return ($res === '1');
  116. }
  117. /**
  118. * Release the mutex
  119. */
  120. public function Unlock()
  121. {
  122. if (!$this->bLocked)
  123. {
  124. // ??? the lock is not acquired, exit
  125. return;
  126. }
  127. if (self::$aAcquiredLocks[$this->sName] == 0)
  128. {
  129. return; // Safety net
  130. }
  131. if (self::$aAcquiredLocks[$this->sName] == 1)
  132. {
  133. $res = $this->QueryToScalar("SELECT RELEASE_LOCK('".$this->sName."')");
  134. }
  135. $this->bLocked = false;
  136. self::$aAcquiredLocks[$this->sName]--;
  137. }
  138. public function InitMySQLSession($sHost, $sUser, $sPwd)
  139. {
  140. $aConnectInfo = explode(':', $sHost);
  141. if (count($aConnectInfo) > 1)
  142. {
  143. // Override the default port
  144. $sServer = $aConnectInfo[0];
  145. $iPort = $aConnectInfo[1];
  146. $this->hDBLink = @mysqli_connect($sServer, $sUser, $sPwd, '', $iPort);
  147. }
  148. else
  149. {
  150. $this->hDBLink = @mysqli_connect($sHost, $sUser, $sPwd);
  151. }
  152. if (!$this->hDBLink)
  153. {
  154. throw new Exception("Could not connect to the DB server (host=$sHost, user=$sUser): ".mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno().')');
  155. }
  156. }
  157. protected function QueryToScalar($sSql)
  158. {
  159. $result = mysqli_query($this->hDBLink, $sSql);
  160. if (!$result)
  161. {
  162. throw new Exception("Failed to issue MySQL query '".$sSql."': ".mysqli_error($this->hDBLink).' (mysql errno: '.mysqli_errno($this->hDBLink).')');
  163. }
  164. if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
  165. {
  166. $res = $aRow[0];
  167. }
  168. else
  169. {
  170. mysqli_free_result($result);
  171. throw new Exception("No result for query '".$sSql."'");
  172. }
  173. mysqli_free_result($result);
  174. return $res;
  175. }
  176. }