check-backup.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. // Copyright (C) 2014-2017 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. // Purpose: check that the backup has been successfully executed
  17. // this script is aimed at being invoked in CLI mode only
  18. // Developer's notes:
  19. // Duplicated code: sys_get_temp_dir, the computation of the target filename, etc.
  20. // Recommended usage in CRON
  21. // /usr/bin/php -q /var/www/combodo/modules/itop-backup/backup.php --backup_file=/home/backups/combodo-crm-%Y-%m-%d
  22. if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  23. require_once(__DIR__.'/../../approot.inc.php');
  24. require_once(APPROOT.'/application/utils.inc.php');
  25. require_once(APPROOT.'/core/config.class.inc.php');
  26. function ReadMandatoryParam($sParam)
  27. {
  28. $value = utils::ReadParam($sParam, null, true /* Allow CLI */, 'raw_data');
  29. if (is_null($value))
  30. {
  31. throw new Exception("Missing argument '$sParam'");
  32. }
  33. return $value;
  34. }
  35. if (!function_exists('sys_get_temp_dir'))
  36. {
  37. // Based on http://www.phpit.net/
  38. // article/creating-zip-tar-archives-dynamically-php/2/
  39. function sys_get_temp_dir()
  40. {
  41. // Try to get from environment variable
  42. if (!empty($_ENV['TMP']))
  43. {
  44. return realpath($_ENV['TMP']);
  45. }
  46. else if (!empty($_ENV['TMPDIR']))
  47. {
  48. return realpath($_ENV['TMPDIR']);
  49. }
  50. else if (!empty($_ENV['TEMP']))
  51. {
  52. return realpath($_ENV['TEMP']);
  53. }
  54. // Detect by creating a temporary file
  55. else
  56. {
  57. // Try to use system's temporary directory
  58. // as random name shouldn't exist
  59. $temp_file = tempnam(md5(uniqid(rand(), TRUE)), '');
  60. if ($temp_file)
  61. {
  62. $temp_dir = realpath(dirname($temp_file));
  63. unlink($temp_file);
  64. return $temp_dir;
  65. }
  66. else
  67. {
  68. return FALSE;
  69. }
  70. }
  71. }
  72. }
  73. function MakeArchiveFileName($iRefTime = null)
  74. {
  75. $sDefaultBackupFileName = sys_get_temp_dir().'/'."__DB__-%Y-%m-%d";
  76. $sBackupFile = utils::ReadParam('backup_file', $sDefaultBackupFileName, true, 'raw_data');
  77. $oConfig = new Config(APPCONF.'production/config-itop.php');
  78. $sBackupFile = str_replace('__HOST__', $oConfig->GetDBHost(), $sBackupFile);
  79. $sBackupFile = str_replace('__DB__', $oConfig->GetDBName(), $sBackupFile);
  80. $sBackupFile = str_replace('__SUBNAME__', $oConfig->GetDBSubName(), $sBackupFile);
  81. if (is_null($iRefTime))
  82. {
  83. $sBackupFile = strftime($sBackupFile);
  84. }
  85. else
  86. {
  87. $sBackupFile = strftime($sBackupFile, $iRefTime);
  88. }
  89. return $sBackupFile;
  90. }
  91. function RaiseAlarm($sMessage)
  92. {
  93. echo "$sMessage\n";
  94. try
  95. {
  96. $sTicketLogin = ReadMandatoryParam('check_ticket_login');
  97. $sTicketPwd = ReadMandatoryParam('check_ticket_pwd');
  98. $sTicketTitle = ReadMandatoryParam('check_ticket_title');
  99. $sTicketCustomer = ReadMandatoryParam('check_ticket_customer');
  100. $sTicketService = ReadMandatoryParam('check_ticket_service');
  101. $sTicketSubcategory = ReadMandatoryParam('check_ticket_service_subcategory');
  102. $sTicketWorkgroup = ReadMandatoryParam('check_ticket_workgroup');
  103. $sTicketImpactedServer = ReadMandatoryParam('check_ticket_impacted_server');
  104. }
  105. catch (Exception $e)
  106. {
  107. echo "The ticket could not be created: ".$e->GetMessage()."\n";
  108. return;
  109. }
  110. $sMessage = "Server: [[Server:".$sTicketImpactedServer."]]\n".$sMessage;
  111. require_once(APPROOT.'webservices/itopsoaptypes.class.inc.php');
  112. //$sItopRootDefault = 'http'.((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off')) ? 's' : '').'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER['SCRIPT_NAME']).'/../..';
  113. //$sItopRoot = utils::ReadParam('check_ticket_itop', $sItopRootDefault);
  114. $sItopRoot = ReadMandatoryParam('check_ticket_itop');
  115. $sWsdlUri = $sItopRoot.'/webservices/itop.wsdl.php';
  116. //$sWsdlUri .= '?service_category=';
  117. $aSOAPMapping = SOAPMapping::GetMapping();
  118. ini_set("soap.wsdl_cache_enabled","0");
  119. $oSoapClient = new SoapClient(
  120. $sWsdlUri,
  121. array(
  122. 'trace' => 1,
  123. 'classmap' => $aSOAPMapping, // defined in itopsoaptypes.class.inc.php
  124. )
  125. );
  126. try
  127. {
  128. $oRes = $oSoapClient->CreateIncidentTicket
  129. (
  130. $sTicketLogin, /* login */
  131. $sTicketPwd, /* password */
  132. $sTicketTitle, /* title */
  133. $sMessage, /* description */
  134. null, /* caller */
  135. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', $sTicketCustomer))), /* customer */
  136. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', $sTicketService))), /* service */
  137. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', $sTicketSubcategory))), /* service subcategory */
  138. '', /* product */
  139. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', $sTicketWorkgroup))), /* workgroup */
  140. array(
  141. new SOAPLinkCreationSpec(
  142. 'Server',
  143. array(new SOAPSearchCondition('name', $sTicketImpactedServer)),
  144. array()
  145. ),
  146. ), /* impacted cis */
  147. '1', /* impact */
  148. '1' /* urgency */
  149. );
  150. }
  151. catch(Exception $e)
  152. {
  153. echo "The ticket could not be created: SOAP Exception = '".$e->getMessage()."'\n";
  154. }
  155. //echo "<pre>\n";
  156. //print_r($oRes);
  157. //echo "</pre>\n";
  158. if ($oRes->status)
  159. {
  160. $sTicketName = $oRes->result[0]->values[1]->value;
  161. echo "Created ticket: $sTicketName\n";
  162. }
  163. else
  164. {
  165. echo "ERROR: Failed to create the ticket in target iTop ($sItopRoot)\n";
  166. foreach ($oRes->errors->messages as $oMessage)
  167. {
  168. echo $oMessage->text."\n";
  169. }
  170. }
  171. }
  172. //////////
  173. // Main
  174. try
  175. {
  176. utils::UseParamFile();
  177. }
  178. catch(Exception $e)
  179. {
  180. echo "Error: ".$e->GetMessage()."\n";
  181. exit;
  182. }
  183. $sZipArchiveFile = MakeArchiveFileName();
  184. echo date('Y-m-d H:i:s')." - Checking file: $sZipArchiveFile\n";
  185. if (file_exists($sZipArchiveFile))
  186. {
  187. if ($aStat = stat($sZipArchiveFile))
  188. {
  189. $iSize = (int) $aStat['size'];
  190. $iMIN = utils::ReadParam('check_size_min', 0);
  191. if ($iSize > $iMIN)
  192. {
  193. echo "Found the archive\n";
  194. $sOldArchiveFile = MakeArchiveFileName(time() - 86400); // yesterday's archive
  195. if (file_exists($sOldArchiveFile))
  196. {
  197. if ($aOldStat = stat($sOldArchiveFile))
  198. {
  199. echo "Comparing its size with older file: $sOldArchiveFile\n";
  200. $iOldSize = (int) $aOldStat['size'];
  201. $fVariationPercent = 100 * ($iSize - $iOldSize) / $iOldSize;
  202. $sVariation = round($fVariationPercent, 2)." percent(s)";
  203. $iREDUCTIONMAX = utils::ReadParam('check_size_reduction_max');
  204. if ($fVariationPercent < -$iREDUCTIONMAX)
  205. {
  206. RaiseAlarm("Backup file '$sZipArchiveFile' changed by $sVariation, expecting a reduction limited to $iREDUCTIONMAX percents of the original size");
  207. }
  208. elseif ($fVariationPercent < 0)
  209. {
  210. echo "Size variation: $sVariation (the maximum allowed reduction is $iREDUCTIONMAX) \n";
  211. }
  212. else
  213. {
  214. echo "The archive grew by: $sVariation\n";
  215. }
  216. }
  217. }
  218. }
  219. else
  220. {
  221. RaiseAlarm("Backup file '$sZipArchiveFile' too small (Found: $iSize, while expecting $iMIN bytes)");
  222. }
  223. }
  224. else
  225. {
  226. RaiseAlarm("Failed to stat backup file '$sZipArchiveFile'");
  227. }
  228. }
  229. else
  230. {
  231. RaiseAlarm("Missing backup file '$sZipArchiveFile'");
  232. }
  233. ?>