File: RequestRetry.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 (324 lines) | stat: -rw-r--r-- 11,087 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# --
# 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::GenericInterface::ErrorHandling::RequestRetry;

use strict;
use warnings;

use Kernel::System::VariableCheck qw(:all);

our @ObjectDependencies = (
    'Kernel::System::Log',
);

=head1 NAME

Kernel::GenericInterface::ErrorHandling::RequestRetry - Module do decide about rescheduling for failed requests

=head1 SYNOPSIS

=head1 PUBLIC INTERFACE

=over 4

=cut

=item new()

create an object. Do not create it directly, instead use:

    use Kernel::System::ObjectManager;
    local $Kernel::OM = Kernel::System::ObjectManager->new();
    my $ErrorObject = $Kernel::OM->Get('Kernel::GenericInterface::ErrorHandling');

=cut

sub new {
    my ( $Type, %Param ) = @_;

    # allocate new hash for object
    my $Self = {};
    bless( $Self, $Type );

    return $Self;
}

=item Run()

Decides if a non-successful request should be retried, based on the configuration.
Relevant module configuration variables are:
- ScheduleRetry         # enable or disable retry for request
- RetryIntervalStart    # time in seconds for first retry after initial request
- RetryIntervalFactor   # send further retries after the same interval as the first or in increasing intervals
- RetryIntervalMax      # maximum allowed interval between retries
- RetryCountMax         # maximum allowed number of retries
- RetryPeriodMax        # maximum time allowed for retries after initial request

    my $Result = $ErrorObject->Run(
        PastExecutionData => $PastExecutionDataStructure,   # optional
        ModuleConfig      => $ModuleConfig,
    );

    $Result = {
        Success       => 1,          # 0 or 1
        ErrorMessage  => '',         # if an error occurred
        Data          => { ... },    # result payload
        ReScheduleData => { ... },   # reschedule information
    };

