backup.class.inc.php 9.9 KB

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