mutex.class.inc.php 4.3 KB

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