mutex.class.inc.php 4.8 KB

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