backup.class.inc.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. // Copyright (C) 2010-2012 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. class BackupException extends Exception
  19. {
  20. }
  21. class DBBackup
  22. {
  23. // To be overriden depending on the expected usages
  24. protected function LogInfo($sMsg)
  25. {
  26. }
  27. protected function LogError($sMsg)
  28. {
  29. }
  30. protected $sDBHost;
  31. protected $iDBPort;
  32. protected $sDBUser;
  33. protected $sDBPwd;
  34. protected $sDBName;
  35. protected $sDBSubName;
  36. /**
  37. * Connects to the database to backup
  38. * By default, connects to the current MetaModel (must be loaded)
  39. *
  40. * @param sDBHost string Database host server
  41. * @param $sDBUser string User login
  42. * @param $sDBPwd string User password
  43. * @param $sDBName string Database name
  44. * @param $sDBSubName string Prefix to the tables of itop in the database
  45. */
  46. public function __construct($sDBHost = null, $sDBUser = null, $sDBPwd = null, $sDBName = null, $sDBSubName = null)
  47. {
  48. if (is_null($sDBHost))
  49. {
  50. // Defaulting to the current config
  51. $sDBHost = MetaModel::GetConfig()->GetDBHost();
  52. $sDBUser = MetaModel::GetConfig()->GetDBUser();
  53. $sDBPwd = MetaModel::GetConfig()->GetDBPwd();
  54. $sDBName = MetaModel::GetConfig()->GetDBName();
  55. $sDBSubName = MetaModel::GetConfig()->GetDBSubName();
  56. }
  57. // Compute the port (if present in the host name)
  58. $aConnectInfo = explode(':', $sDBHost);
  59. $sDBHostName = $aConnectInfo[0];
  60. if (count($aConnectInfo) > 1)
  61. {
  62. $iDBPort = $aConnectInfo[1];
  63. }
  64. else
  65. {
  66. $iDBPort = null;
  67. }
  68. $this->sDBHost = $sDBHostName;
  69. $this->iDBPort = $iDBPort;
  70. $this->sDBUser = $sDBUser;
  71. $this->sDBPwd = $sDBPwd;
  72. $this->sDBName = $sDBName;
  73. $this->sDBSubName = $sDBSubName;
  74. }
  75. protected $sMySQLBinDir = '';
  76. /**
  77. * Create a normalized backup name, depending on the current date/time and Database
  78. * @param sNameSpec string Name and path, eventually containing itop placeholders + time formatting specs
  79. */
  80. public function SetMySQLBinDir($sMySQLBinDir)
  81. {
  82. $this->sMySQLBinDir = $sMySQLBinDir;
  83. }
  84. /**
  85. * Create a normalized backup name, depending on the current date/time and Database
  86. * @param sNameSpec string Name and path, eventually containing itop placeholders + time formatting specs
  87. */
  88. public function MakeName($sNameSpec = "__DB__-%Y-%m-%d")
  89. {
  90. $sFileName = $sNameSpec;
  91. $sFileName = str_replace('__HOST__', $this->sDBHost, $sFileName);
  92. $sFileName = str_replace('__DB__', $this->sDBName, $sFileName);
  93. $sFileName = str_replace('__SUBNAME__', $this->sDBSubName, $sFileName);
  94. // Transform %Y, etc.
  95. $sFileName = strftime($sFileName);
  96. return $sFileName;
  97. }
  98. public function CreateZip($sZipFile, $sSourceConfigFile = null)
  99. {
  100. // Note: the file is created by tempnam and might not be writeable by another process (Windows/IIS)
  101. // (delete it before spawning a process)
  102. $sDataFile = tempnam(SetupUtils::GetTmpDir(), 'itop-');
  103. $this->LogInfo("Data file: '$sDataFile'");
  104. if (is_null($sSourceConfigFile))
  105. {
  106. $sSourceConfigFile = MetaModel::GetConfig()->GetLoadedFile();
  107. }
  108. $this->DoBackup($sDataFile);
  109. $this->DoZip($sDataFile, $sSourceConfigFile, $sZipFile);
  110. // Windows/IIS: the data file has been created by the spawned process...
  111. // trying to delete it will issue a warning, itself stopping the setup abruptely
  112. @unlink($sDataFile);
  113. }
  114. protected static function EscapeShellArg($sValue)
  115. {
  116. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  117. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  118. return escapeshellarg($sValue);
  119. }
  120. /**
  121. * Create a backup file
  122. */
  123. public function DoBackup($sBackupFileName)
  124. {
  125. $sHost = self::EscapeShellArg($this->sDBHost);
  126. $sUser = self::EscapeShellArg($this->sDBUser);
  127. $sPwd = self::EscapeShellArg($this->sDBPwd);
  128. $sDBName = self::EscapeShellArg($this->sDBName);
  129. // Just to check the connection to the DB (better than getting the retcode of mysqldump = 1)
  130. $oMysqli = $this->DBConnect();
  131. $sTables = '';
  132. if ($this->sDBSubName != '')
  133. {
  134. // This instance of iTop uses a prefix for the tables, so there may be other tables in the database
  135. // Let's explicitely list all the tables and views to dump
  136. $aTables = $this->EnumerateTables();
  137. if (count($aTables) == 0)
  138. {
  139. // No table has been found with the given prefix
  140. throw new BackupException("No table has been found with the given prefix");
  141. }
  142. $aEscapedTables = array();
  143. foreach($aTables as $sTable)
  144. {
  145. $aEscapedTables[] = self::EscapeShellArg($sTable);
  146. }
  147. $sTables = implode(' ', $aEscapedTables);
  148. }
  149. $this->LogInfo("Starting backup of $this->sDBHost/$this->sDBName(suffix:'$this->sDBSubName')");
  150. $sMySQLBinDir = utils::ReadParam('mysql_bindir', $this->sMySQLBinDir, true);
  151. if (empty($sMySQLBinDir))
  152. {
  153. $sMySQLDump = 'mysqldump';
  154. }
  155. else
  156. {
  157. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  158. }
  159. // Store the results in a temporary file
  160. $sTmpFileName = self::EscapeShellArg($sBackupFileName);
  161. if (is_null($this->iDBPort))
  162. {
  163. $sPortOption = '';
  164. }
  165. else
  166. {
  167. $sPortOption = '--port='.$this->iDBPort.' ';
  168. }
  169. // Delete the file created by tempnam() so that the spawned process can write into it (Windows/IIS)
  170. unlink($sBackupFileName);
  171. $sCommand = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=$sUser --password=$sPwd --result-file=$sTmpFileName $sDBName $sTables 2>&1";
  172. $sCommandDisplay = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=xxxxx --password=xxxxx --result-file=$sTmpFileName $sDBName $sTables";
  173. // Now run the command for real
  174. $this->LogInfo("Executing command: $sCommandDisplay");
  175. $aOutput = array();
  176. $iRetCode = 0;
  177. exec($sCommand, $aOutput, $iRetCode);
  178. foreach($aOutput as $sLine)
  179. {
  180. $this->LogInfo("mysqldump said: $sLine");
  181. }
  182. if ($iRetCode != 0)
  183. {
  184. $this->LogError("retcode=".$iRetCode."\n");
  185. throw new BackupException("Failed to execute mysqldump. Return code: $iRetCode. Check the log file '".realpath(APPROOT.'/log/setup.log')."' for more information.");
  186. }
  187. }
  188. /**
  189. * Helper to create a ZIP out of a data file and the configuration file
  190. */
  191. protected function DoZip($sDataFile, $sConfigFile, $sZipArchiveFile)
  192. {
  193. if (!is_file($sConfigFile))
  194. {
  195. throw new BackupException("Configuration file '$sConfigFile' does not exist or could not be read");
  196. }
  197. // Make sure the target path exists
  198. $sZipDir = dirname($sZipArchiveFile);
  199. SetupUtils::builddir($sZipDir);
  200. $oZip = new ZipArchive();
  201. $res = $oZip->open($sZipArchiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  202. if ($res === TRUE)
  203. {
  204. $oZip->addFile($sDataFile, 'itop-dump.sql');
  205. $oZip->addFile($sConfigFile, 'config-itop.php');
  206. if ($oZip->close())
  207. {
  208. $this->LogInfo("Archive: $sZipArchiveFile created");
  209. }
  210. else
  211. {
  212. $this->LogError("Failed to save zip archive: $sZipArchiveFile");
  213. throw new BackupException("Failed to save zip archive: $sZipArchiveFile");
  214. }
  215. }
  216. else
  217. {
  218. $this->LogError("Failed to create zip archive: $sZipArchiveFile.");
  219. throw new BackupException("Failed to create zip archive: $sZipArchiveFile.");
  220. }
  221. }
  222. /**
  223. * Helper to download the file directly from the browser
  224. */
  225. public function DownloadBackup($sFile)
  226. {
  227. $oP = new ajax_page('backup');
  228. $oP->SetContentType("multipart/x-zip");
  229. $oP->SetContentDisposition('inline', basename($sFile));
  230. $oP->add(file_get_contents($sFile));
  231. $oP->output();
  232. }
  233. /**
  234. * Helper to open a Database connection
  235. */
  236. protected function DBConnect()
  237. {
  238. if (is_null($this->iDBPort))
  239. {
  240. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd);
  241. }
  242. else
  243. {
  244. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd, '', $this->iDBPort);
  245. }
  246. if ($oMysqli->connect_errno)
  247. {
  248. $sHost = is_null($this->iDBPort) ? $this->sDBHost : $this->sDBHost.' on port '.$this->iDBPort;
  249. throw new BackupException("Cannot connect to the MySQL server '$this->sDBHost' (".$oMysqli->connect_errno . ") ".$oMysqli->connect_error);
  250. }
  251. if (!$oMysqli->select_db($this->sDBName))
  252. {
  253. throw new BackupException("The database '$this->sDBName' does not seem to exist");
  254. }
  255. return $oMysqli;
  256. }
  257. /**
  258. * Helper to enumerate the tables of the database
  259. */
  260. protected function EnumerateTables()
  261. {
  262. $oMysqli = $this->DBConnect();
  263. if ($this->sDBSubName != '')
  264. {
  265. $oResult = $oMysqli->query("SHOW TABLES LIKE '{$this->sDBSubName}%'");
  266. }
  267. else
  268. {
  269. $oResult = $oMysqli->query("SHOW TABLES");
  270. }
  271. if (!$oResult)
  272. {
  273. throw new BackupException("Failed to execute the SHOW TABLES query: ".$oMysqli->error);
  274. }
  275. $aTables = array();
  276. while ($aRow = $oResult->fetch_row())
  277. {
  278. $aTables[] = $aRow[0];
  279. }
  280. return $aTables;
  281. }
  282. }
  283. ?>