asynctask.class.inc.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. /**
  19. * Persistent classes (internal): user defined actions
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class ExecAsyncTask implements iBackgroundProcess
  25. {
  26. public function GetPeriodicity()
  27. {
  28. return 2; // seconds
  29. }
  30. public function Process($iTimeLimit)
  31. {
  32. $sNow = date('Y-m-d H:i:s');
  33. $sOQL = "SELECT AsyncTask WHERE ISNULL(started) AND (ISNULL(planned) OR (planned < '$sNow'))";
  34. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('created' => true) /* order by*/, array());
  35. $iProcessed = 0;
  36. while ((time() < $iTimeLimit) && ($oTask = $oSet->Fetch()))
  37. {
  38. try
  39. {
  40. $oTask->Set('started', time());
  41. $oTask->DBUpdate();
  42. }
  43. catch(Exception $e)
  44. {
  45. // Corrupted task !! (for example: "Failed to reload object")
  46. IssueLog::Error('Failed to process async task #'.$oTask->GetKey().' - reason: '.$e->getMessage().' - fatal error, deleting the task.');
  47. if ($oTask->Get('event_id') != 0)
  48. {
  49. $oEventLog = MetaModel::GetObject('Event', $oTask->Get('event_id'));
  50. $oEventLog->Set('message', 'Failed, corrupted data: '.$e->getMessage());
  51. $oEventLog->DBUpdate();
  52. }
  53. $oTask->DBDelete();
  54. continue; // end of processing for this task
  55. }
  56. try
  57. {
  58. $oTask->Process();
  59. $iProcessed++;
  60. $oTask->DBDelete();
  61. }
  62. catch(Exception $e)
  63. {
  64. $iRemaining = $oTask->Get('remaining_retries');
  65. if ($iRemaining > 0)
  66. {
  67. $aRetries = MetaModel::GetConfig()->Get('async_task_retries', array());
  68. if (is_array($aRetries) && array_key_exists(get_class($oTask), $aRetries))
  69. {
  70. $aConfig = $aRetries[get_class($oTask)];
  71. $iRetryDelay = $aConfig['retry_delay'];
  72. }
  73. else
  74. {
  75. $iRetryDelay = 600;
  76. }
  77. IssueLog::Info('Failed to process async task #'.$oTask->GetKey().' - reason: '.$e->getMessage().' - remaining retries: '.$iRemaining.' - next retry in '.$iRetryDelay.'s');
  78. $oTask->Set('remaining_retries', $iRemaining - 1);
  79. $oTask->Set('started', null);
  80. $oTask->Set('planned', time() + $iRetryDelay);
  81. $oTask->DBUpdate();
  82. }
  83. else
  84. {
  85. IssueLog::Error('Failed to process async task #'.$oTask->GetKey().' - reason: '.$e->getMessage());
  86. }
  87. }
  88. }
  89. if ($iProcessed == $oSet->Count())
  90. {
  91. return "processed $iProcessed tasks";
  92. }
  93. else
  94. {
  95. return "processed $iProcessed tasks (remaining: ".($oSet->Count() - $iProcessed).")";
  96. }
  97. }
  98. }
  99. /**
  100. * A
  101. *
  102. * @package iTopORM
  103. */
  104. abstract class AsyncTask extends DBObject
  105. {
  106. public static function Init()
  107. {
  108. $aParams = array
  109. (
  110. "category" => "core/cmdb",
  111. "key_type" => "autoincrement",
  112. "name_attcode" => array('created'),
  113. "state_attcode" => "",
  114. "reconc_keys" => array(),
  115. "db_table" => "priv_async_task",
  116. "db_key_field" => "id",
  117. "db_finalclass_field" => "realclass",
  118. "display_template" => "",
  119. );
  120. MetaModel::Init_Params($aParams);
  121. //MetaModel::Init_InheritAttributes();
  122. // MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  123. MetaModel::Init_AddAttribute(new AttributeDateTime("created", array("allowed_values"=>null, "sql"=>"created", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  124. MetaModel::Init_AddAttribute(new AttributeDateTime("started", array("allowed_values"=>null, "sql"=>"started", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  125. // planned... still not used - reserved for timer management
  126. MetaModel::Init_AddAttribute(new AttributeDateTime("planned", array("allowed_values"=>null, "sql"=>"planned", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  127. MetaModel::Init_AddAttribute(new AttributeExternalKey("event_id", array("targetclass"=>"Event", "jointype"=> "", "allowed_values"=>null, "sql"=>"event_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  128. MetaModel::Init_AddAttribute(new AttributeInteger("remaining_retries", array("allowed_values"=>null, "sql"=>"remaining_retries", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  129. // Display lists
  130. // MetaModel::Init_SetZListItems('details', array()); // Attributes to be displayed for the complete details
  131. // MetaModel::Init_SetZListItems('list', array()); // Attributes to be displayed for a list
  132. // Search criteria
  133. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  134. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  135. }
  136. protected function OnInsert()
  137. {
  138. $this->Set('created', time());
  139. $aRetries = MetaModel::GetConfig()->Get('async_task_retries', array());
  140. if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries))
  141. {
  142. $aConfig = $aRetries[get_class($this)];
  143. $iRetries = $aConfig['max_retries'];
  144. $this->Set('remaining_retries', $iRetries);
  145. }
  146. }
  147. public function Process()
  148. {
  149. $sStatus = $this->DoProcess();
  150. if ($this->Get('event_id') != 0)
  151. {
  152. $oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
  153. $oEventLog->Set('message', $sStatus);
  154. $oEventLog->DBUpdate();
  155. }
  156. }
  157. abstract public function DoProcess();
  158. }
  159. /**
  160. * An email notification
  161. *
  162. * @package iTopORM
  163. */
  164. class AsyncSendEmail extends AsyncTask
  165. {
  166. public static function Init()
  167. {
  168. $aParams = array
  169. (
  170. "category" => "core/cmdb",
  171. "key_type" => "autoincrement",
  172. "name_attcode" => "created",
  173. "state_attcode" => "",
  174. "reconc_keys" => array(),
  175. "db_table" => "priv_async_send_email",
  176. "db_key_field" => "id",
  177. "db_finalclass_field" => "",
  178. "display_template" => "",
  179. );
  180. MetaModel::Init_Params($aParams);
  181. MetaModel::Init_InheritAttributes();
  182. MetaModel::Init_AddAttribute(new AttributeInteger("version", array("allowed_values"=>null, "sql"=>"version", "default_value"=>Email::ORIGINAL_FORMAT, "is_null_allowed"=>false, "depends_on"=>array())));
  183. MetaModel::Init_AddAttribute(new AttributeText("to", array("allowed_values"=>null, "sql"=>"to", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  184. MetaModel::Init_AddAttribute(new AttributeText("subject", array("allowed_values"=>null, "sql"=>"subject", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  185. MetaModel::Init_AddAttribute(new AttributeLongText("message", array("allowed_values"=>null, "sql"=>"message", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  186. // Display lists
  187. // MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'test_recipient', 'from', 'reply_to', 'to', 'cc', 'bcc', 'subject', 'body', 'importance', 'trigger_list')); // Attributes to be displayed for the complete details
  188. // MetaModel::Init_SetZListItems('list', array('name', 'status', 'to', 'subject')); // Attributes to be displayed for a list
  189. // Search criteria
  190. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  191. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  192. }
  193. static public function AddToQueue(EMail $oEMail, $oLog)
  194. {
  195. $oNew = MetaModel::NewObject(__class__);
  196. if ($oLog)
  197. {
  198. $oNew->Set('event_id', $oLog->GetKey());
  199. }
  200. $oNew->Set('to', $oEMail->GetRecipientTO(true /* string */));
  201. $oNew->Set('subject', $oEMail->GetSubject());
  202. // $oNew->Set('version', 1);
  203. // $sMessage = serialize($oEMail);
  204. $oNew->Set('version', 2);
  205. $sMessage = $oEMail->SerializeV2();
  206. $oNew->Set('message', $sMessage);
  207. $oNew->DBInsert();
  208. }
  209. public function DoProcess()
  210. {
  211. $sMessage = $this->Get('message');
  212. $iVersion = (int) $this->Get('version');
  213. switch($iVersion)
  214. {
  215. case Email::FORMAT_V2:
  216. $oEMail = Email::UnSerializeV2($sMessage);
  217. break;
  218. case Email::ORIGINAL_FORMAT:
  219. $oEMail = unserialize($sMessage);
  220. break;
  221. default:
  222. return 'Unknown version of the serialization format: '.$iVersion;
  223. }
  224. $iRes = $oEMail->Send($aIssues, true /* force synchro !!!!! */);
  225. switch ($iRes)
  226. {
  227. case EMAIL_SEND_OK:
  228. return "Sent";
  229. case EMAIL_SEND_PENDING:
  230. return "Bug - the email should be sent in synchronous mode";
  231. case EMAIL_SEND_ERROR:
  232. return "Failed: ".implode(', ', $aIssues);
  233. }
  234. }
  235. }
  236. ?>