File: FixInvalid.pm

package info (click to toggle)
otrs2 6.0.32-6
  • links: PTS
  • area: non-free
  • in suites: bullseye
  • size: 197,336 kB
  • sloc: perl: 1,003,018; javascript: 75,060; xml: 70,883; php: 51,819; sql: 22,361; sh: 379; makefile: 51
file content (291 lines) | stat: -rw-r--r-- 9,150 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# --
# Copyright (C) 2001-2021 OTRS AG, https://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see https://www.gnu.org/licenses/gpl-3.0.txt.
# --

package Kernel::System::Console::Command::Admin::Config::FixInvalid;

use strict;
use warnings;

use parent qw(Kernel::System::Console::BaseCommand);
use Kernel::System::VariableCheck qw( :all );

our @ObjectDependencies = (
    'Kernel::Config',
    'Kernel::System::Main',
    'Kernel::System::SysConfig',
    'Kernel::System::YAML',
);

sub Configure {
    my ( $Self, %Param ) = @_;

    $Self->Description('Attempt to fix invalid system configuration settings.');
    $Self->AddOption(
        Name        => 'non-interactive',
        Description => 'Attempt to fix invalid settings without user interaction.',
        Required    => 0,
        HasValue    => 0,
    );

    $Self->AddOption(
        Name => 'values-from-path',
        Description =>
            "Read values for invalid settings from a YAML file instead of user input (takes precedence in non-interactive mode).",
        Required   => 0,
        HasValue   => 1,
        ValueRegex => qr/.*/smx,
    );

    $Self->AddOption(
        Name        => 'skip-missing',
        Description => 'Skip invalid settings whose XML configuration file is not present.',
        Required    => 0,
        HasValue    => 0,
    );

    return;
}

