Compare commits

..

12 Commits

Author SHA1 Message Date
Eric Espie
ae4ed11729 N°9617 - Send EVENT on data export for traceability - After Review 2026-07-17 10:57:06 +02:00
Eric Espie
42ade7e1be N°9617 - Send EVENT on data export for traceability 2026-07-17 10:57:06 +02:00
Eric Espie
4ce0cd7173 N°9617 - Send events on data export for traceability 2026-07-17 10:57:06 +02:00
Eric Espie
eeb1312127 N°9617 - Send events on data export for traceability
# Conflicts:
#	core/restservices.class.inc.php
2026-07-17 10:57:06 +02:00
Molkobain
13fad9efc1 N°9625 - Add Session::UnsetAll() method to ensure that even the "welcome" session value is correctly resetted (#970)
* N°9625 - Add Session::UnsetAll() method to ensure that even the "welcome" session value is correctly resetted

* N°9625 - Add unit tests

* N°9625 - Improve robustness

* N°9625 - Code review updates

* N°9625 - Fix logoff page to ensure all authentication plugins are called before emptying the session
2026-07-17 10:28:58 +02:00
Lenaick
9fbc53cf00 N°9679 - Forced uninstallation is not logged when done by extensions management (#956) 2026-07-17 09:42:58 +02:00
lenaick.moreira
918f110dc9 Merge branch 'support/3.3-beta1' into develop 2026-07-15 14:46:48 +02:00
lenaick.moreira
8e0246601a Fix unit tests failed 2026-07-15 14:33:55 +02:00
lenaick.moreira
bd9cc9c15e Fix unit tests failed 2026-07-15 14:21:17 +02:00
Eric Espie
60ce21509f Merge branch 'support/3.3-beta1' into develop 2026-07-15 12:10:56 +02:00
Eric Espie
e6cdcd0a5a N°9808 - Wrong dependency when module is in production-modules 2026-07-15 12:09:55 +02:00
Lenaick
2ab3081926 N°9692 - Uninstall / Disable install when extension has module with missing dependencies (#967)
* N°9692 - Uninstall / Disable install when extension has module with missing dependencies

* N°9692 - Uninstall / Disable install when extension has module with missing dependencies

* N°9692 - Uninstall / Disable install when extension has module with missing dependencies

* N°9692 - Refactor dependency handling for extensions to use HasDependencyIssue method

* Rename cannot-be-installed to dependency_issue

* Changes following the review
2026-07-15 09:20:25 +02:00
35 changed files with 569 additions and 521 deletions

View File

@@ -5368,6 +5368,7 @@ JS
/**
* @param array $aChanges
* @param bool $bIsNew
* @param string|null $sStimulusBeingApplied
*
* @return void
* @throws \ArchivedObjectException
@@ -5381,6 +5382,20 @@ JS
$this->FireEvent(EVENT_DB_AFTER_WRITE, ['is_new' => $bIsNew, 'changes' => $aChanges, 'stimulus_applied' => $sStimulusBeingApplied, 'cmdb_change' => self::GetCurrentChange()]);
}
//////////////
/// READ
///
/**
* @return void
* @throws \CoreException
* @since 3.3.0
*/
final public function FireEventReadDetails(string $sExportType): void
{
$this->FireEvent(EVENT_DATA_EXPORT, ['export_type' => $sExportType]);
}
//////////////
/// DELETE
///

View File

@@ -519,6 +519,31 @@ Call $this->AddInitialAttributeFlags($sAttCode, $iFlags) for all the initial att
</event_datum>
</event_data>
</event>
<event id="EVENT_DATA_EXPORT" _delta="define">
<name>Object details read from outside iTop</name>
<description><![CDATA[An object details has been read during an export]]></description>
<sources>
<source id="cmdbAbstractObject">cmdbAbstractObject</source>
</sources>
<event_data>
<event_datum id="object">
<description>The object unarchived</description>
<type>DBObject</type>
</event_datum>
<event_datum id="attributes">
<description>Attribute codes exposed (empty means potentially all attributes)</description>
<type>array</type>
</event_datum>
<event_datum id="export_type">
<description>Type of export</description>
<type>string</type>
</event_datum>
<event_datum id="debug_info">
<description>Debug string</description>
<type>string</type>
</event_datum>
</event_data>
</event>
<event id="EVENT_DOWNLOAD_DOCUMENT" _delta="define">
<name>Document downloaded</name>
<description><![CDATA[A document has been downloaded from the GUI]]></description>

View File

@@ -25,11 +25,11 @@
*/
use Combodo\iTop\Application\Branding;
use Combodo\iTop\Application\Helper\Session;
use Combodo\iTop\Application\WebPage\ErrorPage;
use Combodo\iTop\Application\WebPage\NiceWebPage;
use Combodo\iTop\Service\Events\EventData;
use Combodo\iTop\Service\Events\EventService;
use Combodo\iTop\Service\Session\Session;
/**
* Web page used for displaying the login form
@@ -369,16 +369,7 @@ class LoginWebPage extends NiceWebPage
public static function ResetSession()
{
// Unset all of the session variables.
Session::Unset('auth_user');
Session::Unset('login_state');
Session::Unset('can_logoff');
Session::Unset('archive_mode');
Session::Unset('impersonate_user');
Session::Unset('PluginProperties');
Session::Unset('UrlMakerClass');
Session::Unset('itop_env');
Session::Unset('obj_messages');
Session::Unset('profile_list');
Session::UnsetAll();
UserRights::_ResetSessionCache();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!

View File

@@ -3218,24 +3218,4 @@ TXT
return (int)$sLimit;
}
}
/**
* Count the number of cron.php processes currently running
*
* @return int process count
* @throws \Exception
*/
public static function CountCronRunning(): int
{
$iMaxCronProcess = max(MetaModel::GetConfig()->Get('cron.max_processes'), 1);
$iCount = 0;
for ($i = 0; $i < $iMaxCronProcess; $i++) {
$oMutex = new iTopMutex("cron#$i");
if ($oMutex->IsLocked()) {
$iCount++;
}
}
return $iCount;
}
}

View File

@@ -578,11 +578,19 @@ class Config
'cron_max_execution_time' => [
'type' => 'integer',
'description' => 'Duration (seconds) of the cron.php script : if exceeded the script will exit even if there are remaining tasks to process. Must be shorter than php max_execution_time setting (note than when using CLI, this is set to 0 by default which means unlimited). If cron.php is ran via web, it must be shorter than the web server response timeout.',
'default' => 590,
'value' => 590,
'default' => 600,
'value' => 600,
'source_of_value' => '',
'show_in_conf_sample' => true,
],
'cron_task_max_execution_time' => [
'type' => 'integer',
'description' => 'Background tasks will use this value (integer) multiplicated by its periodicity (in seconds) as max duration per cron execution. 0 is unlimited time',
'default' => 0,
'value' => 0,
'source_of_value' => '',
'show_in_conf_sample' => false,
],
'cron_sleep' => [
'type' => 'integer',
'description' => 'Duration (seconds) before cron.php checks again if something must be done',
@@ -591,14 +599,6 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => false,
],
'cron.max_processes' => [
'type' => 'integer',
'description' => 'Maximum number of cron processes to run',
'default' => 10,
'value' => 10,
'source_of_value' => '',
'show_in_conf_sample' => true,
],
'async_task_retries' => [
'type' => 'array',
'description' => 'Automatic retries of asynchronous tasks in case of failure (per class)',

View File

@@ -334,12 +334,14 @@ EOF
while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
$aData = [];
foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$aExportedObjects = [];
foreach ($this->aStatusInfo['fields'] as $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$sField = '';
$oObj = $aRow[$sAlias];
$aExportedObjects[] = $oObj;
if ($oObj != null) {
switch ($sAttCode) {
case 'id':
@@ -366,7 +368,13 @@ EOF
}
$sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
$iCount++;
$aExportedObjects = array_unique($aExportedObjects);
foreach ($aExportedObjects as $oExportedObject) {
$oExportedObject->FireEventReadDetails(get_class($this));
}
}
// Restore original date & time formats
AttributeDateTime::SetFormat($oPrevDateTimeFormat);
AttributeDate::SetFormat($oPrevDateFormat);

View File

@@ -6247,7 +6247,9 @@ abstract class DBObject implements iDisplay
}
/**
* @param array $aChanges
* @param bool $bIsNew
* @param string|null $sStimulusBeingApplied
*
* @return void
* @since 3.1.0
@@ -6256,6 +6258,18 @@ abstract class DBObject implements iDisplay
{
}
//////////////
/// READ
///
/**
* @return void
* @since 3.3.0
*/
public function FireEventReadDetails(string $sExportType): void
{
}
//////////////
/// DELETE
///

View File

@@ -288,11 +288,13 @@ EOF
while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
$aData = [];
$aExportedObjects = [];
foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$oObj = $aRow[$sAlias];
$aExportedObjects[] = $oObj;
$sField = '';
if ($oObj) {
$sField = $this->GetValue($oObj, $sAttCode);
@@ -301,6 +303,11 @@ EOF
}
fwrite($hFile, json_encode($aData)."\n");
$iCount++;
$aExportedObjects = array_unique($aExportedObjects);
foreach ($aExportedObjects as $oExportedObject) {
$oExportedObject->FireEventReadDetails(get_class($this));
}
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;

View File

@@ -139,6 +139,7 @@ class HTMLBulkExport extends TabularBulkExport
} else {
$sData .= "<tr>";
}
$aExportedObjects = [];
foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
@@ -147,12 +148,18 @@ class HTMLBulkExport extends TabularBulkExport
$sField = '';
if ($oObj) {
$sField = $this->GetValue($oObj, $sAttCode);
$aExportedObjects[] = $oObj;
}
$sValue = ($sField === '') ? '&nbsp;' : $sField;
$sData .= "<td>$sValue</td>";
}
$sData .= "</tr>";
$iCount++;
$aExportedObjects = array_unique($aExportedObjects);
foreach ($aExportedObjects as $oExportedObject) {
$oExportedObject->FireEventReadDetails(get_class($this));
}
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;

View File

@@ -563,7 +563,7 @@ class InlineImageGC implements iBackgroundProcess
*/
public function GetPeriodicity()
{
return 600;
return 1;
}
/**

View File

@@ -625,6 +625,7 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
}
while ($oObject = $oObjectSet->Fetch()) {
$oObject->FireEventReadDetails(get_class($this));
$oResult->AddObject(0, '', $oObject, $aShowFields, RestUtils::HasRequestedExtendedOutput($sShowFields));
}
$oResult->message = "Found: ".$oObjectSet->Count();
@@ -699,6 +700,7 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
if ($oElement instanceof RelationObjectNode) {
$oObject = $oElement->GetProperty('object');
if ($oObject) {
$oObject->FireEventReadDetails(get_class($this));
if ($bEnableRedundancy && $sDirection == 'down') {
// Add only the "reached" objects
if ($oElement->GetProperty('is_reached')) {

View File

@@ -233,7 +233,6 @@ EOF
public function GetNextChunk(&$aStatus)
{
$sRetCode = 'run';
$iPercentage = 0;
$oSet = new DBObjectSet($this->oSearch);
$oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
@@ -254,7 +253,8 @@ EOF
set_time_limit(intval($iLoopTimeLimit));
$sData .= "<tr>";
foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$aExportedObjects = [];
foreach ($this->aStatusInfo['fields'] as $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
@@ -265,7 +265,7 @@ EOF
$sData .= "<td x:str></td>";
continue;
}
$aExportedObjects[] = $oObj;
switch ($sAttCode) {
case 'id':
$sField = $oObj->GetKey();
@@ -322,6 +322,11 @@ EOF
}
$sData .= "</tr>";
$iCount++;
$aExportedObjects = array_unique($aExportedObjects);
foreach ($aExportedObjects as $oExportedObject) {
$oExportedObject->FireEventReadDetails(get_class($this));
}
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;

View File

@@ -135,6 +135,11 @@ abstract class Trigger extends cmdbAbstractObject
if ($oAction->IsActive()) {
$oKPI = new ExecutionKPI();
$aContextArgs['action->object()'] = $oAction;
if (array_key_exists('this->object()', $aContextArgs)) {
/** @var \DBObject $oObject */
$oObject = $aContextArgs['this->object()'];
$oObject->FireEventReadDetails(get_class($oAction));
}
$oAction->DoExecute($this, $aContextArgs);
$oKPI->ComputeStatsForExtension($oAction, 'DoExecute');
}