=cut

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

    # Module config parameter validity check.
    if ( !IsHashRefWithData( $Param{ModuleConfig} ) ) {
        return $Self->_LogAndReturn( ErrorMessage => 'Got no ModuleConfig!' );
    }
    my $ModuleConfigCheck = $Self->_ModuleConfigCheck( %{ $Param{ModuleConfig} } );
    return $ModuleConfigCheck if !$ModuleConfigCheck->{Success};

    # Set basic information including possibly existing past execution data.
    my $RetryCount      = $Param{PastExecutionData}->{RetryCount} // 0;
    my $CurrentDateTime = $Kernel::OM->Create('Kernel::System::DateTime');

    # Get date-time of last (=this) request. If we are not in a retry, use current date-time.
    # This is used to properly calculate time based intervals.
    my $CurrentRequestDateTime;
    if ( IsStringWithData( $Param{PastExecutionData}->{RetryDateTime} ) ) {
        $CurrentRequestDateTime = $Kernel::OM->Create(
            'Kernel::System::DateTime',
            ObjectParams => {
                String => $Param{PastExecutionData}->{RetryDateTime},
            },
        );
        return $Self->_LogAndReturn( ErrorMessage => 'RetryDateTime is invalid!' ) if !$CurrentRequestDateTime;
    }
    else {
        $CurrentRequestDateTime = $CurrentDateTime->Clone();
    }

    # Get date-time of first request. If we are not in a retry, use current date-time.
    my $InitialRequestDateTime;
    if ( IsStringWithData( $Param{PastExecutionData}->{InitialRequestDateTime} ) ) {
        $InitialRequestDateTime = $Kernel::OM->Create(
            'Kernel::System::DateTime',
            ObjectParams => {
                String => $Param{PastExecutionData}->{InitialRequestDateTime},
            },
        );
        return $Self->_LogAndReturn( ErrorMessage => 'InitialRequestDateTime is invalid!' ) if !$InitialRequestDateTime;
    }
    else {
        $InitialRequestDateTime = $CurrentDateTime->Clone();
    }

    # Prepare default set of return data.
    my %ReturnData = (
        Success => 1,
        Data    => {
            ReSchedule                => 0,
            InitialRequestDateTime    => $InitialRequestDateTime->ToString(),
            CurrentRequestDateTime    => $CurrentRequestDateTime->ToString(),
            CurrentRetryCount         => $RetryCount,
            MaximumRetryCountReached  => 0,
            MaximumRetryPeriodReached => 0,
        },
        ReScheduleData => {
            ReSchedule => 0,
        },
    );

    # Retries are completely disabled.
    if ( !$Param{ModuleConfig}->{ScheduleRetry} ) {
        return \%ReturnData;
    }

    # No retry if maximum retry count has been reached.
    if (
        $Param{ModuleConfig}->{RetryCountMax}
        && $RetryCount >= $Param{ModuleConfig}->{RetryCountMax}
        )
    {
        $ReturnData{Data}->{MaximumRetryCountReached} = 1;
        return \%ReturnData;
    }

    # No retry if maximum retry period has been reached.
    my $DeltaInitialToCurrentRequest;
    if ( $Param{ModuleConfig}->{RetryPeriodMax} ) {
        $DeltaInitialToCurrentRequest = $InitialRequestDateTime->Delta( DateTimeObject => $CurrentRequestDateTime );
        if ( $DeltaInitialToCurrentRequest->{AbsoluteSeconds} >= $Param{ModuleConfig}->{RetryPeriodMax} ) {
            $ReturnData{Data}->{MaximumRetryPeriodReached} = 1;
            return \%ReturnData;
        }
    }

    # Calculate interval for next execution.
    my $RetryInterval;
    if ( IsStringWithData( $Param{PastExecutionData}->{RetryInterval} ) ) {
        $RetryInterval
            = int( $Param{PastExecutionData}->{RetryInterval} * $Param{ModuleConfig}->{RetryIntervalFactor} );
        if (
            IsStringWithData( $Param{ModuleConfig}->{RetryIntervalMax} )
            && $RetryInterval > $Param{ModuleConfig}->{RetryIntervalMax}
            )
        {
            $RetryInterval = $Param{ModuleConfig}->{RetryIntervalMax};
        }
    }
    else {
        $RetryInterval = $Param{ModuleConfig}->{RetryIntervalStart};
    }

    # Calculate next execution timestamp.
    my $TargetDateTime;
    if ( $Param{ModuleConfig}->{RetryPeriodMax} ) {
        if ( !$DeltaInitialToCurrentRequest ) {
            $DeltaInitialToCurrentRequest = $InitialRequestDateTime->Delta( DateTimeObject => $CurrentRequestDateTime );
        }
        if (
            $DeltaInitialToCurrentRequest->{AbsoluteSeconds} + $RetryInterval
            >= $Param{ModuleConfig}->{RetryPeriodMax}
            )
        {
            $TargetDateTime = $InitialRequestDateTime->Clone();
            $TargetDateTime->Add( Seconds => $Param{ModuleConfig}->{RetryPeriodMax} );
        }
    }
    if ( !$TargetDateTime ) {
        $TargetDateTime = $CurrentRequestDateTime->Clone();
        $TargetDateTime->Add( Seconds => $RetryInterval );
    }

    # Even after delayed executions, minimum wait time after requests is 1 second to prevent possible DoS.
    if ( $TargetDateTime->Compare( DateTimeObject => $CurrentDateTime ) != 1 ) {
        $TargetDateTime = $CurrentDateTime->Clone();
        $TargetDateTime->Add( Seconds => 1 );
    }

    # Schedule retry and set appropriate past execution data.
    $ReturnData{Data}->{ReSchedule} = 1;
    return {
        %ReturnData,
        ReScheduleData => {
            ReSchedule        => 1,
            ExecutionTime     => $TargetDateTime->ToString(),
            PastExecutionData => {
                InitialRequestDateTime => $InitialRequestDateTime->ToString(),
                RetryCount             => ++$RetryCount,
                RetryInterval          => $RetryInterval,
                RetryDateTime          => $TargetDateTime->ToString(),
            },
        },
    };
}

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

    # Allowed Values:
    # ScheduleRetry       => [            0, 1 ],
    # RetryIntervalFactor => [               1, 1.5, 2 ],
    # RetryIntervalStart  => [            0, 1 .. 999999 ],
    # RetryIntervalMax    => [ undef, '', 0, 1 .. 999999 ],
    # RetryCountMax       => [ undef, '',    1 .. 999999 ],
    # RetryPeriodMax      => [ undef, '',    1 .. 999999 ],

    STRINGWITHDATA:
    for my $StringWithData (qw(ScheduleRetry RetryIntervalStart RetryIntervalFactor)) {
        next STRINGWITHDATA if IsStringWithData( $Param{$StringWithData} );

        return $Self->_LogAndReturn( ErrorMessage => "Config param '$StringWithData' is not a non-empty string!" );
    }

    STRING:
    for my $String (qw(RetryIntervalMax RetryCountMax RetryPeriodMax)) {

        # Set fall-back for optional parameters.
        $Param{$String} //= '';

        next STRING if IsString( $Param{$String} );

        return $Self->_LogAndReturn( ErrorMessage => "Config param '$String' is not a string!" );
    }

    if (
        $Param{ScheduleRetry} ne '0'
        && $Param{ScheduleRetry} ne '1'
        )
    {
        return $Self->_LogAndReturn( ErrorMessage => "Config param 'ScheduleRetry' is not '0' or '1'!" );
    }

    if (
        $Param{RetryIntervalFactor} ne '1'
        && $Param{RetryIntervalFactor} ne '1.5'
        && $Param{RetryIntervalFactor} ne '2'
        )
    {
        return $Self->_LogAndReturn( ErrorMessage => "Config param 'RetryIntervalFactor' is not '1', '1.5' or '2'!" );
    }

    my %ParamToMessage = (
        RetryIntervalStart => "Config param 'RetryIntervalStart' is not '0' or a positive integer!",
        RetryIntervalMax   => "Config param 'RetryIntervalMax' is not empty, '0' or a positive integer!",
        RetryCountMax      => "Config param 'RetryCountMax' is not empty or a positive integer!",
        RetryPeriodMax     => "Config param 'RetryPeriodMax' is not empty or a positive integer!",
    );
    INTEGER:
    for my $Integer (qw(RetryIntervalStart RetryIntervalMax RetryCountMax RetryPeriodMax)) {

        # RetryIntervalStart is not optional but string length >0 has been checked already.
        next INTEGER if $Param{$Integer} eq '';

        next INTEGER if IsPositiveInteger( $Param{$Integer} );

        # RetryIntervalStart and RetryIntervalMax may also contain '0'.
        if ( $Integer eq 'RetryIntervalStart' || $Integer eq 'RetryIntervalMax' ) {
            next INTEGER if $Param{$Integer} eq '0';
        }

        return $Self->_LogAndReturn( ErrorMessage => $ParamToMessage{$Integer} );
    }

    return {
        Success => 1,
    };
}

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

    my $ErrorMessage = $Param{ErrorMessage} || 'No error message provided!';

    $Kernel::OM->Get('Kernel::System::Log')->Log(
        Priority => 'error',
        Message  => $ErrorMessage,
    );

    return {
        Success      => 0,
        ErrorMessage => $ErrorMessage,
    };
}

1;

=back

=head1 TERMS AND CONDITIONS

This software is part of the OTRS project (L<https://otrs.org/>).

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 L<https://www.gnu.org/licenses/gpl-3.0.txt>.

=cut