sub Run {
    my ( $Self, %Param ) = @_;

    my $NonInteractive = $Self->GetOption('non-interactive') || 0;
    my $ValuesFromPath = $Self->GetOption('values-from-path');
    my $SkipMissing    = $Self->GetOption('skip-missing') || 0;

    my $SysConfigObject = $Kernel::OM->Get('Kernel::System::SysConfig');

    my @InvalidSettings = $SysConfigObject->ConfigurationInvalidList(
        Undeployed => 1,
        NoCache    => 1,
    );

    if ( !scalar @InvalidSettings ) {
        $Self->Print("<green>All settings are valid.</green>\n\n");

        $Self->Print("<green>Done.</green>\n") if !$NonInteractive;

        return $Self->ExitCodeOk();
    }

    my $MainObject = $Kernel::OM->Get('Kernel::System::Main');

    if ($SkipMissing) {
        $Self->Print("<yellow>Skipping missing settings for now...</yellow>\n\n");
    }

    my $TargetValues;
    if ($ValuesFromPath) {

        my $Content = $Kernel::OM->Get('Kernel::System::Main')->FileRead(
            Location => $ValuesFromPath,
        );
        if ( !$Content ) {
            $Self->PrintError("Could not read YAML source from '$ValuesFromPath'.");
            return $Self->ExitCodeError();
        }

        $TargetValues = $Kernel::OM->Get('Kernel::System::YAML')->Load( Data => ${$Content} );

        if ( !$TargetValues ) {
            $Self->PrintError('Could not parse YAML source.');
            return $Self->ExitCodeError();
        }
    }

    my @FixedSettings;
    my @NotFixedSettings;

    SETTING:
    for my $SettingName (@InvalidSettings) {
        my %Setting = $SysConfigObject->SettingGet(
            Name => $SettingName,
        );

        # If we have a target value use it if it's valid - otherwise use normal flow.
        # This also works for missing xml files and non-entity types.
        if (
            $TargetValues
            && $TargetValues->{$SettingName}
            && $Self->_TryUpdateSetting(
                SettingName => $SettingName,
                Value       => $TargetValues->{$SettingName},
            )
            )
        {
            push @FixedSettings, $SettingName;
            $Self->Print("<green>Corrected setting via input file:</green> $SettingName\n");

            next SETTING;
        }

        # Skip setting if the original XML file does not exist.
        if ($SkipMissing) {
            my $XMLFilename = $Setting{XMLFilename};
            my $FilePath    = join '/',
                $Kernel::OM->Get('Kernel::Config')->Get('Home'),
                'Kernel/Config/Files/XML',
                $XMLFilename;

            next SETTING if !( -e $FilePath );
        }

        my $EntityType = $Setting{XMLContentRaw} =~ s{ \A .*? ValueEntityType=" ( [^"]* ) " .*? \z }{$1}xmsr;

        # Skip settings that are not related to the Entities.
        if ( $Setting{XMLContentRaw} eq $EntityType ) {    # non-match
            $Self->PrintWarning("$SettingName is not an entity value type, skipping...");
            push @NotFixedSettings, $SettingName;
            next SETTING;
        }

        # Skip settings without ValueEntityType.
        if ( !$EntityType ) {
            $Self->PrintWarning("System was unable to determine ValueEntityType for $SettingName, skipping...");
            push @NotFixedSettings, $SettingName;
            next SETTING;
        }

        # Check if Entity module exists.
        my $Loaded = $MainObject->Require(
            "Kernel::System::SysConfig::ValueType::Entity::$EntityType",
            Silent => 1,
        );

        if ( !$Loaded ) {
            $Self->PrintWarning("Kernel::System::SysConfig::ValueType::Entity::$EntityType not found, skipping...");
            push @NotFixedSettings, $SettingName;
            next SETTING;
        }

        my @List = $Kernel::OM->Get("Kernel::System::SysConfig::ValueType::Entity::$EntityType")->EntityValueList();

        if ( !scalar @List ) {
            $Self->PrintWarning("$EntityType list is empty, skipping...");
            push @NotFixedSettings, $SettingName;
            next SETTING;
        }

        # Non-interactive.
        if ($NonInteractive) {

            next SETTING if !$Self->_TryUpdateSetting(
                SettingName      => $SettingName,
                Value            => $List[0],             # Take first available option.
                NotFixedSettings => \@NotFixedSettings,
            );

            push @FixedSettings, $SettingName;
            $Self->Print("<green>Auto-corrected setting:</green> $SettingName\n");

            next SETTING;
        }

        # Ask user.
        $Self->Print("\n<yellow>$SettingName is invalid, select one of the choices below:</yellow>\n");

        my $Index = 1;
        for my $Item (@List) {
            $Self->Print("    [$Index] $Item\n");
            $Index++;
        }

        my $SelectedIndex;
        while (
            !$SelectedIndex
            || !IsPositiveInteger($SelectedIndex)
            || $SelectedIndex > scalar @List
            )
        {
            $Self->Print("\nYour choice: ");
            $SelectedIndex = <STDIN>;    ## no critic

            # Remove white space.
            $SelectedIndex =~ s{\s}{}smx;
        }

        next SETTING if !$Self->_TryUpdateSetting(
            SettingName      => $SettingName,
            Value            => $List[ $SelectedIndex - 1 ],
            NotFixedSettings => \@NotFixedSettings,
        );

        push @FixedSettings, $SettingName;
    }

    if ( scalar @FixedSettings ) {

        my %Result = $SysConfigObject->ConfigurationDeploy(
            Comments      => 'FixInvalid - Automatically fixed invalid settings',
            NoValidation  => 1,
            UserID        => 1,
            Force         => 1,
            DirtySettings => \@FixedSettings,
        );

        if ( !$Result{Success} ) {
            $Self->PrintError('Deployment failed!');
            return $Self->ExitCodeError();
        }

        $Self->Print("\n<green>Deployment successful.</green>\n");
    }

    if ( scalar @NotFixedSettings ) {
        $Self->Print(
            "\nFollowing settings were not fixed:\n"
                . join( ",\n", map {"  - $_"} @NotFixedSettings ) . "\n"
                . "\nPlease use console command (bin/otrs.Console.pl Admin::Config::Update --help) or GUI to fix them.\n\n"
        );
    }

    $Self->Print("<green>Done.</green>\n") if !$NonInteractive;

    return $Self->ExitCodeOk();
}

sub PrintWarning {
    my ( $Self, $Message ) = @_;

    return $Self->Print("<yellow>Warning: $Message</yellow>\n");
}

sub _TryUpdateSetting {
    my ( $Self, %Param ) = @_;

    my $SysConfigObject = $Kernel::OM->Get('Kernel::System::SysConfig');

    my $ExclusiveLockGUID = $SysConfigObject->SettingLock(
        Name   => $Param{SettingName},
        Force  => 1,
        UserID => 1,
    );
    if ( !$ExclusiveLockGUID && $Param{NotFixedSettings} ) {
        $Self->PrintWarning("System was not able to lock the setting $Param{SettingName}, skipping...");
        push @{ $Param{NotFixedSettings} }, $Param{SettingName};
    }
    return if !$ExclusiveLockGUID;

    my %Update = $SysConfigObject->SettingUpdate(
        Name              => $Param{SettingName},
        IsValid           => 1,
        EffectiveValue    => $Param{Value},
        ExclusiveLockGUID => $ExclusiveLockGUID,
        UserID            => 1,
    );

    if ( !$Update{Success} && $Param{NotFixedSettings} ) {
        $Self->PrintWarning("System was not able to update the setting $Param{SettingName}, skipping...");
        push @{ $Param{NotFixedSettings} }, $Param{SettingName};
    }
    return if !$Update{Success};

    return 1;
}

1;