backup.class.inc.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. $aContents = array();
  105. $aContents[] = array(
  106. 'source' => $sDataFile,
  107. 'dest' => 'itop-dump.sql',
  108. );
  109. if (is_null($sSourceConfigFile))
  110. {
  111. $sSourceConfigFile = MetaModel::GetConfig()->GetLoadedFile();
  112. }
  113. if (!empty($sSourceConfigFile))
  114. {
  115. $aContents[] = array(
  116. 'source' => $sSourceConfigFile,
  117. 'dest' => 'config-itop.php',
  118. );
  119. }
  120. $this->DoBackup($sDataFile);
  121. $sDeltaFile = APPROOT.'data/'.utils::GetCurrentEnvironment().'.delta.xml';
  122. if (file_exists($sDeltaFile))
  123. {
  124. $aContents[] = array(
  125. 'source' => $sDeltaFile,
  126. 'dest' => 'delta.xml',
  127. );
  128. }
  129. $this->DoZip($aContents, $sZipFile);
  130. // Windows/IIS: the data file has been created by the spawned process...
  131. // trying to delete it will issue a warning, itself stopping the setup abruptely
  132. @unlink($sDataFile);
  133. }
  134. protected static function EscapeShellArg($sValue)
  135. {
  136. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  137. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  138. return escapeshellarg($sValue);
  139. }
  140. /**
  141. * Create a backup file
  142. */
  143. public function DoBackup($sBackupFileName)
  144. {
  145. $sHost = self::EscapeShellArg($this->sDBHost);
  146. $sUser = self::EscapeShellArg($this->sDBUser);
  147. $sPwd = self::EscapeShellArg($this->sDBPwd);
  148. $sDBName = self::EscapeShellArg($this->sDBName);
  149. // Just to check the connection to the DB (better than getting the retcode of mysqldump = 1)
  150. $oMysqli = $this->DBConnect();
  151. $sTables = '';
  152. if ($this->sDBSubName != '')
  153. {
  154. // This instance of iTop uses a prefix for the tables, so there may be other tables in the database
  155. // Let's explicitely list all the tables and views to dump
  156. $aTables = $this->EnumerateTables();
  157. if (count($aTables) == 0)
  158. {
  159. // No table has been found with the given prefix
  160. throw new BackupException("No table has been found with the given prefix");
  161. }
  162. $aEscapedTables = array();
  163. foreach($aTables as $sTable)
  164. {
  165. $aEscapedTables[] = self::EscapeShellArg($sTable);
  166. }
  167. $sTables = implode(' ', $aEscapedTables);
  168. }
  169. $this->LogInfo("Starting backup of $this->sDBHost/$this->sDBName(suffix:'$this->sDBSubName')");
  170. $sMySQLBinDir = utils::ReadParam('mysql_bindir', $this->sMySQLBinDir, true);
  171. if (empty($sMySQLBinDir))
  172. {
  173. $sMySQLDump = 'mysqldump';
  174. }
  175. else
  176. {
  177. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  178. }
  179. // Store the results in a temporary file
  180. $sTmpFileName = self::EscapeShellArg($sBackupFileName);
  181. if (is_null($this->iDBPort))
  182. {
  183. $sPortOption = '';
  184. }
  185. else
  186. {
  187. $sPortOption = '--port='.$this->iDBPort.' ';
  188. }
  189. // Delete the file created by tempnam() so that the spawned process can write into it (Windows/IIS)
  190. unlink($sBackupFileName);
  191. $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";
  192. $sCommandDisplay = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=xxxxx --password=xxxxx --result-file=$sTmpFileName $sDBName $sTables";
  193. // Now run the command for real
  194. $this->LogInfo("Executing command: $sCommandDisplay");
  195. $aOutput = array();
  196. $iRetCode = 0;
  197. exec($sCommand, $aOutput, $iRetCode);
  198. foreach($aOutput as $sLine)
  199. {
  200. $this->LogInfo("mysqldump said: $sLine");
  201. }
  202. if ($iRetCode != 0)
  203. {
  204. $this->LogError("Failed to execute: $sCommandDisplay. The command returned:$iRetCode");
  205. foreach($aOutput as $sLine)
  206. {
  207. $this->LogError("mysqldump said: $sLine");
  208. }
  209. if (count($aOutput) == 1)
  210. {
  211. $sMoreInfo = trim($aOutput[0]);
  212. }
  213. else
  214. {
  215. $sMoreInfo = "Check the log files '".realpath(APPROOT.'/log/setup.log or error.log')."' for more information.";
  216. }
  217. throw new BackupException("Failed to execute mysqldump: ".$sMoreInfo);
  218. }
  219. }
  220. /**
  221. * Helper to create a ZIP out of a data file and the configuration file
  222. */
  223. protected function DoZip($aFiles, $sZipArchiveFile)
  224. {
  225. foreach ($aFiles as $aFile)
  226. {
  227. $sFile = $aFile['source'];
  228. if (!is_file($sFile))
  229. {
  230. throw new BackupException("File '$sFile' does not exist or could not be read");
  231. }
  232. }
  233. // Make sure the target path exists
  234. $sZipDir = dirname($sZipArchiveFile);
  235. SetupUtils::builddir($sZipDir);
  236. $oZip = new ZipArchive();
  237. $res = $oZip->open($sZipArchiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  238. if ($res === TRUE)
  239. {
  240. foreach ($aFiles as $aFile)
  241. {
  242. $oZip->addFile($aFile['source'], $aFile['dest']);
  243. }
  244. if ($oZip->close())
  245. {
  246. $this->LogInfo("Archive: $sZipArchiveFile created");
  247. }
  248. else
  249. {
  250. $this->LogError("Failed to save zip archive: $sZipArchiveFile");
  251. throw new BackupException("Failed to save zip archive: $sZipArchiveFile");
  252. }
  253. }
  254. else
  255. {
  256. $this->LogError("Failed to create zip archive: $sZipArchiveFile.");
  257. throw new BackupException("Failed to create zip archive: $sZipArchiveFile.");
  258. }
  259. }
  260. /**
  261. * Helper to download the file directly from the browser
  262. */
  263. public function DownloadBackup($sFile)
  264. {
  265. $oP = new ajax_page('backup');
  266. $oP->SetContentType("multipart/x-zip");
  267. $oP->SetContentDisposition('inline', basename($sFile));
  268. $oP->add(file_get_contents($sFile));
  269. $oP->output();
  270. }
  271. /**
  272. * Helper to open a Database connection
  273. */
  274. protected function DBConnect()
  275. {
  276. if (is_null($this->iDBPort))
  277. {
  278. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd);
  279. }
  280. else
  281. {
  282. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd, '', $this->iDBPort);
  283. }
  284. if ($oMysqli->connect_errno)
  285. {
  286. $sHost = is_null($this->iDBPort) ? $this->sDBHost : $this->sDBHost.' on port '.$this->iDBPort;
  287. throw new BackupException("Cannot connect to the MySQL server '$this->sDBHost' (".$oMysqli->connect_errno . ") ".$oMysqli->connect_error);
  288. }
  289. if (!$oMysqli->select_db($this->sDBName))
  290. {
  291. throw new BackupException("The database '$this->sDBName' does not seem to exist");
  292. }
  293. return $oMysqli;
  294. }
  295. /**
  296. * Helper to enumerate the tables of the database
  297. */
  298. protected function EnumerateTables()
  299. {
  300. $oMysqli = $this->DBConnect();
  301. if ($this->sDBSubName != '')
  302. {
  303. $oResult = $oMysqli->query("SHOW TABLES LIKE '{$this->sDBSubName}%'");
  304. }
  305. else
  306. {
  307. $oResult = $oMysqli->query("SHOW TABLES");
  308. }
  309. if (!$oResult)
  310. {
  311. throw new BackupException("Failed to execute the SHOW TABLES query: ".$oMysqli->error);
  312. }
  313. $aTables = array();
  314. while ($aRow = $oResult->fetch_row())
  315. {
  316. $aTables[] = $aRow[0];
  317. }
  318. return $aTables;
  319. }
  320. }
  321. ?>