View File

@@ -144,6 +144,7 @@ class XMLBulkExport extends BulkExport
if (count($aAuthorizedClasses) > 1) {
$sData .= "<Row>\n";
}
$aExportedObjects = [];
foreach ($aAuthorizedClasses as $sAlias => $sClassName) {
$oObj = $aObjects[$sAlias];
if (is_null($oObj)) {
@@ -151,6 +152,7 @@ class XMLBulkExport extends BulkExport
} else {
$sClassName = get_class($oObj);
$sData .= "<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n";
$aExportedObjects[] = $oObj;
}
foreach ($aClass2Attributes[$sAlias] as $sAttCode => $oAttDef) {
if (is_null($oObj)) {
@@ -166,6 +168,11 @@ class XMLBulkExport extends BulkExport
$sData .= "</Row>\n";
}
$iCount++;
$aExportedObjects = array_unique($aExportedObjects);
foreach ($aExportedObjects as $oExportedObject) {
$oExportedObject->FireEventReadDetails(get_class($this));
}
}
set_time_limit(intval($iPreviousTimeLimit));

View File

@@ -127,6 +127,9 @@ class DataFeatureRemovalController extends Controller
$aRemovedExtensions = $this->aExtensionsToCheck['to_be_removed'];
$aHiddenInputs['removed_extensions'] = $this->ConvertIntoSetupFormat($aRemovedExtensions);
$aExtensionsNotUninstallable = $this->aExtensionsToCheck['extensions_not_uninstallable'];
$aHiddenInputs['extensions_not_uninstallable'] = $this->ConvertIntoSetupFormat($aExtensionsNotUninstallable);
}
$aParams['aAddedExtensions'] = $aAddedExtensions;
@@ -344,7 +347,7 @@ class DataFeatureRemovalController extends Controller
'uninstallable' => $oExtension->CanBeUninstalled(),
'remote' => $oExtension->IsRemote(),
'missing' => $oExtension->bRemovedFromDisk,
'cannot-be-installed' => count($oExtension->aMissingDependencies) > 0,
'cannot-be-installed' => $oExtension->HasDependencyIssue(),
],
];
@@ -425,6 +428,7 @@ class DataFeatureRemovalController extends Controller
$this->aExtensionsToCheck = [
'to_be_installed' => [],
'to_be_removed' => [],
'extensions_not_uninstallable' => [],
];
foreach ($aAvailableExtensions as $sCode => &$aExtensionData) {
if (!isset($aSelectedExtensionsFromUI[$sCode])) {
@@ -438,6 +442,9 @@ class DataFeatureRemovalController extends Controller
if (! $this->bForcedUninstallation && $aExtensionData['extra_flags']['uninstallable']) {
$this->bForcedUninstallation = true;
}
if (false === $aExtensionData['extra_flags']['uninstallable']) {
$this->aExtensionsToCheck['extensions_not_uninstallable'][] = $sCode;
}
} elseif (!$aExtensionData['installed'] && $aSelectedExtensionsFromUI[$sCode] === 'on') {
$aExtensionData['extra_flags']['selected'] = true;
$sLabel = $aAvailableExtensions[$sCode]['label'];

View File

@@ -159,7 +159,7 @@ function DoInstall(WebPage $oPage)
foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) {
if ($oExtension->sSource == iTopExtension::SOURCE_REMOTE) {
if (count($oExtension->aMissingDependencies) > 0) {
if ($oExtension->HasDependencyIssue()) {
$oPage->add('<div class="choice">');
$oPage->add('<input type="checkbox" disabled>&nbsp;');
$sTitle = Dict::Format('iTopHub:InstallationEffect:MissingDependencies_Details', implode(', ', $oExtension->aMissingDependencies));

View File

@@ -614,7 +614,6 @@ return array(
'Combodo\\iTop\\Service\\Base\\ObjectRepository' => $baseDir . '/sources/Service/Base/ObjectRepository.php',
'Combodo\\iTop\\Service\\Base\\iDataPostProcessor' => $baseDir . '/sources/Service/Base/iDataPostProcessor.php',
'Combodo\\iTop\\Service\\Cache\\DataModelDependantCache' => $baseDir . '/sources/Service/Cache/DataModelDependantCache.php',
'Combodo\\iTop\\Service\\Cron\\CronLog' => $baseDir . '/sources/Service/Cron/CronLog.php',
'Combodo\\iTop\\Service\\DependencyInjection\\DIException' => $baseDir . '/sources/Service/DependencyInjection/DIException.php',
'Combodo\\iTop\\Service\\DependencyInjection\\ServiceLocator' => $baseDir . '/sources/Service/DependencyInjection/ServiceLocator.php',
'Combodo\\iTop\\Service\\Events\\Description\\EventDataDescription' => $baseDir . '/sources/Service/Events/Description/EventDataDescription.php',

View File

@@ -28,12 +28,12 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
);
public static $prefixLengthsPsr4 = array (
'T' =>
'T' =>
array (
'Twig\\' => 5,
'TheNetworg\\OAuth2\\Client\\' => 25,
),
'S' =>
'S' =>
array (
'Symfony\\Runtime\\Symfony\\Component\\' => 34,
'Symfony\\Polyfill\\Php83\\' => 23,
@@ -85,7 +85,7 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
'ScssPhp\\ScssPhp\\' => 16,
'Sabberworm\\CSS\\' => 15,
),
'P' =>
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
@@ -96,310 +96,310 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
'PhpParser\\' => 10,
'Pelago\\Emogrifier\\' => 18,
),
'L' =>
'L' =>
array (
'League\\OAuth2\\Client\\' => 21,
),
'G' =>
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
),
'F' =>
'F' =>
array (
'Firebase\\JWT\\' => 13,
),
'E' =>
'E' =>
array (
'Egulias\\EmailValidator\\' => 23,
),
'D' =>
'D' =>
array (
'Doctrine\\Common\\Lexer\\' => 22,
),
);
public static $prefixDirsPsr4 = array (
'Twig\\' =>
'Twig\\' =>
array (
0 => __DIR__ . '/..' . '/twig/twig/src',
),
'TheNetworg\\OAuth2\\Client\\' =>
'TheNetworg\\OAuth2\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/thenetworg/oauth2-azure/src',
),
'Symfony\\Runtime\\Symfony\\Component\\' =>
'Symfony\\Runtime\\Symfony\\Component\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/runtime/Internal',
),
'Symfony\\Polyfill\\Php83\\' =>
'Symfony\\Polyfill\\Php83\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php83',
),
'Symfony\\Polyfill\\Mbstring\\' =>
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Intl\\Normalizer\\' =>
'Symfony\\Polyfill\\Intl\\Normalizer\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer',
),
'Symfony\\Polyfill\\Intl\\Idn\\' =>
'Symfony\\Polyfill\\Intl\\Idn\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-idn',
),
'Symfony\\Polyfill\\Intl\\Icu\\' =>
'Symfony\\Polyfill\\Intl\\Icu\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-icu',
),
'Symfony\\Polyfill\\Intl\\Grapheme\\' =>
'Symfony\\Polyfill\\Intl\\Grapheme\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme',
),
'Symfony\\Polyfill\\Ctype\\' =>
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Symfony\\Contracts\\Translation\\' =>
'Symfony\\Contracts\\Translation\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/translation-contracts',
),
'Symfony\\Contracts\\Service\\' =>
'Symfony\\Contracts\\Service\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/service-contracts',
),
'Symfony\\Contracts\\EventDispatcher\\' =>
'Symfony\\Contracts\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts',
),
'Symfony\\Contracts\\Cache\\' =>
'Symfony\\Contracts\\Cache\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/cache-contracts',
),
'Symfony\\Component\\Yaml\\' =>
'Symfony\\Component\\Yaml\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/yaml',
),
'Symfony\\Component\\VarExporter\\' =>
'Symfony\\Component\\VarExporter\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/var-exporter',
),
'Symfony\\Component\\VarDumper\\' =>
'Symfony\\Component\\VarDumper\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/var-dumper',
),
'Symfony\\Component\\Validator\\' =>
'Symfony\\Component\\Validator\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/validator',
),
'Symfony\\Component\\String\\' =>
'Symfony\\Component\\String\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/string',
),
'Symfony\\Component\\Stopwatch\\' =>
'Symfony\\Component\\Stopwatch\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/stopwatch',
),
'Symfony\\Component\\Security\\Csrf\\' =>
'Symfony\\Component\\Security\\Csrf\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/security-csrf',
),
'Symfony\\Component\\Security\\Core\\' =>
'Symfony\\Component\\Security\\Core\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/security-core',
),
'Symfony\\Component\\Runtime\\' =>
'Symfony\\Component\\Runtime\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/runtime',
),
'Symfony\\Component\\Routing\\' =>
'Symfony\\Component\\Routing\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/routing',
),
'Symfony\\Component\\PropertyInfo\\' =>
'Symfony\\Component\\PropertyInfo\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/property-info',
),
'Symfony\\Component\\PropertyAccess\\' =>
'Symfony\\Component\\PropertyAccess\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/property-access',
),
'Symfony\\Component\\PasswordHasher\\' =>
'Symfony\\Component\\PasswordHasher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/password-hasher',
),
'Symfony\\Component\\OptionsResolver\\' =>
'Symfony\\Component\\OptionsResolver\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/options-resolver',
),
'Symfony\\Component\\Mime\\' =>
'Symfony\\Component\\Mime\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/mime',
),
'Symfony\\Component\\Mailer\\' =>
'Symfony\\Component\\Mailer\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/mailer',
),
'Symfony\\Component\\HttpKernel\\' =>
'Symfony\\Component\\HttpKernel\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/http-kernel',
),
'Symfony\\Component\\HttpFoundation\\' =>
'Symfony\\Component\\HttpFoundation\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/http-foundation',
),
'Symfony\\Component\\Form\\' =>
'Symfony\\Component\\Form\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/form',
),
'Symfony\\Component\\Finder\\' =>
'Symfony\\Component\\Finder\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/finder',
),
'Symfony\\Component\\Filesystem\\' =>
'Symfony\\Component\\Filesystem\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/filesystem',
),
'Symfony\\Component\\EventDispatcher\\' =>
'Symfony\\Component\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher',
),
'Symfony\\Component\\ErrorHandler\\' =>
'Symfony\\Component\\ErrorHandler\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/error-handler',
),
'Symfony\\Component\\Dotenv\\' =>
'Symfony\\Component\\Dotenv\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/dotenv',
),
'Symfony\\Component\\DependencyInjection\\' =>
'Symfony\\Component\\DependencyInjection\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/dependency-injection',
),
'Symfony\\Component\\CssSelector\\' =>
'Symfony\\Component\\CssSelector\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/css-selector',
),
'Symfony\\Component\\Console\\' =>
'Symfony\\Component\\Console\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Symfony\\Component\\Config\\' =>
'Symfony\\Component\\Config\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/config',
),
'Symfony\\Component\\Cache\\' =>
'Symfony\\Component\\Cache\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/cache',
),
'Symfony\\Bundle\\WebProfilerBundle\\' =>
'Symfony\\Bundle\\WebProfilerBundle\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/web-profiler-bundle',
),
'Symfony\\Bundle\\TwigBundle\\' =>
'Symfony\\Bundle\\TwigBundle\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/twig-bundle',
),
'Symfony\\Bundle\\FrameworkBundle\\' =>
'Symfony\\Bundle\\FrameworkBundle\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/framework-bundle',
),
'Symfony\\Bundle\\DebugBundle\\' =>
'Symfony\\Bundle\\DebugBundle\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/debug-bundle',
),
'Symfony\\Bridge\\Twig\\' =>
'Symfony\\Bridge\\Twig\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/twig-bridge',
),
'Soundasleep\\' =>
'Soundasleep\\' =>
array (
0 => __DIR__ . '/..' . '/soundasleep/html2text/src',
),
'ScssPhp\\ScssPhp\\' =>
'ScssPhp\\ScssPhp\\' =>
array (
0 => __DIR__ . '/..' . '/scssphp/scssphp/src',
),
'Sabberworm\\CSS\\' =>
'Sabberworm\\CSS\\' =>
array (
0 => __DIR__ . '/..' . '/sabberworm/php-css-parser/src',
),
'Psr\\Log\\' =>
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/src',
),
'Psr\\Http\\Message\\' =>
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'Psr\\EventDispatcher\\' =>
'Psr\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/psr/event-dispatcher/src',
),
'Psr\\Container\\' =>
'Psr\\Container\\' =>
array (
0 => __DIR__ . '/..' . '/psr/container/src',
),
'Psr\\Cache\\' =>
'Psr\\Cache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/cache/src',
),
'PhpParser\\' =>
'PhpParser\\' =>
array (
0 => __DIR__ . '/..' . '/nikic/php-parser/lib/PhpParser',
),
'Pelago\\Emogrifier\\' =>
'Pelago\\Emogrifier\\' =>
array (
0 => __DIR__ . '/..' . '/pelago/emogrifier/src',
),
'League\\OAuth2\\Client\\' =>
'League\\OAuth2\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/league/oauth2-google/src',
1 => __DIR__ . '/..' . '/league/oauth2-client/src',
),
'GuzzleHttp\\Psr7\\' =>
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'GuzzleHttp\\Promise\\' =>
'GuzzleHttp\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
),
'GuzzleHttp\\' =>
'GuzzleHttp\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
),
'Firebase\\JWT\\' =>
'Firebase\\JWT\\' =>
array (
0 => __DIR__ . '/..' . '/firebase/php-jwt/src',
),
'Egulias\\EmailValidator\\' =>
'Egulias\\EmailValidator\\' =>
array (
0 => __DIR__ . '/..' . '/egulias/email-validator/src',
),
'Doctrine\\Common\\Lexer\\' =>
'Doctrine\\Common\\Lexer\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/lexer/src',
),
);
public static $prefixesPsr0 = array (
'C' =>
'C' =>
array (
'Console' =>
'Console' =>
array (
0 => __DIR__ . '/..' . '/pear/console_getopt',
),
),
'A' =>
'A' =>
array (
'Archive_Tar' =>
'Archive_Tar' =>
array (
0 => __DIR__ . '/..' . '/pear/archive_tar',
),
@@ -1015,7 +1015,6 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
'Combodo\\iTop\\Service\\Base\\ObjectRepository' => __DIR__ . '/../..' . '/sources/Service/Base/ObjectRepository.php',
'Combodo\\iTop\\Service\\Base\\iDataPostProcessor' => __DIR__ . '/../..' . '/sources/Service/Base/iDataPostProcessor.php',
'Combodo\\iTop\\Service\\Cache\\DataModelDependantCache' => __DIR__ . '/../..' . '/sources/Service/Cache/DataModelDependantCache.php',
'Combodo\\iTop\\Service\\Cron\\CronLog' => __DIR__ . '/../..' . '/sources/Service/Cron/CronLog.php',
'Combodo\\iTop\\Service\\DependencyInjection\\DIException' => __DIR__ . '/../..' . '/sources/Service/DependencyInjection/DIException.php',
'Combodo\\iTop\\Service\\DependencyInjection\\ServiceLocator' => __DIR__ . '/../..' . '/sources/Service/DependencyInjection/ServiceLocator.php',
'Combodo\\iTop\\Service\\Events\\Description\\EventDataDescription' => __DIR__ . '/../..' . '/sources/Service/Events/Description/EventDataDescription.php',

View File

@@ -49,8 +49,6 @@ if (Session::IsSet('auth_user')) {
UserRights::Login($sAuthUser); // Set the user's language
}
LoginWebPage::ResetSession();
$bLoginDebug = MetaModel::GetConfig()->Get('login_debug');
if ($bLoginDebug) {
IssueLog::Info("---------------------------------");
@@ -88,7 +86,7 @@ if ($bLoginDebug) {
IssueLog::Info("--> Display logout page");
}
LoginWebPage::ResetSession(true);
LoginWebPage::ResetSession();
if ($bLoginDebug) {
$sSessionLog = session_id().' '.utils::GetSessionLog();
IssueLog::Info("SESSION: $sSessionLog");

View File

@@ -545,7 +545,7 @@ class iTopExtensionsMap
continue;
}
if (! $bKeepExtensionsHavingMissingDependencies && count($oExtension->aMissingDependencies) > 0) {
if (! $bKeepExtensionsHavingMissingDependencies && $oExtension->HasDependencyIssue()) {
//skip extensions with dependency issues
continue;
}
@@ -562,19 +562,20 @@ class iTopExtensionsMap
public function GetAllExtensionsOptionInfo(bool $bRemoteExtensionsShouldBeMandatory = true): array
{
$aRes = [];
foreach ($this->GetAllExtensionsToDisplayInSetup(false, $bRemoteExtensionsShouldBeMandatory) as $sCode => $oExtension) {
foreach ($this->GetAllExtensionsToDisplayInSetup(true, $bRemoteExtensionsShouldBeMandatory) as $sCode => $oExtension) {
$aRes[] = [
'extension_code' => $oExtension->sCode,
'title' => $oExtension->sLabel,
'description' => $oExtension->sDescription,
'more_info' => $oExtension->sMoreInfoUrl,
'default' => true, // by default offer to install all modules
'modules' => $oExtension->aModules,
'mandatory' => $oExtension->bMandatory,
'source_label' => $oExtension->GetExtensionSourceLabel(),
'uninstallable' => $oExtension->CanBeUninstalled(),
'missing' => $oExtension->bRemovedFromDisk,
'version' => $oExtension->sVersion,
'extension_code' => $oExtension->sCode,
'title' => $oExtension->sLabel,
'description' => $oExtension->sDescription,
'more_info' => $oExtension->sMoreInfoUrl,
'default' => true, // by default offer to install all modules
'modules' => $oExtension->aModules,
'mandatory' => $oExtension->bMandatory,
'dependency_issue' => $oExtension->HasDependencyIssue(),
'source_label' => $oExtension->GetExtensionSourceLabel(),
'uninstallable' => $oExtension->CanBeUninstalled(),
'missing' => $oExtension->bRemovedFromDisk,
'version' => $oExtension->sVersion,
];
}

View File

@@ -200,4 +200,9 @@ class iTopExtension
{
return $this->sLabel !== '';
}
public function HasDependencyIssue(): bool
{
return count($this->aMissingDependencies) > 0;
}
}

View File

@@ -1661,11 +1661,14 @@ JS
$aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $aDirsToScan, $bAbortOnMissingDependency, $aModulesToLoad);
foreach ($aAvailableModules as $key => $aModule) {
$bIsExtra = (array_key_exists('root_dir', $aModule) && (strpos($aModule['root_dir'], $sExtraDir) !== false)); // Some modules (root, datamodel) have no 'root_dir'
if ($bIsExtra) {
// Modules in data/production-modules/ are considered as mandatory and always installed
$aAvailableModules[$key]['visible'] = false;
$bRemoteExtensionsShouldBeMandatory = !$oWizard->GetParameter('force-uninstall', false);
if ($bRemoteExtensionsShouldBeMandatory) {
foreach ($aAvailableModules as $key => $aModule) {
$bIsExtra = (array_key_exists('root_dir', $aModule) && (strpos($aModule['root_dir'], $sExtraDir) !== false)); // Some modules (root, datamodel) have no 'root_dir'
if ($bIsExtra) {
// Modules in data/production-modules/ are considered as mandatory and always installed
$aAvailableModules[$key]['visible'] = false;
}
}
}
@@ -2056,45 +2059,25 @@ JS
*/
private static function WaitCronTermination($oConfig, $sMode)
{
$iMaxDuration = $oConfig->Get('cron_max_execution_time');
// Avoid PHP stopping while waiting the cron
set_time_limit($iMaxDuration);
try {
// Wait for cron to stop
if (is_null($oConfig) || ContextTag::Check(ContextTag::TAG_CRON)) {
return;
}
// Limit the number of cron process to run in parallel
$iMaxCronProcess = $oConfig->Get('cron.max_processes');
// Use mutex to check if cron is running
$oMutex = self::GetCronMutex($oConfig);
$iCount = 1;
$iTimeLimit = time() + $iMaxDuration;
do {
$bIsRunning = false;
// Use all mutexes to check if cron is running
for ($i = 0; $i < $iMaxCronProcess; $i++) {
$sName = "cron#$i";
$oMutex = new iTopMutex(
$sName.$oConfig->Get('db_name').$oConfig->Get('db_subname'),
$oConfig->Get('db_host'),
$oConfig->Get('db_user'),
$oConfig->Get('db_pwd'),
$oConfig->Get('db_tls.enabled'),
$oConfig->Get('db_tls.ca')
);
if ($oMutex->IsLocked()) {
$bIsRunning = true;
SetupLog::Info("Waiting for cron to stop ($iCount)");
$iCount++;
sleep(1);
if (time() > $iTimeLimit) {
SetupLog::Error("Cannot enter $sMode mode, consider stopping the cron temporarily");
throw new Exception("Cannot enter $sMode mode, consider stopping the cron temporarily");
}
break;
}
$iStarted = time();
$iMaxDuration = $oConfig->Get('cron_max_execution_time');
$iTimeLimit = $iStarted + $iMaxDuration;
while ($oMutex->IsLocked()) {
SetupLog::Info("Waiting for cron to stop ($iCount)");
$iCount++;
sleep(1);
if (time() > $iTimeLimit) {
throw new Exception("Cannot enter $sMode mode, consider stopping the cron temporarily");
}
} while ($bIsRunning);
}
} catch (Exception $e) {
// Ignore errors
}

View File

@@ -338,7 +338,7 @@ class InstallationFileService
continue;
}
if ($this->CanChooseUnpackageExtension($oExtension)) {
if (($oExtension->bVisible) && (count($oExtension->aMissingDependencies) === 0)) {
if ($oExtension->bVisible && !$oExtension->HasDependencyIssue()) {
$aCurrentModules = [];
$aUnselectableModules = [];
$bIsExtensionSelectable = true;

View File

@@ -112,6 +112,22 @@ JS);
return;
}
// When the setup reach this step, it already checked whether extensions were uninstallable (during WizStepModulesChoice or combodo-data-feature-removal). We only need to log what has been done.
if ($this->oWizard->GetParameter('force-uninstall', false)) {
SetupLog::Warning("User disabled uninstallation checks");
}
$aExtensionsRemoved = json_decode($this->oWizard->GetParameter('removed_extensions'), true) ?? [];
$aExtensionsNotUninstallable = json_decode($this->oWizard->GetParameter('extensions_not_uninstallable'), true) ?? [];
$aExtensionsForceUninstalled = [];
foreach ($aExtensionsRemoved as $sExtensionCode => $sLabel) {
if (in_array($sExtensionCode, $aExtensionsNotUninstallable)) {
$aExtensionsForceUninstalled[] = $sExtensionCode;
}
}
if (count($aExtensionsForceUninstalled)) {
SetupLog::Warning("Extensions uninstalled forcefully : ".implode(',', $aExtensionsForceUninstalled));
}
$oPage->add_ready_script(<<<JS
$("#wiz_form").data("installation_status", "not started");
ExecuteStep("");

View File

@@ -31,8 +31,8 @@ class WizStepLandingBeforeAudit extends WizStepModulesChoice
$oWizard->SetParameter('db_tls_enabled', $this->oConfig->Get('db_tls.enabled'));
$oWizard->SetParameter('db_tls_ca', $this->oConfig->Get('db_tls.ca') ?? '');
$oWizard->SetParameter('display_choices', '');
$oWizard->SetParameter('extensions_not_uninstallable', '[]');
$oWizard->SaveParameter('extensions_not_uninstallable', '[]');
$oWizard->SaveParameter('use_symbolic_links', MFCompiler::UseSymbolicLinks());
$oWizard->SaveParameter('force-uninstall', false);
$oWizard->SaveParameter('skip_wizard', false);

View File

@@ -587,7 +587,7 @@ EOF
break;
}
}
if ((isset($aChoice['mandatory']) && $aChoice['mandatory']) ||
if ((isset($aChoice['mandatory']) && $aChoice['mandatory'] && (!isset($aChoice['dependency_issue']) || !$aChoice['dependency_issue'])) ||
(isset($aSelectedChoices[$sChoiceId]) && ($aSelectedChoices[$sChoiceId] == $sChoiceId))) {
$sDisplayChoices .= '<li>'.$aChoice['title'].'</li>';
if (isset($aChoice['modules'])) {
@@ -637,7 +637,7 @@ EOF
if ($sChoiceName == null) {
$sChoiceName = $sChoiceId;
}
if ((isset($aChoice['mandatory']) && $aChoice['mandatory']) ||
if ((isset($aChoice['mandatory']) && $aChoice['mandatory'] && (!isset($aChoice['dependency_issue']) || !$aChoice['dependency_issue'])) ||
(isset($aSelectedChoices[$sChoiceName]) && ($aSelectedChoices[$sChoiceName] == $sChoiceId))) {
$sDisplayChoices .= '<li>'.$aChoice['title'].'</li>';
if ($aSelectedExtensions !== null) {
@@ -751,12 +751,16 @@ EOF
$bMissingFromDisk = isset($aChoice['missing']) && $aChoice['missing'] === true;
$bMandatory = (isset($aChoice['mandatory']) && $aChoice['mandatory']);
$bInstalled = $bMissingFromDisk || $oITopExtension->bInstalled;
$bDependencyIssue = $oITopExtension->HasDependencyIssue();
$bChecked = $bSelected;
$bDisabled = false;
if ($bMissingFromDisk) {
$bDisabled = true;
$bChecked = false;
} elseif ($bDependencyIssue) {
$bDisabled = true;
$bChecked = false;
} elseif ($bMandatory) {
$bDisabled = true;
$bChecked = true;
@@ -787,6 +791,8 @@ EOF
return [
'uninstallable' => $bCanBeUninstalled,
'dependency_issue' => $bDependencyIssue,
'mandatory' => $bMandatory,
'missing' => $bMissingFromDisk,
'installed' => $bInstalled,
'disabled' => $bDisabled,
@@ -805,7 +811,7 @@ EOF
$sChoiceId = $sParentId.self::$SEP.$index;
$aFlags = $this->ComputeChoiceFlags($aChoice, $sChoiceId, $aSelectedComponents, $bAllDisabled, $bDisableUninstallCheck, $this->bUpgrade);
if ($aFlags['disabled'] && !$aFlags['checked'] && !$aFlags['uninstallable'] && !$bDisableUninstallCheck) {
if ($aFlags['disabled'] && !$aFlags['checked'] && !$bDisableUninstallCheck && (!$aFlags['uninstallable'] || $aFlags['mandatory'])) {
$this->bCanMoveForward = false;//Disable "Next"
}
@@ -882,6 +888,9 @@ EOF
if (!$aFlags['uninstallable']) {
$sTooltip .= '<div id="badge--'.$sId.'--not-uninstallable" class="ibo-badge ibo-block ibo-is-yellow" title="Once this extension has been installed, it should not be uninstalled." >cannot be uninstalled</div>';
}
if ($aFlags['dependency_issue']) {
$sTooltip .= '<div id="badge--'.$sId.'--cannot-be-installed" class="ibo-badge ibo-block ibo-is-orange" title="This extension cannot be installed because one or more dependencies are not satisfied." >cannot be installed</div>';
}
$sMetadata = '';
if (isset($aChoice['version']) && isset($aChoice['source_label'])) {
@@ -939,10 +948,6 @@ EOF
public function GetNextButtonLabel()
{
if (!$this->bCanMoveForward) {
return 'Non-uninstallable extension missing';
}
if ($this->GetStepInfo(1 + $this->GetStepIndex()) === null) {
return 'Check compatibility';
}

View File

@@ -116,7 +116,7 @@ class WizStepSummary extends AbstractWizStepInstall
$oPage->add('<div class="closed"><a class="title ibo-setup-summary-title" href="#" aria-label="Extensions to be uninstalled">Extensions to be uninstalled</a>');
$aExtensionsRemoved = json_decode($this->oWizard->GetParameter('removed_extensions'), true) ?? [];
$aExtensionsNotUninstallable = json_decode($this->oWizard->GetParameter('extensions_not_uninstallable')) ?? [];
$aExtensionsNotUninstallable = json_decode($this->oWizard->GetParameter('extensions_not_uninstallable'), true) ?? [];
if (count($aExtensionsRemoved) > 0) {
$sExtensionsRemoved = '<ul>';
foreach ($aExtensionsRemoved as $sExtensionCode => $sLabel) {

View File

@@ -26,11 +26,11 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
$aBadges = [];
$bUninstallable = $aExtraFlags['uninstallable'] ?? true;
$bMissingFromDisk = $aExtraFlags['missing'] ?? false;
$bCannotBeInstalled = $aExtraFlags['cannot-be-installed'] ?? false;
$bDependencyIssue = $aExtraFlags['dependency_issue'] ?? false;
$bSelected = $aExtraFlags['selected'] ?? true;
$bDisabled = $aExtraFlags['disabled'] ?? false;
$bRemote = $aExtraFlags['remote'] ?? false;
self::AddExtraBadges($aBadges, $bUninstallable, $bMissingFromDisk, $bCannotBeInstalled, $sCode);
self::AddExtraBadges($aBadges, $bUninstallable, $bMissingFromDisk, $bDependencyIssue, $sCode);
$oBadgeInstalled = BadgeUIBlockFactory::MakeGreen(
Dict::S('UI:Layout:ExtensionsDetails:BadgeInstalled'),
Dict::S('UI:Layout:ExtensionsDetails:BadgeInstalled+'),
@@ -48,7 +48,7 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
$oExtensionDetails = new ExtensionDetails($sCode, $sLabel, $sDescription, $aMetaData, $aBadges, $sAbout);
$oExtensionDetails->GetToggler()->SetIsToggled(true);
if ($bMissingFromDisk || $bCannotBeInstalled) {
if ($bMissingFromDisk || $bDependencyIssue) {
$oExtensionDetails->GetToggler()->SetIsToggled(false);
$oExtensionDetails->GetToggler()->SetIsDisabled(true);
} elseif ((!$bUninstallable || $bRemote) && !$bDisabled) {
@@ -71,10 +71,10 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
{
$aBadges = [];
$bUninstallable = $aExtraFlags['uninstallable'] ?? true;
$bCannotBeInstalled = $aExtraFlags['cannot-be-installed'] ?? false;
$bDependencyIssue = $aExtraFlags['dependency_issue'] ?? false;
$bSelected = $aExtraFlags['selected'] ?? false;
$bDisabled = $aExtraFlags['disabled'] ?? false;
self::AddExtraBadges($aBadges, $bUninstallable, false, $bCannotBeInstalled, $sCode);
self::AddExtraBadges($aBadges, $bUninstallable, false, $bDependencyIssue, $sCode);
$oBadgeInstalled = BadgeUIBlockFactory::MakeGrey(
Dict::S('UI:Layout:ExtensionsDetails:BadgeNotInstalled'),
Dict::S('UI:Layout:ExtensionsDetails:BadgeNotInstalled+'),
@@ -91,7 +91,7 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
$aBadges[] = $oBadgeToBeUninstalled;
$oExtensionDetails = new ExtensionDetails($sCode, $sLabel, $sDescription, $aMetaData, $aBadges, $sAbout);
if ($bCannotBeInstalled) {
if ($bDependencyIssue) {
$oExtensionDetails->GetToggler()->SetIsToggled(false);
$oExtensionDetails->GetToggler()->SetIsDisabled(true);
}
@@ -107,7 +107,7 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
return $oExtensionDetails;
}
private static function AddExtraBadges(array &$aBadges, bool $bUninstallable, bool $bMissingFromDisk, bool $bCannotBeInstalled, string $sCode)
private static function AddExtraBadges(array &$aBadges, bool $bUninstallable, bool $bMissingFromDisk, bool $bDependencyIssue, string $sCode)
{
if (!$bUninstallable) {
$aBadges[] = BadgeUIBlockFactory::MakeYellow(
@@ -123,7 +123,7 @@ class ExtensionDetailsUIBlockFactory extends AbstractUIBlockFactory
self::GetBadgeId($sCode, self::BADGE_ID_MISSING_FROM_DISK)
);
}
if ($bCannotBeInstalled) {
if ($bDependencyIssue) {
$aBadges[] = BadgeUIBlockFactory::MakeOrange(
Dict::S('UI:Layout:ExtensionsDetails:BadgeCannotBeInstalled'),
Dict::S('UI:Layout:ExtensionsDetails:BadgeCannotBeInstalled+'),

View File

@@ -1,73 +0,0 @@
<?php
/*
* @copyright Copyright (C) 2010-2022 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
*/
namespace Combodo\iTop\Service\Cron;
use LogAPI;
use Page;
use utils;
/**
* @since 3.1.0
*/
class CronLog extends LogAPI
{
public static int $iProcessNumber = 0;
private static int $iDebugLevel = 0;
private static ?Page $oP = null;
public const CHANNEL_DEFAULT = 'Cron';
/**
* @inheritDoc
*
* As this object is used during setup, without any conf file available, customizing the level can be done by changing this constant !
*/
public const LEVEL_DEFAULT = self::LEVEL_INFO;
protected static $m_oFileLog = null;
public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = []): void
{
if (static::$iProcessNumber !== 0) {
$sMessage = 'cron'.str_pad(static::$iProcessNumber, 3).$sMessage;
}
parent::Log($sLevel, $sMessage, $sChannel, $aContext);
}
public static function Debug($sMessage, $sChannel = null, $aContext = []): void
{
if (self::$iDebugLevel > 0 && self::$oP) {
self::$oP->p('cron'.str_pad(static::$iProcessNumber, 3).$sMessage);
}
parent::Debug($sMessage, $sChannel, $aContext);
}
public static function Trace($sMessage, $sChannel = null, $aContext = []): void
{
if (self::$iDebugLevel > 1 && self::$oP) {
self::$oP->p('cron'.str_pad(static::$iProcessNumber, 3).$sMessage);
}
parent::Trace($sMessage, $sChannel, $aContext);
}
public static function SetDebug(Page $oP, int $iDebugLevel): void
{
self::$oP = $oP;
self::$iDebugLevel = $iDebugLevel;
}
public static function GetDebugClassName($sTaskClass): string
{
if (utils::StartsWith($sTaskClass, 'Combodo\\iTop\\Service\\')) {
return substr($sTaskClass, strlen('Combodo\\iTop\\Service\\'));
}
if (utils::StartsWith($sTaskClass, 'Combodo\\iTop\\')) {
return substr($sTaskClass, strlen('Combodo\\iTop\\'));
}
return $sTaskClass;
}
}

View File

@@ -131,6 +131,23 @@ class Session
}
}
/**
* Unset all session variables, no matter if they were set by iTop or not
*
* @return void
* @since 3.3.0 N°9625
*/
public static function UnsetAll(): void
{
if (session_status() !== PHP_SESSION_ACTIVE) {
self::Start();
$_SESSION = [];
self::WriteClose();
} else {
$_SESSION = [];
}
}
/**
* @param string|array $key key to access to the session variable. To access to $_SESSION['a']['b'] $key must be ['a', 'b']
* @param $default
@@ -183,6 +200,10 @@ class Session
public static function ListVariables(): array
{
if (!isset($_SESSION)) {
return [];
}
return array_keys($_SESSION);
}

View File

@@ -123,6 +123,23 @@ class SessionTest extends ItopTestCase
$this->assertFalse(Session::IsSet(['test1', 'test2', 'test3']));
}
public function testUnsetAll()
{
Session::Start();
Session::Set('test', 'OK');
Session::Set(['test1', 'test2', 'test3'], 'OK');
Session::Set('another_test', ['foo' => 'bar']);
$this->assertTrue(Session::IsSet('test'));
$this->assertTrue(Session::IsSet(['test1', 'test2', 'test3']));
$this->assertTrue(Session::IsSet('another_test'));
Session::UnsetAll();
$this->assertEmpty($_SESSION);
$this->assertFalse(Session::IsSet('test'));
$this->assertFalse(Session::IsSet(['test1', 'test2', 'test3']));
$this->assertFalse(Session::IsSet('another_test'));
}
public function testRegenerateId()
{
Session::Start();

View File

@@ -49,6 +49,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => false,
'checked' => false,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A selected but not installed extension should be checked and enabled' => [
@@ -70,10 +72,15 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => false,
'checked' => true,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A missing extension should be disabled and unchecked' => [
'aExtensionsOnDiskOrDb' => [
'itop-ext1' => [
'installed' => false,
],
],
'aWizardStepDefinition' => [
'extension_code' => 'itop-ext1',
@@ -89,10 +96,15 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => true,
'checked' => false,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A missing extension should always be disabled and unchecked, even when mandatory' => [
'aExtensionsOnDiskOrDb' => [
'itop-ext1' => [
'installed' => false,
],
],
'aWizardStepDefinition' => [
'extension_code' => 'itop-ext1',
@@ -108,10 +120,15 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => true,
'checked' => false,
'dependency_issue' => false,
'mandatory' => true,
],
],
'A missing extension should always be disabled and unchecked, even when non-uninstallable' => [
'aExtensionsOnDiskOrDb' => [
'itop-ext1' => [
'installed' => false,
],
],
'aWizardStepDefinition' => [
'extension_code' => 'itop-ext1',
@@ -127,6 +144,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => true,
'checked' => false,
'dependency_issue' => false,
'mandatory' => true,
],
],
'An installed but not selected extension should not be checked and be enabled' => [
@@ -148,6 +167,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => false,
'checked' => false,
'dependency_issue' => false,
'mandatory' => false,
],
],
'An installed non uninstallable extension should be checked and disabled' => [
@@ -169,6 +190,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => true,
'checked' => true,
'dependency_issue' => false,
'mandatory' => false,
],
],
'An installed non uninstallable extension should be enabled if the "disable uninstallation check" flag is set' => [
@@ -190,6 +213,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => false,
'checked' => true,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A mandatory extension should be checked and disabled' => [
@@ -211,6 +236,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => true,
'checked' => true,
'dependency_issue' => false,
'mandatory' => true,
],
],
'A mandatory extension should be checked and disabled even if the "disable uninstallation check" flag is set' => [
@@ -232,6 +259,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => true,
'checked' => true,
'dependency_issue' => false,
'mandatory' => true,
],
],
'An optional sub extension should not force its parent flags' => [
@@ -265,6 +294,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => false,
'checked' => false,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A mandatory sub extension should force its parent to be checked and disabled' => [
@@ -298,6 +329,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => false,
'disabled' => true,
'checked' => true,
'dependency_issue' => false,
'mandatory' => false,
],
],
'An installed non uninstallable sub extension should force its parent to be checked and disabled' => [
@@ -331,6 +364,8 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => true,
'checked' => true,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A non installed non uninstallable sub extension should not force its parent flags' => [
@@ -364,6 +399,62 @@ class WizStepModulesChoiceTest extends ItopTestCase
'installed' => true,
'disabled' => false,
'checked' => false,
'dependency_issue' => false,
'mandatory' => false,
],
],
'A non installed extension with missing dependencies should be not checked and disabled' => [
'aExtensionsOnDiskOrDb' => [
'itop-ext1' => [
'installed' => false,
'missing_dependencies' => [
'itop-ext1-1',
],
],
],
'aWizardStepDefinition' => [
'extension_code' => 'itop-ext1',
'mandatory' => false,
'uninstallable' => true,
'missing_dependencies' => true,
],
'bCurrentSelected' => false,
'bDisableUninstallChecks' => false,
'aExpectedFlags' => [
'uninstallable' => true,
'missing' => false,
'installed' => false,
'disabled' => true,
'checked' => false,
'dependency_issue' => true,
'mandatory' => false,
],
],
'An installed extension with missing dependencies should be not checked and disabled' => [
'aExtensionsOnDiskOrDb' => [
'itop-ext1' => [
'installed' => true,
'missing_dependencies' => [
'itop-ext1-1',
],
],
],
'aWizardStepDefinition' => [
'extension_code' => 'itop-ext1',
'mandatory' => false,
'uninstallable' => true,
'missing_dependencies' => true,
],
'bCurrentSelected' => false,
'bDisableUninstallChecks' => false,
'aExpectedFlags' => [
'uninstallable' => true,
'missing' => false,
'installed' => true,
'disabled' => true,
'checked' => false,
'dependency_issue' => true,
'mandatory' => false,
],
],
];

View File

@@ -23,6 +23,7 @@ class iTopExtensionsMapFake extends iTopExtensionsMap
$oExtension->sVersion = $aExtension['version'] ?? '1.0.0';
$oExtension->sSource = $aExtension['source'] ?? iTopExtension::SOURCE_MANUAL;
$oExtension->aModuleInfo = $aExtension['module_info'] ?? [];
$oExtension->aMissingDependencies = $aExtension['missing_dependencies'] ?? [];
$oMap->AddExtension($oExtension);
}
return $oMap;

View File

@@ -19,14 +19,10 @@
*/
use Combodo\iTop\Application\WebPage\CLIPage;
use Combodo\iTop\Application\WebPage\Page;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Service\Cron\CronLog;
use Combodo\iTop\Service\InterfaceDiscovery\InterfaceDiscovery;
if (!defined('__DIR__')) {
define('__DIR__', dirname(__FILE__));
}
require_once(__DIR__.'/../approot.inc.php');
const EXIT_CODE_ERROR = -1;
@@ -37,7 +33,10 @@ if (file_exists(READONLY_MODE_FILE)) {
exit(EXIT_CODE_ERROR);
}
$sConfigFile = utils::GetConfigFilePath();
require_once(APPROOT.'/application/application.inc.php');
require_once(APPROOT.'/core/background.inc.php');
$sConfigFile = APPCONF.ITOP_DEFAULT_ENV.'/'.ITOP_CONFIG_FILE;
if (!file_exists($sConfigFile)) {
echo "iTop is not yet installed. Exiting...\n";
exit(EXIT_CODE_ERROR);
@@ -51,7 +50,7 @@ function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter = 'parameter')
{
$sValue = utils::ReadParam($sParam, null, true, $sSanitizationFilter);
if (is_null($sValue)) {
CronLog::Error("ERROR: Missing argument '$sParam'\n");
$oP->p("ERROR: Missing argument '$sParam'\n");
UsageAndExit($oP);
}
@@ -64,7 +63,7 @@ function UsageAndExit($oP)
if ($bModeCLI) {
$oP->p("USAGE:\n");
$oP->p("php cron.php --auth_user=<login> --auth_pwd=<password> [--param_file=<file>] [--verbose=0] [--status_only=1]\n");
$oP->p("php cron.php --auth_user=<login> --auth_pwd=<password> [--param_file=<file>] [--verbose=1] [--debug=1] [--status_only=1]\n");
} else {
$oP->p("Optional parameters: verbose, param_file, status_only\n");
}
@@ -92,6 +91,7 @@ function RunTask(BackgroundTask $oTask, $iTimeLimit)
$oProcess = new $TaskClass();
$oRefClass = new ReflectionClass(get_class($oProcess));
$oDateStarted = new DateTime();
$oDatePlanned = new DateTime($oTask->Get('next_run_date'));
$fStart = microtime(true);
$oCtx = new ContextTag('CRON:Task:'.$TaskClass);
@@ -99,34 +99,25 @@ function RunTask(BackgroundTask $oTask, $iTimeLimit)
$oExceptionToThrow = null;
try {
// Record (when starting) that this task was started, just in case it crashes during the execution
if ($oTask->Get('total_exec_count') == 0) {
// First execution
$oTask->Set('first_run_date', $oDateStarted->format('Y-m-d H:i:s'));
}
$oTask->Set('latest_run_date', $oDateStarted->format('Y-m-d H:i:s'));
// Record the current user running the cron
$oTask->Set('system_user', utils::GetCurrentUserName());
$oTask->Set('running', 1);
// Compute the next run date
if ($oRefClass->implementsInterface('iScheduledProcess')) {
// Schedules process do repeat at specific moments
$oPlannedStart = $oProcess->GetNextOccurrence();
} else {
// Background processes do repeat periodically
$oDatePlanned = new DateTime($oTask->Get('next_run_date'));
$oPlannedStart = clone $oDatePlanned;
// Let's schedule from the previous planned date of execution to avoid shift
$oPlannedStart->modify('+'.$oProcess->GetPeriodicity().' seconds');
$oNow = new DateTime();
while ($oPlannedStart->format('U') <= $oNow->format('U')) {
// Next planned start is already in the past, increase it again by a period
$oPlannedStart = $oPlannedStart->modify('+'.$oProcess->GetPeriodicity().' seconds');
$oTask->DBUpdate();
// Time in seconds allowed to the task
$iCurrTimeLimit = $iTimeLimit;
// Compute allowed time
if ($oRefClass->implementsInterface('iScheduledProcess') === false) {
// Periodic task, allow only X times ($iMaxTaskExecutionTime) its periodicity (GetPeriodicity())
$iMaxTaskExecutionTime = MetaModel::GetConfig()->Get('cron_task_max_execution_time');
$iTaskLimit = time() + $oProcess->GetPeriodicity() * $iMaxTaskExecutionTime;
// If our proposed time limit is less than cron limit, and cron_task_max_execution_time is > 0
if ($iTaskLimit < $iTimeLimit && $iMaxTaskExecutionTime > 0) {
$iCurrTimeLimit = $iTaskLimit;
}
}
$oTask->Set('next_run_date', $oPlannedStart->format('Y-m-d H:i:s'));
$oTask->DBUpdate();
$sMessage = $oProcess->Process($iTimeLimit);
$sMessage = $oProcess->Process($iCurrTimeLimit);
$oTask->Set('running', 0);
} catch (MySQLHasGoneAwayException $e) {
throw $e;
} catch (ProcessFatalException $e) {
@@ -137,12 +128,35 @@ function RunTask(BackgroundTask $oTask, $iTimeLimit)
} else {
$sMessage = 'Processing failed with message: '.$e->getMessage();
}
} finally {
$oTask->Set('running', 0);
$fDuration = microtime(true) - $fStart;
$oTask->ComputeDurations($fDuration); // does increment the counter and compute statistics
$oTask->DBUpdate();
}
$fDuration = microtime(true) - $fStart;
if ($oTask->Get('total_exec_count') == 0) {
// First execution
$oTask->Set('first_run_date', $oDateStarted->format('Y-m-d H:i:s'));
}
$oTask->ComputeDurations($fDuration); // does increment the counter and compute statistics
// Update the timestamp since we want to be able to re-order the tasks based on the time they finished
$oDateEnded = new DateTime();
$oTask->Set('latest_run_date', $oDateEnded->format('Y-m-d H:i:s'));
if ($oRefClass->implementsInterface('iScheduledProcess')) {
// Schedules process do repeat at specific moments
$oPlannedStart = $oProcess->GetNextOccurrence();
} else {
// Background processes do repeat periodically
$oPlannedStart = clone $oDatePlanned;
// Let's schedule from the previous planned date of execution to avoid shift
$oPlannedStart->modify($oProcess->GetPeriodicity().' seconds');
$oEnd = new DateTime();
while ($oPlannedStart->format('U') < $oEnd->format('U')) {
// Next planned start is already in the past, increase it again by a period
$oPlannedStart = $oPlannedStart->modify('+'.$oProcess->GetPeriodicity().' seconds');
}
}
$oTask->Set('next_run_date', $oPlannedStart->format('Y-m-d H:i:s'));
$oTask->DBUpdate();
if ($oExceptionToThrow) {
throw $oExceptionToThrow;
@@ -154,6 +168,8 @@ function RunTask(BackgroundTask $oTask, $iTimeLimit)
}
/**
* @param CLIPage|WebPage $oP
* @param boolean $bVerbose
*
* @param bool $bDebug
*
@@ -168,39 +184,22 @@ function RunTask(BackgroundTask $oTask, $iTimeLimit)
* @throws \OQLException
* @throws \ReflectionException
*/
function CronExec($bDebug)
function CronExec($oP, $bVerbose, $bDebug = false)
{
$iStarted = time();
$iMaxDuration = MetaModel::GetConfig()->Get('cron_max_execution_time');
$iTimeLimit = $iStarted + $iMaxDuration;
$iCronSleep = MetaModel::GetConfig()->Get('cron_sleep');
$iMaxCronProcess = max(MetaModel::GetConfig()->Get('cron.max_processes'), 1);
// Allow a time slot for every task
// knowing that there are $iMaxCronProcess running in parallel for the number of tasks
$oSearch = new DBObjectSearch('BackgroundTask');
$oSearch->AddCondition('status', 'active');
$oTasks = new DBObjectSet($oSearch);
$iCount = $oTasks->Count();
$iTotalAvailableTime = $iMaxDuration * $iMaxCronProcess;
$iTimeSlot = (int)($iTotalAvailableTime / max($iCount, 1));
CronLog::Trace("Planned duration = $iMaxDuration seconds");
CronLog::Trace("Planned duration per task = $iTimeSlot seconds");
CronLog::Trace("Loop pause = $iCronSleep seconds");
$oResyncMutex = new iTopMutex("cron_resync_processes");
try {
if ($oResyncMutex->TryLock()) {
ReSyncProcesses($bDebug);
$oResyncMutex->Unlock();
}
} catch (Exception $e) {
CronLog::Error('Error: '.$e->GetMessage(), CronLog::CHANNEL_DEFAULT, ['stack' => $e->getTraceAsString()]);
if ($bVerbose) {
$oP->p("Planned duration = $iMaxDuration seconds");
$oP->p("Loop pause = $iCronSleep seconds");
}
ReSyncProcesses($oP, $bVerbose, $bDebug);
while (time() < $iTimeLimit) {
CheckMaintenanceMode();
CheckMaintenanceMode($oP);
$oNow = new DateTime();
$sNow = $oNow->format('Y-m-d H:i:s');
@@ -208,104 +207,103 @@ function CronExec($bDebug)
$oSearch->AddCondition('next_run_date', $sNow, '<=');
$oSearch->AddCondition('status', 'active');
$oTasks = new DBObjectSet($oSearch, ['next_run_date' => true]);
$bWorkDone = false;
$aTasks = [];
if ($oTasks->CountExceeds(0)) {
$aDebugMessages = [];
while ($oTask = $oTasks->Fetch()) {
$sTaskName = $oTask->Get('class_name');
$oTaskMutex = new iTopMutex("cron_$sTaskName");
if ($oTaskMutex->IsLocked()) {
// Already running, ignore
continue;
}
$aTasks[] = $oTask;
$sStatus = $oTask->Get('status');
$sLastRunDate = $oTask->Get('latest_run_date');
$sNextRunDate = $oTask->Get('next_run_date');
$aDebugMessages[] = sprintf('Task Class: %1$-25.25s Status: %2$-7s Last Run: %3$-19s Next Run: %4$-19s', $sTaskName, $sStatus, $sLastRunDate, $sNextRunDate);
$bWorkDone = true;
$aTasks = [];
if ($bVerbose) {
$sCount = $oTasks->Count();
$oP->p("$sCount Tasks planned to run now ($sNow):");
$oP->p('+---------------------------+---------+---------------------+---------------------+');
$oP->p('| Task Class | Status | Last Run | Next Run |');
$oP->p('+---------------------------+---------+---------------------+---------------------+');
}
$sCount = count($aDebugMessages);
CronLog::Trace("$sCount Tasks planned to run now ($sNow):");
foreach ($aDebugMessages as $sDebugMessage) {
CronLog::Trace($sDebugMessage);
while ($oTask = $oTasks->Fetch()) {
$aTasks[$oTask->Get('class_name')] = $oTask;
if ($bVerbose) {
$sTaskName = $oTask->Get('class_name');
$sStatus = $oTask->Get('status');
$sLastRunDate = $oTask->Get('latest_run_date');
$sNextRunDate = $oTask->Get('next_run_date');
$oP->p(sprintf('| %1$-25.25s | %2$-7s | %3$-19s | %4$-19s |', $sTaskName, $sStatus, $sLastRunDate, $sNextRunDate));
}
}
if ($bVerbose) {
$oP->p('+---------------------------+---------+---------------------+---------------------+');
}
$aRunTasks = [];
while (count($aTasks) > 0) {
$oTask = array_shift($aTasks);
foreach ($aTasks as $oTask) {
$sTaskClass = $oTask->Get('class_name');
// Check if the current task is running
$oTaskMutex = new iTopMutex("cron_$sTaskClass");
if (!$oTaskMutex->TryLock()) {
// Task is already running, try next one
continue;
}
$aRunTasks[] = $sTaskClass;
// N°3219 for each process will use a specific CMDBChange object with a specific track info
// Any BackgroundProcess can override this as needed
// Any BackgroundProcess can overrides this as needed
CMDBObject::SetCurrentChangeFromParams("Background task ($sTaskClass)");
// Run the task and record its next run time
$sDebugTaskClass = CronLog::GetDebugClassName($sTaskClass);
$oNow = new DateTime();
CronLog::Debug(sprintf("> Starting >>> %-'>49s", $sDebugTaskClass.' '));
if ($bVerbose) {
$oNow = new DateTime();
$oP->p(">> === ".$oNow->format('Y-m-d H:i:s').sprintf(" Starting:%-'=49s", ' '.$sTaskClass.' '));
}
try {
// The limit of time for this task corresponds to the time slot allowed for every task
// but limited to the cron job time limit
$sMessage = RunTask($oTask, min($iTimeLimit, time() + $iTimeSlot));
$sMessage = RunTask($aTasks[$sTaskClass], $iTimeLimit);
} catch (MySQLHasGoneAwayException $e) {
CronLog::Error("ERROR : 'MySQL has gone away' thrown when processing $sDebugTaskClass (error_code=".$e->getCode().")", CronLog::CHANNEL_DEFAULT, ['stack' => $e->getTraceAsString()]);
$oP->p("ERROR : 'MySQL has gone away' thrown when processing $sTaskClass (error_code=".$e->getCode().")");
exit(EXIT_CODE_FATAL);
} catch (ProcessFatalException $e) {
CronLog::Error("ERROR : an exception was thrown when processing '$sDebugTaskClass' (".$e->getInfoLog().")", CronLog::CHANNEL_DEFAULT, ['stack' => $e->getTraceAsString()]);
} finally {
$oTaskMutex->Unlock();
$oP->p("ERROR : an exception was thrown when processing '$sTaskClass' (".$e->getInfoLog().")");
IssueLog::Error("Cron.php error : an exception was thrown when processing '$sTaskClass' (".$e->getInfoLog().')');
}
if (!empty($sMessage)) {
CronLog::Debug("$sDebugTaskClass: $sMessage");
if ($bVerbose) {
if (!empty($sMessage)) {
$oP->p("$sTaskClass: $sMessage");
}
$oEnd = new DateTime();
$sNextRunDate = $oTask->Get('next_run_date');
$oP->p("<< === ".$oEnd->format('Y-m-d H:i:s').sprintf(" End of: %-'=42s", ' '.$sTaskClass.' ')." Next: $sNextRunDate");
}
$sNextRunDate = $oTask->Get('next_run_date');
CronLog::Debug(sprintf("< Ending <<<<< %-'<49s", $sDebugTaskClass.' ')." Next: $sNextRunDate");
if (time() > $iTimeLimit) {
break 2;
}
CheckMaintenanceMode();
if ($iMaxCronProcess > 1) {
// Reindex tasks every time
break;
}
CheckMaintenanceMode($oP);
}
// Tasks to run later
if (count($aTasks) == 0) {
if ($bVerbose) {
$oP->p('--');
$oSearch = new DBObjectSearch('BackgroundTask');
$oSearch->AddCondition('next_run_date', $sNow, '>');
$oSearch->AddCondition('status', 'active');
$oTasks = new DBObjectSet($oSearch, ['next_run_date' => true]);
while ($oTask = $oTasks->Fetch()) {
if (!in_array($oTask->Get('class_name'), $aRunTasks)) {
$sDebugTaskClass = CronLog::GetDebugClassName($oTask->Get('class_name'));
CronLog::Trace(sprintf("-- Skipping task: %-'-40s", $sDebugTaskClass.' ')." until: ".$oTask->Get('next_run_date'));
$oP->p(sprintf("-- Skipping task: %-'-40s", $oTask->Get('class_name').' ')." until: ".$oTask->Get('next_run_date'));
}
}
}
}
if (count($aTasks) == 0) {
CronLog::Trace("sleeping...");
sleep($iCronSleep);
if ($bVerbose && $bWorkDone) {
$oP->p("Sleeping...\n");
}
sleep($iCronSleep);
}
if ($bVerbose) {
$oP->p('');
DisplayStatus($oP, ['next_run_date' => true]);
$oP->p("Reached normal execution time limit (exceeded by ".(time() - $iTimeLimit)."s)");
}
CronLog::Trace("Reached normal execution time limit (exceeded by ".(time() - $iTimeLimit)."s)");
}
function CheckMaintenanceMode()
/**
* @param WebPage $oP
*/
function CheckMaintenanceMode(Page $oP)
{
// Verify files instead of reloading the full config each time
if (file_exists(MAINTENANCE_MODE_FILE) || file_exists(READONLY_MODE_FILE)) {
CronLog::Info("Maintenance detected, exiting");
$oP->p("Maintenance detected, exiting");
exit(EXIT_CODE_ERROR);
}
}
@@ -320,7 +318,7 @@ function CheckMaintenanceMode()
* @throws \MySQLException
* @throws \OQLException
*/
function DisplayStatus($oP = null, $aTaskOrderBy = [])
function DisplayStatus($oP, $aTaskOrderBy = [])
{
$oSearch = new DBObjectSearch('BackgroundTask');
$oTasks = new DBObjectSet($oSearch, $aTaskOrderBy);
@@ -348,6 +346,8 @@ function DisplayStatus($oP = null, $aTaskOrderBy = [])
}
/**
* @param $oP
* @param $bVerbose
* @param $bDebug
*
* @throws \ArchivedObjectException
@@ -359,7 +359,7 @@ function DisplayStatus($oP = null, $aTaskOrderBy = [])
* @throws \OQLException
* @throws \ReflectionException
*/
function ReSyncProcesses($bDebug)
function ReSyncProcesses($oP, $bVerbose, $bDebug)
{
// Enumerate classes implementing BackgroundProcess
//
@@ -394,9 +394,10 @@ function ReSyncProcesses($bDebug)
// Background processes do start asap, i.e. "now"
$oTask->Set('next_run_date', $oNow->format('Y-m-d H:i:s'));
}
$sDebugTaskClass = CronLog::GetDebugClassName($sTaskClass);
CronLog::Trace('Creating record for: '.$sDebugTaskClass);
CronLog::Trace('First execution planned at: '.$oTask->Get('next_run_date'));
if ($bVerbose) {
$oP->p('Creating record for: '.$sTaskClass);
$oP->p('First execution planned at: '.$oTask->Get('next_run_date'));
}
$oTask->DBInsert();
} else {
/** @var \BackgroundTask $oTask */
@@ -429,12 +430,14 @@ function ReSyncProcesses($bDebug)
}
}
$aDisplayProcesses = [];
foreach ($aProcesses as $oExecInstance) {
$aDisplayProcesses[] = get_class($oExecInstance);
if ($bVerbose) {
$aDisplayProcesses = [];
foreach ($aProcesses as $oExecInstance) {
$aDisplayProcesses[] = get_class($oExecInstance);
}
$sDisplayProcesses = implode(', ', $aDisplayProcesses);
$oP->p("Background processes: ".$sDisplayProcesses);
}
$sDisplayProcesses = implode(', ', $aDisplayProcesses);
CronLog::Trace("Background processes: ".$sDisplayProcesses);
}
////////////////////////////////////////////////////////////////////////////////
@@ -442,25 +445,20 @@ function ReSyncProcesses($bDebug)
// Main
//
CronLog::Enable(APPROOT.'/log/itop-cron.log');
set_time_limit(0); // Some background actions may really take long to finish (like backup)
$bIsModeCLI = utils::IsModeCLI();
if ($bIsModeCLI) {
$oP = new CLIPage("iTop - cron");
SetupUtils::CheckPhpAndExtensionsForCli($oP, EXIT_CODE_FATAL);
utils::UseParamFile();
} else {
$oP = new WebPage("iTop - cron");
}
try {
utils::UseParamFile();
$bIsModeCLI = utils::IsModeCLI();
if ($bIsModeCLI) {
$oP = new CLIPage("iTop - cron");
// Allow verbosity on output from 0 => none, 1 => debug, 2 => trace
// (writing debug messages to the cron.log file is configured with log_level_min config parameter)
$iVerbose = utils::ReadParam('verbose', 0, true /* Allow CLI */);
CronLog::SetDebug($oP, $iVerbose);
SetupUtils::CheckPhpAndExtensionsForCli($oP, EXIT_CODE_FATAL);
utils::UseParamFile();
} else {
$oP = new WebPage("iTop - cron");
}
$bVerbose = utils::ReadParam('verbose', false, true /* Allow CLI */);
$bDebug = utils::ReadParam('debug', false, true /* Allow CLI */);
if ($bIsModeCLI) {
// Next steps:
@@ -471,7 +469,7 @@ try {
if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd)) {
UserRights::Login($sAuthUser); // Login & set the user's language
} else {
CronLog::Error("Access wrong credentials ('$sAuthUser')");
$oP->p("Access wrong credentials ('$sAuthUser')");
$oP->output();
exit(EXIT_CODE_ERROR);
}
@@ -481,7 +479,7 @@ try {
}
if (!UserRights::IsAdministrator()) {
CronLog::Error("Access restricted to administrators");
$oP->p("Access restricted to administrators");
$oP->Output();
exit(EXIT_CODE_ERROR);
}
@@ -493,49 +491,42 @@ try {
}
require_once(APPROOT.'core/mutex.class.inc.php');
$oP->p("Starting: ".time().' ('.date('Y-m-d H:i:s').')');
} catch (Exception $e) {
CronLog::Error("Error: ".$e->GetMessage(), CronLog::CHANNEL_DEFAULT, ['stack' => $e->getTraceAsString()]);
$oP->p("Error: ".$e->GetMessage());
$oP->output();
exit(EXIT_CODE_FATAL);
}
try {
$oMutex = new iTopMutex('cron');
if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) {
CronLog::Debug("A maintenance is ongoing");
$oP->p("A maintenance is ongoing");
} else {
// Limit the number of cron process to run in parallel
$iMaxCronProcess = max(MetaModel::GetConfig()->Get('cron.max_processes'), 1);
$bCanRun = false;
$iProcessNumber = 0;
for ($i = 0; $i < $iMaxCronProcess; $i++) {
$oMutex = new iTopMutex("cron#$i");
if ($oMutex->TryLock()) {
$iProcessNumber = $i + 1;
$bCanRun = true;
break;
}
}
if ($bCanRun) {
CronLog::$iProcessNumber = $iProcessNumber;
$iCronRunningCount = utils::CountCronRunning();
CronLog::Info("Starting ($iCronRunningCount total cron running)");
CronExec($iVerbose > 0);
if ($oMutex->TryLock()) {
CronExec($oP, $bVerbose, $bDebug);
} else {
CronLog::$iProcessNumber = 0;
CronLog::Debug("The limit of $iMaxCronProcess cron process running in parallel is already reached");
exit(0);
// Exit silently
$oP->p("Already running...");
}
}
} catch (Exception $e) {
CronLog::Error("ERROR: '".$e->getMessage()."'", CronLog::CHANNEL_DEFAULT, ['stack' => $e->getTraceAsString()]);
$oP->p("ERROR: '".$e->getMessage()."'");
if ($bDebug) {
// Might contain verb parameters such a password...
$oP->p($e->getTraceAsString());
}
} finally {
try {
$oMutex->Unlock();
} catch (Exception $e) {
CronLog::Error("ERROR: '".$e->getMessage()."'");
$oP->p("ERROR: '".$e->getMessage()."'");
if ($bDebug) {
// Might contain verb parameters such a password...
$oP->p($e->getTraceAsString());
}
}
}
$iCronRunningCount = utils::CountCronRunning();
CronLog::Info("Exiting ($iCronRunningCount total cron running)");
$oP->p("Exiting: ".time().' ('.date('Y-m-d H:i:s').')');
$oP->Output();

View File

@@ -1,79 +0,0 @@
<?php
/*
* @copyright Copyright (C) 2010-2026 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
use Combodo\iTop\Application\WebPage\CLIPage;
use Combodo\iTop\Service\Cron\CronLog;
require_once(__DIR__.'/../approot.inc.php');
$sConfigFile = utils::GetConfigFilePath();
if (!file_exists($sConfigFile)) {
echo "iTop is not yet installed. Exiting...\n";
exit(EXIT_CODE_ERROR);
}
require_once(APPROOT.'/application/startup.inc.php');
function UsageAndExit()
{
echo "USAGE:\n";
echo "php cron_multi_launcher_linux.php --param_file=<file>\n";
exit(EXIT_CODE_FATAL);
}
function ReadMandatoryParam($sParam, $sSanitizationFilter = 'parameter')
{
$sValue = utils::ReadParam($sParam, null, true, $sSanitizationFilter);
if (is_null($sValue)) {
echo "ERROR: Missing argument '$sParam'\n";
UsageAndExit();
}
return trim($sValue);
}
////////////////////////////////////////////////////////////////////////////////
//
// Main
//
try {
utils::UseParamFile();
$sAuthUser = ReadMandatoryParam('auth_user', 'raw_data');
$sAuthPwd = ReadMandatoryParam('auth_pwd', 'raw_data');
if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd)) {
UserRights::Login($sAuthUser); // Login & set the user's language
} else {
echo "Access wrong credentials ('$sAuthUser')\n";
exit(EXIT_CODE_ERROR);
}
if (!UserRights::IsAdministrator()) {
echo "Access restricted to administrators\n";
exit(EXIT_CODE_ERROR);
}
if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE) || file_exists(MAINTENANCE_MODE_FILE) || file_exists(READONLY_MODE_FILE)) {
echo "A maintenance is ongoing\n";
exit(EXIT_CODE_ERROR);
}
$iMaxCronProcess = max(MetaModel::GetConfig()->Get('cron.max_processes'), 1);
$iRespawnTime = 60 / $iMaxCronProcess;
for ($i = 0; $i < $iMaxCronProcess; $i++) {
$sParamsFile = utils::ReadParam('param_file', '', true, 'raw_data');
$sCronCmd = APPROOT."webservices/cron.php --param_file=$sParamsFile";
$sOutputFile = APPROOT.'log/itop-cron.log';
// Execute command, redirect stdout and stderr
exec(sprintf('/usr/bin/php %s >> %s 2>&1 &', escapeshellcmd($sCronCmd), escapeshellarg($sOutputFile)));
sleep((int)(floor($iRespawnTime)));
}
} catch (Exception $e) {
echo "ERROR: {$e->getMessage()}\n";
}