synchrodatasource.class.inc.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. <?php
  2. // Copyright (C) 2010 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. /**
  17. * Data Exchange - synchronization with external applications (incoming data)
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. class SynchroDataSource extends cmdbAbstractObject
  25. {
  26. public static function Init()
  27. {
  28. $aParams = array
  29. (
  30. "category" => "core/cmdb,view_in_gui",
  31. "key_type" => "autoincrement",
  32. "name_attcode" => array('name'),
  33. "state_attcode" => "",
  34. "reconc_keys" => array(),
  35. "db_table" => "priv_sync_datasource",
  36. "db_key_field" => "id",
  37. "db_finalclass_field" => "realclass",
  38. "display_template" => "",
  39. "icon" => "../images/synchro.png",
  40. );
  41. MetaModel::Init_Params($aParams);
  42. //MetaModel::Init_InheritAttributes();
  43. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  44. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  45. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('implementation,production,obsolete'), "sql"=>"status", "default_value"=>"implementation", "is_null_allowed"=>false, "depends_on"=>array())));
  46. MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=>null, "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  47. MetaModel::Init_AddAttribute(new AttributeClass("scope_class", array("class_category"=>"bizmodel", "more_values"=>"", "sql"=>"scope_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  48. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  49. //MetaModel::Init_AddAttribute(new AttributeDateTime("last_synchro_date", array("allowed_values"=>null, "sql"=>"last_synchro_date", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  50. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  51. MetaModel::Init_AddAttribute(new AttributeString("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  52. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  53. MetaModel::Init_AddAttribute(new AttributeEnum("reconciliation_policy", array("allowed_values"=>new ValueSetEnum('use_primary_key,use_attributes'), "sql"=>"reconciliation_policy", "default_value"=>"use_attributes", "is_null_allowed"=>false, "depends_on"=>array())));
  54. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_zero", array("allowed_values"=>new ValueSetEnum('create,error'), "sql"=>"action_on_zero", "default_value"=>"create", "is_null_allowed"=>false, "depends_on"=>array())));
  55. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_one", array("allowed_values"=>new ValueSetEnum('update,error'), "sql"=>"action_on_one", "default_value"=>"update", "is_null_allowed"=>false, "depends_on"=>array())));
  56. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_multiple", array("allowed_values"=>new ValueSetEnum('take_first,create,error'), "sql"=>"action_on_multiple", "default_value"=>"error", "is_null_allowed"=>false, "depends_on"=>array())));
  57. MetaModel::Init_AddAttribute(new AttributeEnum("delete_policy", array("allowed_values"=>new ValueSetEnum('ignore,delete,update,update_then_delete'), "sql"=>"delete_policy", "default_value"=>"ignore", "is_null_allowed"=>false, "depends_on"=>array())));
  58. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_update", array("allowed_values"=>null, "sql"=>"delete_policy_update", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  59. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  60. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_retention", array("allowed_values"=>null, "sql"=>"delete_policy_retention", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  61. MetaModel::Init_AddAttribute(new AttributeLinkedSet("attribute_list", array("linked_class"=>"SynchroAttribute", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array())));
  62. MetaModel::Init_AddAttribute(new AttributeLinkedSet("status_list", array("linked_class"=>"SynchroLog", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array())));
  63. // Display lists
  64. MetaModel::Init_SetZListItems('details', array('name', 'description', 'scope_class', 'scope_restriction', 'status', 'user_id', 'full_load_periodicity', 'reconciliation_policy', 'action_on_zero', 'action_on_one', 'action_on_multiple', 'delete_policy', 'delete_policy_update', 'delete_policy_retention' /*'attribute_list'*/, 'status_list')); // Attributes to be displayed for the complete details
  65. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  66. // Search criteria
  67. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  68. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  69. }
  70. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  71. {
  72. if (!$this->IsNew())
  73. {
  74. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  75. $oAttributeSet = $this->Get('attribute_list');
  76. $aAttributes = array();
  77. while($oAttribute = $oAttributeSet->Fetch())
  78. {
  79. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  80. }
  81. $aAttribs = array(
  82. 'attcode' => array('label'=>'Attribute', 'description' => 'Field of the object'),
  83. 'reconciliation' => array('label'=>'Reconciliation ?', 'description' => 'Used for searching'),
  84. 'update' => array('label'=>'Update ?', 'description' => 'Used to update the object'),
  85. 'update_policy' => array('label'=>'Update Policy', 'description' => 'Behavior of the updated field'),
  86. );
  87. $aValues = array();
  88. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  89. {
  90. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  91. {
  92. if (isset($aAttributes[$sAttCode]))
  93. {
  94. $oAttribute = $aAttributes[$sAttCode];
  95. }
  96. else
  97. {
  98. $oAttribute = new SynchroAttribute();
  99. $oAttribute->Set('sync_source_id', $this->GetKey());
  100. $oAttribute->Set('attcode', $sAttCode);
  101. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  102. $oAttribute->Set('update', 1);
  103. $oAttribute->Set('update_policy', 'master_locked');
  104. }
  105. if (!$bEditMode)
  106. {
  107. // Read-only mode
  108. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  109. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  110. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  111. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  112. }
  113. else
  114. {
  115. // Read-only mode
  116. $sAttCode = $oAttribute->Get('attcode');
  117. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  118. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  119. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  120. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  121. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  122. $oAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  123. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  124. }
  125. $aValues[] = $aRow;
  126. }
  127. }
  128. $oPage->Table($aAttribs, $aValues);
  129. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  130. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  131. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  132. if ($oSetSynchroLog->Count() > 0)
  133. {
  134. $oLastLog = $oSetSynchroLog->Fetch();
  135. $sStartDate = $oLastLog->Get('start_date');
  136. $oLastLog->Get('stats_nb_replica_seen');
  137. if ($oLastLog->Get('status') == 'running')
  138. {
  139. // Still running !
  140. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  141. }
  142. else
  143. {
  144. $sEndDate = $oLastLog->Get('end_date');
  145. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  146. }
  147. $iDeleted = $oLastLog->Get('stats_nb_obj_deleted');
  148. $iObsoleted = $oLastLog->Get('stats_nb_obj_obsoleted');
  149. $iDisappearedErrors = $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors');
  150. $iUpdated = $oLastLog->Get('stats_nb_obj_updated');
  151. $iUpdatedErrors = $oLastLog->Get('stats_nb_obj_updated_errors');
  152. $iReconciled = $oLastLog->Get('stats_nb_replica_reconciled');
  153. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  154. $iCreated = $oLastLog->Get('stats_nb_obj_created');
  155. $iCreatedErrors = $oLastLog->Get('stats_nb_obj_created_errors');
  156. $iDisappeared = $iDisappearedErrors + $iObsoleted + $iDeleted;
  157. $iNewErrors = $iCreatedErrors + $iReconciledErrors;
  158. $iNew = $iCreated + $iCreatedErrors + $iReconciled + $iReconciledErrors;
  159. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  160. $iUnchanged = $iExisting - $iUpdated - $iUpdatedErrors;
  161. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  162. $fOpacity = 0.3;
  163. $sNewOpacity = ($iNew ==0) ? "opacity:$fOpacity;" : "";
  164. $sExistingOpacity = ($iExisting ==0) ? "opacity:$fOpacity;" : "";
  165. $sDisappearedOpacity = ($iDisappeared ==0) ? "opacity:$fOpacity;" : "";
  166. $sIgnoredOpacity = ($iIgnored ==0) ? "opacity:$fOpacity;" : "";
  167. $sCreateOpacity = ($iCreated ==0) ? "opacity:$fOpacity;" : "";
  168. $sReconciledOpacity = ($iReconciled ==0) ? "opacity:$fOpacity;" : "";
  169. $sNewErrorsOpacity = ($iNewErrors ==0) ? "opacity:$fOpacity;" : "";
  170. $sUnchangedOpacity = ($iUnchanged ==0) ? "opacity:$fOpacity;" : "";
  171. $sUpdatedOpacity = ($iUpdated ==0) ? "opacity:$fOpacity;" : "";
  172. $sUpdatedErrorsOpacity = ($iUpdatedErrors ==0) ? "opacity:$fOpacity;" : "";
  173. $sDeletedOpacity = ($iDeleted ==0) ? "opacity:$fOpacity;" : "";
  174. $sObsoletedOpacity = ($iObsoleted ==0) ? "opacity:$fOpacity;" : "";
  175. $sDisappearedErrorsOpacity = ($iDisappearedErrors ==0) ? "opacity:$fOpacity;" : "";
  176. $oPage->add(
  177. <<<EOF
  178. <style>
  179. .synoptics, .synoptics tr td { background: transparent; padding:10px; font-size:1em; vertical-align:middle; color:#fff; text-align:center;}
  180. .synoptics tr td.arrow { color:#333; border-top: 1px dashed #333; width:100px; }
  181. </style>
  182. <table class="synoptics">
  183. <tr>
  184. <td style="background-color:#999;$sIgnoredOpacity">Ignored ($iIgnored)</td><td colspan="2">&nbsp;</td>
  185. </tr>
  186. <tr>
  187. <td style="background-color:#630;$sDisappearedOpacity" rowspan="3">Disappeared ($iDisappeared)</td><td rowspan="3" class="arrow">=&gt;</td><td style="background-color:#300;$sDeletedOpacity">Deleted ($iDeleted)</td>
  188. </tr>
  189. <tr>
  190. <td style="background-color:#630;$sObsoletedOpacity">Obsoleted ($iObsoleted)</td>
  191. </tr>
  192. <tr>
  193. <td style="background-color:#C00;$sDisappearedErrorsOpacity">Errors ($iDisappearedErrors)</td>
  194. </tr>
  195. <tr>
  196. <td style="background-color:#093;$sExistingOpacity" rowspan="3">Existing ($iExisting)</td><td rowspan="3" class="arrow">=&gt;</td><td style="background-color:#393;$sUnchangedOpacity">Unchanged ($iUnchanged)</td>
  197. </tr>
  198. <tr>
  199. <td style="background-color:#3C3;$sUpdatedOpacity">Updated ($iUpdated)</td>
  200. </tr>
  201. <tr>
  202. <td style="background-color:#C00;$sUpdatedErrorsOpacity">Errors ($iUpdatedErrors)</td>
  203. </tr>
  204. <tr>
  205. <td style="background-color:#039;$sNewOpacity"rowspan="3">New ($iNew)</td><td rowspan="3" class="arrow">=&gt;</td><td style="background-color:#C00;$sNewErrorsOpacity">Errors ($iNewErrors)</td>
  206. </tr>
  207. <tr>
  208. <td style="background-color:#33F;$sReconciledOpacity">Reconciled ($iReconciled)</td>
  209. </tr>
  210. <tr>
  211. <td style="background-color:#339;$sCreateOpacity">Created ($iCreated)</td>
  212. </tr>
  213. </table>
  214. EOF
  215. );
  216. }
  217. else
  218. {
  219. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  220. }
  221. }
  222. parent::DisplayBareRelations($oPage, $bEditMode);
  223. }
  224. public function GetAttributeFlags($sAttCode)
  225. {
  226. if (($sAttCode == 'scope_class') && (!$this->IsNew()))
  227. {
  228. return OPT_ATT_READONLY;
  229. }
  230. return parent::GetAttributeFlags($sAttCode);
  231. }
  232. public function UpdateObject($sFormPrefix = '')
  233. {
  234. parent::UpdateObject($sFormPrefix);
  235. // And now read the other post parameters...
  236. $oAttributeSet = $this->Get('attribute_list');
  237. $aAttributes = array();
  238. while($oAttribute = $oAttributeSet->Fetch())
  239. {
  240. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  241. }
  242. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  243. $aUpdate = utils::ReadPostedParam('update', array());
  244. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  245. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  246. // through all the writable attributes
  247. foreach($aUpdatePolicy as $sAttCode => $sValue)
  248. {
  249. if(!isset($aAttributes[$sAttCode]))
  250. {
  251. $oAttribute = new SynchroAttribute();
  252. $oAttribute->Set('sync_source_id', $this->GetKey());
  253. $oAttribute->Set('attcode', $sAttCode);
  254. }
  255. else
  256. {
  257. $oAttribute = $aAttributes[$sAttCode];
  258. }
  259. $bReconcile = 0;
  260. if (isset($aReconcile[$sAttCode]))
  261. {
  262. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  263. }
  264. $bUpdate = 0 ; // Default / initial value
  265. if (isset($aUpdate[$sAttCode]))
  266. {
  267. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  268. }
  269. $oAttribute->Set('reconcile', $bReconcile);
  270. $oAttribute->Set('update', $bUpdate);
  271. $oAttribute->Set('update_policy', $sValue);
  272. $oAttributeSet->AddObject($oAttribute);
  273. }
  274. $this->Set('attribute_list', $oAttributeSet);
  275. }
  276. public function GetTargetClass()
  277. {
  278. return $this->Get('scope_class');
  279. }
  280. public function GetDataTable()
  281. {
  282. $sName = strtolower($this->GetTargetClass());
  283. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  284. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  285. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  286. return $sTable;
  287. }
  288. /**
  289. * When inserting a new datasource object, also create the SynchroAttribute objects
  290. * for each field of the target class
  291. */
  292. protected function OnInsert()
  293. {
  294. // Create all the SynchroAttribute records
  295. $oAttributeSet = $this->Get('attribute_list');
  296. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  297. {
  298. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  299. {
  300. $oAttribute = new SynchroAttribute();
  301. $oAttribute->Set('sync_source_id', $this->GetKey());
  302. $oAttribute->Set('attcode', $sAttCode);
  303. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  304. $oAttribute->Set('update', 1);
  305. $oAttribute->Set('update_policy', 'master_locked');
  306. $oAttributeSet->AddObject($oAttribute);
  307. }
  308. }
  309. $this->Set('attribute_list', $oAttributeSet);
  310. }
  311. /**
  312. * When the new datasource has been created, let's create the synchro_data table
  313. * that will hold the data records and the correspoding triggers which will maintain
  314. * both tables in sync
  315. */
  316. protected function AfterInsert()
  317. {
  318. parent::AfterInsert();
  319. $sTable = $this->GetDataTable();
  320. $aColumns = $this->GetSQLColumns();
  321. $aFieldDefs = array();
  322. // Allow '0', otherwise mysql will render an error when the id is not given
  323. // (the trigger is expected to set the value, but it is not executed soon enough)
  324. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  325. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  326. foreach($aColumns as $sColumn => $ColSpec)
  327. {
  328. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  329. }
  330. $aFieldDefs[] = "INDEX (id)";
  331. $aFieldDefs[] = "INDEX (primary_key)";
  332. $sFieldDefs = implode(', ', $aFieldDefs);
  333. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  334. CMDBSource::Query($sCreateTable);
  335. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  336. $sTriggerInsert .= " FOR EACH ROW";
  337. $sTriggerInsert .= " BEGIN";
  338. $sTriggerInsert .= " INSERT INTO priv_sync_replica (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  339. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  340. $sTriggerInsert .= " END;";
  341. CMDBSource::Query($sTriggerInsert);
  342. $aModified = array();
  343. foreach($aColumns as $sColumn => $ColSpec)
  344. {
  345. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  346. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  347. }
  348. $sIsModified = '('.implode(') OR (', $aModified).')';
  349. // Update the replica
  350. //
  351. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  352. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  353. // otherwise, the status is left as is
  354. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  355. $sTriggerUpdate .= " FOR EACH ROW";
  356. $sTriggerUpdate .= " BEGIN";
  357. $sTriggerUpdate .= " IF @itopuser is null THEN";
  358. $sTriggerUpdate .= " UPDATE priv_sync_replica SET status_last_seen = NOW(), `status` = IF(`status` = 'obsolete', IF(`dest_id` IS NULL, 'new', 'modified'), IF(`status` IN ('synchronized') AND ($sIsModified), 'modified', `status`)) WHERE sync_source_id = {$this->GetKey()} AND id = OLD.id;";
  359. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  360. $sTriggerUpdate .= " END IF;";
  361. $sTriggerUpdate .= " END;";
  362. CMDBSource::Query($sTriggerUpdate);
  363. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  364. $sTriggerInsert .= " FOR EACH ROW";
  365. $sTriggerInsert .= " BEGIN";
  366. $sTriggerInsert .= " DELETE FROM priv_sync_replica WHERE id = OLD.id;";
  367. $sTriggerInsert .= " END;";
  368. CMDBSource::Query($sTriggerInsert);
  369. }
  370. protected function AfterDelete()
  371. {
  372. parent::AfterDelete();
  373. $sTable = $this->GetDataTable();
  374. $sDropTable = "DROP TABLE `$sTable`";
  375. CMDBSource::Query($sDropTable);
  376. // TO DO - check that triggers get dropped with the table
  377. }
  378. /**
  379. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  380. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  381. * is used to determine which records are obsolete.
  382. * @param Hash $aTraces Debugs/Trace information, one or more entries per replica
  383. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  384. * @return void
  385. */
  386. public function Synchronize(&$aTraces, $oLastFullLoadStartDate = null)
  387. {
  388. // Create a change used for logging all the modifications/creations happening during the synchro
  389. $oMyChange = MetaModel::NewObject("CMDBChange");
  390. $oMyChange->Set("date", time());
  391. $sUserString = CMDBChange::GetCurrentUserName();
  392. $oMyChange->Set("userinfo", $sUserString);
  393. $iChangeId = $oMyChange->DBInsert();
  394. // Start logging this execution (stats + protection against reentrance)
  395. //
  396. $oStatLog = new SynchroLog();
  397. $oStatLog->Set('sync_source_id', $this->GetKey());
  398. $oStatLog->Set('start_date', time());
  399. $oStatLog->Set('status', 'running');
  400. $oStatLog->Set('stats_nb_replica_seen', 0);
  401. $oStatLog->Set('stats_nb_replica_total', 0);
  402. $oStatLog->Set('stats_nb_obj_deleted', 0);
  403. $oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  404. $oStatLog->Set('stats_nb_obj_obsoleted', 0);
  405. $oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  406. $oStatLog->Set('stats_nb_obj_created', 0);
  407. $oStatLog->Set('stats_nb_obj_created_errors', 0);
  408. $oStatLog->Set('stats_nb_obj_updated', 0);
  409. $oStatLog->Set('stats_nb_obj_updated_errors', 0);
  410. $oStatLog->Set('stats_nb_replica_reconciled', 0);
  411. $oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  412. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  413. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->GetKey()));
  414. $oStatLog->Set('stats_nb_replica_total', $oSetTotal->Count());
  415. $oStatLog->DBInsertTracked($oMyChange);
  416. try
  417. {
  418. $this->DoSynchronize($oLastFullLoadStartDate, $oMyChange, $oStatLog, $aTraces);
  419. $oStatLog->Set('end_date', time());
  420. $oStatLog->Set('status', 'completed');
  421. $oStatLog->DBUpdateTracked($oMyChange);
  422. }
  423. catch (Exception $e)
  424. {
  425. $oStatLog->Set('end_date', time());
  426. $oStatLog->Set('status', 'completed');
  427. $oStatLog->DBUpdateTracked($oMyChange);
  428. }
  429. return $oStatLog;
  430. }
  431. protected function DoSynchronize($oLastFullLoadStartDate, $oMyChange, &$oStatLog, &$aTraces)
  432. {
  433. // Get all the replicas that were not seen in the last import and mark them as obsolete
  434. if ($oLastFullLoadStartDate == null)
  435. {
  436. // No previous import known, use the full_load_periodicity value... and the current date
  437. $oLastFullLoadStartDate = new DateTime(); // Now
  438. // TO DO: how do we support localization here ??
  439. $sLoadPeriodicity = trim($this->Get('full_load_periodicity'));
  440. if (strlen($sLoadPeriodicity) > 0)
  441. {
  442. $sInterval = '-'.$sLoadPeriodicity;
  443. // Note: the PHP doc states that Modify return FALSE in case of error
  444. // but, this is actually NOT the case
  445. // Therefore, I do compare before and after, considering that the
  446. // format is incorrect when the datetime remains unchanged
  447. $sBefore = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  448. $oLastFullLoadStartDate->Modify($sInterval);
  449. $sAfter = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  450. if ($sBefore == $sAfter)
  451. {
  452. throw new CoreException("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  453. }
  454. }
  455. }
  456. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  457. $aTraces[] = "Limit Date: $sLimitDate";
  458. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  459. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  460. while($oReplica = $oSetToObsolete->Fetch())
  461. {
  462. // TO DO: take the appropriate action based on the 'delete_policy' field
  463. $sUpdateOnObsolete = $this->Get('delete_policy');
  464. if ( ($sUpdateOnObsolete == 'update') || ($sUpdateOnObsolete == 'update_then_delete') )
  465. {
  466. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be updated";
  467. $aToUpdate = array();
  468. $aToUpdate = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  469. foreach($aToUpdate as $sUpdateSpec)
  470. {
  471. $aUpdateSpec = explode(':', $sUpdateSpec);
  472. if (count($aUpdateSpec) == 2)
  473. {
  474. $sAttCode = $aUpdateSpec[0];
  475. $sValue = $aUpdateSpec[1];
  476. $aToUpdate[$sAttCode] = $sValue;
  477. }
  478. }
  479. $oReplica->UpdateDestObject($aToUpdate, $oMyChange, $oStatLog, $aTraces, 'stats_nb_obj_obsoleted');
  480. }
  481. $oReplica->Set('status', 'obsolete');
  482. $oReplica->DBUpdateTracked($oMyChange);
  483. }
  484. //Count "seen" objects
  485. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  486. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  487. $oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  488. // Get all the replicas that are 'new' or modified
  489. //
  490. // Get the list of SQL columns
  491. $sClass = $this->GetTargetClass();
  492. $aAttCodes = array();
  493. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND update = 1";
  494. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  495. while ($oSyncAtt = $oSetAtt->Fetch())
  496. {
  497. $aAttCodes[] = $oSyncAtt->Get('attcode');
  498. }
  499. $aColumns = $this->GetSQLColumns($aAttCodes);
  500. $aExtDataFields = array_keys($aColumns);
  501. $aExtDataFields[] = 'primary_key';
  502. $aExtDataSpec = array(
  503. 'table' => $this->GetDataTable(),
  504. 'join_key' => 'id',
  505. 'fields' => $aExtDataFields
  506. );
  507. // Get the list of reconciliation keys
  508. $aReconciliationKeys = array();
  509. if ($this->Get('reconciliation_policy') == 'use_attributes')
  510. {
  511. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND reconcile = 1";
  512. $oAttSet = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  513. while ($oSyncAtt = $oAttSet->Fetch())
  514. {
  515. $aReconciliationKeys[] = $oSyncAtt->Get('attcode');
  516. }
  517. }
  518. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  519. {
  520. $aReconciliationKeys[] = "primary_key";
  521. }
  522. $aTraces[] = "Reconciliation on: {".implode(', ', $aReconciliationKeys)."}";
  523. $aAttributes = array();
  524. foreach($aAttCodes as $sAttCode)
  525. {
  526. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  527. if ($oAttDef->IsWritable() && $oAttDef->IsScalar())
  528. {
  529. $aAttributes[] = $sAttCode;
  530. }
  531. }
  532. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  533. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  534. while($oReplica = $oSetToSync->Fetch())
  535. {
  536. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange, $oStatLog, $aTraces);
  537. }
  538. // Get all the replicas that are to be deleted
  539. //
  540. $oDeletionDate = $oLastFullLoadStartDate;
  541. $sDeleteRetention = trim($this->Get('delete_policy_retention'));
  542. if (strlen($sDeleteRetention) > 0)
  543. {
  544. $sInterval = '-'.$sDeleteRetention;
  545. // Note: the PHP doc states that Modify return FALSE in case of error
  546. // but, this is actually NOT the case
  547. // Therefore, I do compare before and after, considering that the
  548. // format is incorrect when the datetime remains unchanged
  549. $sBefore = $oDeletionDate->Format('Y-m-d H:i:s');
  550. $oDeletionDate->Modify($sInterval);
  551. $sAfter = $oDeletionDate->Format('Y-m-d H:i:s');
  552. if ($sBefore == $sAfter)
  553. {
  554. throw new CoreException("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  555. }
  556. }
  557. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  558. $aTraces[] = "sDeletionDate: $sDeletionDate";
  559. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  560. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  561. while($oReplica = $oSetToDelete->Fetch())
  562. {
  563. $sUpdateOnObsolete = $this->Get('delete_policy');
  564. if ( ($sUpdateOnObsolete == 'delete') || ($sUpdateOnObsolete == 'update_then_delete') )
  565. {
  566. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be DELETED";
  567. $oReplica->DeleteDestObject($oMyChange, $oStatLog, $aTraces);
  568. }
  569. $aTraces[] = "Replica id:".$oReplica->GetKey()." (dest_id:".$oReplica->Get('dest_id').") to be deleted";
  570. $oReplica->DBDeleteTracked($oMyChange);
  571. }
  572. }
  573. /**
  574. * Get the list of SQL columns corresponding to a particular list of attribute codes
  575. * Defaults to the whole list of columns for the current class
  576. */
  577. public function GetSQLColumns($aAttributeCodes = null)
  578. {
  579. $aColumns = array();
  580. $sClass = $this->GetTargetClass();
  581. if (is_null($aAttributeCodes))
  582. {
  583. $aAttributeCodes = array();
  584. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  585. {
  586. if ($sAttCode == 'finalclass') continue;
  587. $aAttributeCodes[] = $sAttCode;
  588. }
  589. }
  590. foreach($aAttributeCodes as $sAttCode)
  591. {
  592. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  593. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  594. {
  595. $aColumns[$sField] = $sDBFieldType;
  596. }
  597. }
  598. return $aColumns;
  599. }
  600. public function IsRunning()
  601. {
  602. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  603. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  604. if ($oSet->Count() < 1)
  605. {
  606. $bRet = false;
  607. }
  608. else
  609. {
  610. $bRet = true;
  611. }
  612. return $bRet;
  613. }
  614. public function GetLatestLog()
  615. {
  616. $oLog = null;
  617. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  618. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  619. if ($oSet->Count() >= 1)
  620. {
  621. $oLog = $oSet->Fetch();
  622. }
  623. return $oLog;
  624. }
  625. // TO DO: remove if still unused
  626. /**
  627. * Retrieve from the log, the date of the last completed import
  628. * @return DateTime
  629. */
  630. public function GetLastCompletedImportDate()
  631. {
  632. $date = null;
  633. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  634. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  635. if ($oSet->Count() >= 1)
  636. {
  637. $oLog = $oSet->Fetch();
  638. $date = $oLog->Get('end_date');
  639. }
  640. else
  641. {
  642. // TO DO: remove trace
  643. echo "<p>No completed log found</p>\n";
  644. }
  645. return $date;
  646. }
  647. }
  648. class SynchroAttribute extends cmdbAbstractObject
  649. {
  650. public static function Init()
  651. {
  652. $aParams = array
  653. (
  654. "category" => "core/cmdb,view_in_gui",
  655. "key_type" => "autoincrement",
  656. "name_attcode" => "",
  657. "state_attcode" => "",
  658. "reconc_keys" => array(),
  659. "db_table" => "priv_sync_att",
  660. "db_key_field" => "id",
  661. "db_finalclass_field" => "",
  662. "display_template" => "",
  663. );
  664. MetaModel::Init_Params($aParams);
  665. MetaModel::Init_InheritAttributes();
  666. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  667. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  668. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  669. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  670. MetaModel::Init_AddAttribute(new AttributeEnum("update_policy", array("allowed_values"=>new ValueSetEnum('master_locked,master_unlocked,write_once'), "sql"=>"update_policy", "default_value"=>"master_locked", "is_null_allowed"=>false, "depends_on"=>array())));
  671. // Display lists
  672. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  673. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  674. // Search criteria
  675. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  676. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  677. }
  678. }
  679. class SynchroAttExtKey extends SynchroAttribute
  680. {
  681. public static function Init()
  682. {
  683. $aParams = array
  684. (
  685. "category" => "core/cmdb,view_in_gui",
  686. "key_type" => "autoincrement",
  687. "name_attcode" => "",
  688. "state_attcode" => "",
  689. "reconc_keys" => array(),
  690. "db_table" => "priv_sync_att_extkey",
  691. "db_key_field" => "id",
  692. "db_finalclass_field" => "",
  693. "display_template" => "",
  694. );
  695. MetaModel::Init_Params($aParams);
  696. MetaModel::Init_InheritAttributes();
  697. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  698. // Display lists
  699. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  700. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  701. // Search criteria
  702. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  703. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  704. }
  705. }
  706. class SynchroAttLinkSet extends SynchroAttribute
  707. {
  708. public static function Init()
  709. {
  710. $aParams = array
  711. (
  712. "category" => "core/cmdb,view_in_gui",
  713. "key_type" => "autoincrement",
  714. "name_attcode" => "",
  715. "state_attcode" => "",
  716. "reconc_keys" => array(),
  717. "db_table" => "priv_sync_att_linkset",
  718. "db_key_field" => "id",
  719. "db_finalclass_field" => "",
  720. "display_template" => "",
  721. );
  722. MetaModel::Init_Params($aParams);
  723. MetaModel::Init_InheritAttributes();
  724. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  725. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  726. // Display lists
  727. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'row_separator', 'attribute_separator')); // Attributes to be displayed for the complete details
  728. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  729. // Search criteria
  730. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  731. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  732. }
  733. }
  734. //class SynchroLog extends Event
  735. class SynchroLog extends cmdbAbstractObject
  736. {
  737. public static function Init()
  738. {
  739. $aParams = array
  740. (
  741. "category" => "core/cmdb,view_in_gui",
  742. "key_type" => "autoincrement",
  743. "name_attcode" => "",
  744. "state_attcode" => "",
  745. "reconc_keys" => array(),
  746. "db_table" => "priv_sync_log",
  747. "db_key_field" => "id",
  748. "db_finalclass_field" => "",
  749. "display_template" => "",
  750. );
  751. MetaModel::Init_Params($aParams);
  752. MetaModel::Init_InheritAttributes();
  753. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  754. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  755. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  756. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  757. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('running,completed'), "sql"=>"status", "default_value"=>"running", "is_null_allowed"=>false, "depends_on"=>array())));
  758. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_seen", array("allowed_values"=>null, "sql"=>"stats_nb_replica_seen", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  759. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_total", array("allowed_values"=>null, "sql"=>"stats_nb_replica_total", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  760. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_deleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  761. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted_errors", array("allowed_values"=>null, "sql"=>"stats_deleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  762. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  763. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  764. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  765. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  766. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  767. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  768. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  769. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled_errors", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  770. // Display lists
  771. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_total', 'stats_nb_replica_seen', 'stats_nb_obj_created', 'stats_nb_replica_reconciled', 'stats_nb_obj_updated', 'stats_nb_obj_obsoleted', 'stats_nb_obj_deleted',
  772. 'stats_nb_obj_created_errors', 'stats_nb_replica_reconciled_errors', 'stats_nb_obj_updated_errors', 'stats_nb_obj_obsoleted_errors', 'stats_nb_obj_deleted_errors')); // Attributes to be displayed for the complete details
  773. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  774. // Search criteria
  775. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  776. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  777. }
  778. /**
  779. * Increments a statistics counter
  780. */
  781. function Inc($sCode)
  782. {
  783. $this->Set($sCode, 1+$this->Get($sCode));
  784. }
  785. }
  786. class SynchroReplica extends DBObject
  787. {
  788. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  789. public static function Init()
  790. {
  791. $aParams = array
  792. (
  793. "category" => "core/cmdb,view_in_gui",
  794. "key_type" => "autoincrement",
  795. "name_attcode" => "",
  796. "state_attcode" => "",
  797. "reconc_keys" => array(),
  798. "db_table" => "priv_sync_replica",
  799. "db_key_field" => "id",
  800. "db_finalclass_field" => "",
  801. "display_template" => "",
  802. );
  803. MetaModel::Init_Params($aParams);
  804. MetaModel::Init_InheritAttributes();
  805. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  806. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  807. MetaModel::Init_AddAttribute(new AttributeClass("dest_class", array("class_category"=>"bizmodel", "more_values"=>"", "sql"=>"dest_class", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  808. MetaModel::Init_AddAttribute(new AttributeDateTime("status_last_seen", array("allowed_values"=>null, "sql"=>"status_last_seen", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  809. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('new,synchronized,modified,orphan,obsolete'), "sql"=>"status", "default_value"=>"new", "is_null_allowed"=>false, "depends_on"=>array())));
  810. MetaModel::Init_AddAttribute(new AttributeBoolean("status_dest_creator", array("allowed_values"=>null, "sql"=>"status_dest_creator", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  811. MetaModel::Init_AddAttribute(new AttributeString("status_last_error", array("allowed_values"=>null, "sql"=>"status_last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  812. MetaModel::Init_AddAttribute(new AttributeDateTime("info_creation_date", array("allowed_values"=>null, "sql"=>"info_creation_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  813. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_modified", array("allowed_values"=>null, "sql"=>"info_last_modified", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  814. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_synchro", array("allowed_values"=>null, "sql"=>"info_last_synchro", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  815. // Display lists
  816. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'info_creation_date', 'info_last_modified', 'info_last_synchro')); // Attributes to be displayed for the complete details
  817. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error')); // Attributes to be displayed for a list
  818. // Search criteria
  819. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error')); // Criteria of the std search form
  820. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  821. }
  822. public function DBInsert()
  823. {
  824. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  825. }
  826. // Overload the deletion -> the replica has been created by the mean of a trigger,
  827. // it will be deleted by the mean of a trigger too
  828. public function DBDelete()
  829. {
  830. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  831. $sTable = $oDataSource->GetDataTable();
  832. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  833. CMDBSource::Query($sSQL);
  834. $this->m_bIsInDB = false;
  835. $this->m_iKey = null;
  836. }
  837. public function SetLastError($sMessage, $oException = null)
  838. {
  839. if ($oException)
  840. {
  841. $sText = $sMessage.$oException->getMessage();
  842. }
  843. else
  844. {
  845. $sText = $sMessage;
  846. }
  847. if (strlen($sText) > 255)
  848. {
  849. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  850. }
  851. $this->Set('status_last_error', $sText);
  852. }
  853. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  854. {
  855. switch($this->Get('status'))
  856. {
  857. case 'new':
  858. // If needed, construct the query used for the reconciliation
  859. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  860. {
  861. foreach($aReconciliationKeys as $sFilterCode)
  862. {
  863. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  864. }
  865. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  866. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  867. }
  868. // Get the criterias for the search
  869. $aFilterValues = array();
  870. foreach($aReconciliationKeys as $sFilterCode)
  871. {
  872. $value = $this->GetValueFromExtData($sFilterCode);
  873. if (!is_null($value))
  874. {
  875. $aFilterValues[$sFilterCode] = $value;
  876. }
  877. else
  878. {
  879. // Reconciliation could not be performed - log and EXIT
  880. $aTraces[] = "Could not reconcile on null value: ".$sFilterCode;
  881. $this->SetLastError('Could not reconcile on null value: '.$sFilterCode);
  882. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  883. return;
  884. }
  885. }
  886. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  887. $iCount = $oDestSet->Count();
  888. $aConditions = array();
  889. foreach($aFilterValues as $sCode => $sValue)
  890. {
  891. $aConditions[] = $sCode.'='.$sValue;
  892. }
  893. $sConditionDesc = implode(' AND ', $aConditions);
  894. // How many objects match the reconciliation criterias
  895. switch($iCount)
  896. {
  897. case 0:
  898. $aTraces[] = "Nothing found on: $sConditionDesc";
  899. if ($oDataSource->Get('action_on_zero') == 'create')
  900. {
  901. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  902. }
  903. else // assumed to be 'error'
  904. {
  905. $aTraces[] = "Failed to reconcile (no match)";
  906. $this->SetLastError('Could not find a match for reconciliation');
  907. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  908. }
  909. break;
  910. case 1:
  911. $aTraces[] = "Found 1 object on: $sConditionDesc";
  912. if ($oDataSource->Get('action_on_one') == 'update')
  913. {
  914. $oDestObj = $oDestSet->Fetch();
  915. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_replica_reconciled');
  916. $this->Set('dest_id', $oDestObj->GetKey());
  917. $this->Set('status_dest_creator', false);
  918. $this->Set('dest_class', get_class($oDestObj));
  919. $oStatLog->Inc('stats_nb_replica_reconciled');
  920. }
  921. else
  922. {
  923. // assumed to be 'error'
  924. $aTraces[] = "Failed to reconcile (1 match)";
  925. $this->SetLastError('Found a match while expecting several');
  926. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  927. }
  928. break;
  929. default:
  930. $aTraces[] = "Found $iCount objects on: $sConditionDesc";
  931. if ($oDataSource->Get('action_on_multiple') == 'error')
  932. {
  933. $aTraces[] = "Failed to reconcile (N>1 matches)";
  934. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  935. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  936. }
  937. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  938. {
  939. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  940. }
  941. else
  942. {
  943. // assumed to be 'take_first'
  944. $oDestObj = $oDestSet->Fetch();
  945. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_replica_reconciled');
  946. $this->Set('dest_id', $oDestObj->GetKey());
  947. $this->Set('status_dest_creator', false);
  948. $this->Set('dest_class', get_class($oDestObj));
  949. }
  950. }
  951. break;
  952. case 'modified':
  953. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  954. if ($oDestObj == null)
  955. {
  956. $this->Set('status', 'orphan'); // The destination object has been deleted !
  957. $this->SetLastError('Destination object deleted unexpectedly');
  958. $oStatLog->Inc('stats_nb_obj_updated_errors');
  959. }
  960. else
  961. {
  962. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj_updated');
  963. }
  964. break;
  965. default: // Do nothing in all other cases
  966. }
  967. $this->DBUpdateTracked($oChange);
  968. }
  969. /**
  970. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  971. */
  972. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, &$aTraces, $sStatsCode)
  973. {
  974. $aValueTrace = array();
  975. foreach($aAttributes as $sAttCode)
  976. {
  977. $value = $this->GetValueFromExtData($sAttCode);
  978. if (!is_null($value))
  979. {
  980. $oDestObj->Set($sAttCode, $value);
  981. $aValueTrace[] = "$sAttCode: $value";
  982. }
  983. }
  984. try
  985. {
  986. $oDestObj->DBUpdateTracked($oChange);
  987. $aTraces[] = "Updated object ".$oDestObj->GetHyperLink()." (".implode(', ', $aValueTrace).")";
  988. $oStatLog->Inc($sStatsCode);
  989. $this->Set('status_last_error', '');
  990. $this->Set('status', 'synchronized');
  991. }
  992. catch(Exception $e)
  993. {
  994. $aTraces[] = "Failed to update destination object: {$e->getMessage()}";
  995. $this->SetLastError('Unable to update destination object: ', $e);
  996. $oStatLog->Inc($sStatsCode.'_errors');
  997. }
  998. }
  999. /**
  1000. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1001. */
  1002. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  1003. {
  1004. $oDestObj = MetaModel::NewObject($sClass);
  1005. try
  1006. {
  1007. $aValueTrace = array();
  1008. foreach($aAttributes as $sAttCode)
  1009. {
  1010. $value = $this->GetValueFromExtData($sAttCode);
  1011. if (!is_null($value))
  1012. {
  1013. $oDestObj->Set($sAttCode, $value);
  1014. $aValueTrace[] = "$sAttCode: $value";
  1015. }
  1016. }
  1017. $iNew = $oDestObj->DBInsertTracked($oChange);
  1018. $aTraces[] = "Created $sClass::$iNew (".implode(', ', $aValueTrace).")";
  1019. $this->Set('dest_id', $oDestObj->GetKey());
  1020. $this->Set('dest_class', get_class($oDestObj));
  1021. $this->Set('status_dest_creator', true);
  1022. $this->Set('status_last_error', '');
  1023. $this->Set('status', 'synchronized');
  1024. $oStatLog->Inc('stats_nb_obj_created');
  1025. }
  1026. catch(Exception $e)
  1027. {
  1028. $aTraces[] = "Failed to create $sClass ({$e->getMessage()})";
  1029. $this->SetLastError('Unable to create destination object: ', $e);
  1030. $oStatLog->Inc('stats_nb_obj_created_errors');
  1031. }
  1032. }
  1033. /**
  1034. * Update the destination object with given values
  1035. */
  1036. public function UpdateDestObject($aValues, $oChange, &$oStatLog, &$aTraces, $sStatCode)
  1037. {
  1038. try
  1039. {
  1040. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1041. foreach($aValues as $sAttCode => $value)
  1042. {
  1043. $oDestObj->Set($sAttCode, $value);
  1044. }
  1045. $oDestObj->DBUpdateTracked($oChange);
  1046. $aTraces[] = "Replica id:".$this->GetKey()." (dest_id:".$this->Get('dest_id').") marked as obsolete";
  1047. $oStatLog->Inc($sStatCode);
  1048. }
  1049. catch(Exception $e)
  1050. {
  1051. $this->SetLastError('Unable to update the destination object: ', $e);
  1052. $oStatLog->Inc($sStatCode.'_errors');
  1053. }
  1054. }
  1055. /**
  1056. * Delete the destination object
  1057. */
  1058. public function DeleteDestObject($oChange, &$oStatLog, &$aTraces)
  1059. {
  1060. if($this->Get('status_dest_creator'))
  1061. {
  1062. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1063. try
  1064. {
  1065. $oDestObj->DBDeleteTracked($oChange);
  1066. $oStatLog->Inc('stats_nb_obj_deleted');
  1067. }
  1068. catch(Exception $e)
  1069. {
  1070. $this->SetLastError('Unable to delete the destination object: ', $e);
  1071. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1077. */
  1078. protected function GetValueFromExtData($sColumnName)
  1079. {
  1080. $aData = $this->GetExtendedData();
  1081. return $aData[$sColumnName];
  1082. }
  1083. }
  1084. // TO DO: finalize.... admins only ? which options ? troubleshoot WebPageMenuNode::__construct(.... sEnableClass...) ?
  1085. //if (UserRights::IsAdministrator())
  1086. {
  1087. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */);
  1088. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1089. new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  1090. }
  1091. ?>