aboutsummaryrefslogtreecommitdiffstats
path: root/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/Step.java
blob: ae51c737fd2d80b0b2b8aa6439b8e90a926b72f8 (plain)
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
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controlloop.eventmanager;

import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import lombok.Getter;
import lombok.NonNull;
import org.onap.policy.controlloop.actorserviceprovider.Operation;
import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A single step within a single policy. The rules typically break a policy operation down
 * into separate steps. For instance, a policy for VF-Module-Create would be broken down
 * into lock target, A&AI tenant query, A&AI custom query, guard, and finally
 * VF-Module-Create.
 */
public class Step {
    private static final Logger logger = LoggerFactory.getLogger(Step.class);

    @Getter
    protected ControlLoopOperationParams params;

    /**
     * Time when the first step started for the current policy. This is shared by all
     * steps for the policy. When a step is started and finds this to be {@code null}, it
     * sets the value. Subsequent steps leave it unchanged.
     */
    private final AtomicReference<Instant> startTime;

    /**
     * {@code True} if this step is for the policy's actual operation, {@code false} if
     * it's a preprocessor step.
     */
    @Getter
    private final boolean policyStep;

    /**
     * The parent step from which this was constructed, or {@code null} if is was not
     * constructed from another step.
     */
    @Getter
    private final Step parentStep;

    /**
     * The operation for this step.
     */
    @Getter
    private Operation operation = null;

    /**
     * Used to cancel the running operation.
     */
    protected CompletableFuture<OperationOutcome> future;


    /**
     * Constructs the object. This is used when constructing the step for the policy's
     * actual operation.
     *
     * @param params operation parameters
     * @param startTime start time of the first step for the current policy, initially
     *        containing {@code null}
     */
    public Step(ControlLoopOperationParams params, @NonNull AtomicReference<Instant> startTime) {
        this.params = params;
        this.startTime = startTime;
        this.policyStep = true;
        this.parentStep = null;
    }

    /**
     * Constructs the object using information from another step. This is used when
     * constructing a preprocessing step.
     *
     * @param parentStep parent step whose information should be used
     * @param actor actor name
     * @param operation operation name
     */
    public Step(Step parentStep, String actor, String operation) {
        this.params = parentStep.params.toBuilder().actor(actor).operation(operation).retry(null).timeoutSec(null)
                        .payload(new LinkedHashMap<>()).build();
        this.startTime = parentStep.startTime;
        this.policyStep = false;
        this.parentStep = parentStep;
    }

    public String getActorName() {
        return params.getActor();
    }

    public String getOperationName() {
        return params.getOperation();
    }

    /**
     * Determines if the operation has been initialized (i.e., created).
     *
     * @return {@code true} if the operation has been initialized, {@code false} otherwise
     */
    public boolean isInitialized() {
        return (operation != null);
    }

    /**
     * Initializes the step, creating the operation if it has not yet been created.
     */
    public void init() {
        if (operation == null) {
            operation = buildOperation();
        }
    }

    /**
     * Starts the operation.
     *
     * @param remainingMs time remaining, in milliseconds, for the control loop
     * @return {@code true} if started, {@code false} if the step is no longer necessary
     *         (i.e., because it was previously completed)
     */
    public boolean start(long remainingMs) {
        if (!isInitialized()) {
            throw new IllegalStateException("step has not been initialized");
        }

        if (future != null) {
            throw new IllegalStateException("step is already running");
        }

        try {
            initStartTime();
            future = operation.start();

            // handle any exceptions that may be thrown, set timeout, and handle timeout

            // @formatter:off
            future.exceptionally(this::handleException)
                    .orTimeout(remainingMs, TimeUnit.MILLISECONDS)
                    .exceptionally(this::handleTimeout);
            // @formatter:on

        } catch (RuntimeException e) {
            handleException(e);
        }

        return true;
    }

    /**
     * Handles exceptions that may be generated.
     *
     * @param thrown exception that was generated
     * @return {@code null}
     */
    private OperationOutcome handleException(Throwable thrown) {
        if (thrown instanceof CancellationException || thrown.getCause() instanceof CancellationException) {
            return null;
        }

        logger.warn("{}.{}: exception starting operation for {}", params.getActor(), params.getOperation(),
                        params.getRequestId(), thrown);
        OperationOutcome outcome = new PipelineUtil(params).setOutcome(params.makeOutcome(), thrown);
        outcome.setStart(startTime.get());
        outcome.setEnd(Instant.now());
        outcome.setFinalOutcome(true);
        params.getCompleteCallback().accept(outcome);

        // this outcome is not used so just return "null"
        return null;
    }

    /**
     * Handles control loop timeout exception.
     *
     * @param thrown exception that was generated
     * @return {@code null}
     */
    private OperationOutcome handleTimeout(Throwable thrown) {
        logger.warn("{}.{}: control loop timeout for {}", params.getActor(), params.getOperation(),
                        params.getRequestId(), thrown);

        OperationOutcome outcome = new PipelineUtil(params).setOutcome(params.makeOutcome(), thrown);
        outcome.setActor(ActorConstants.CL_TIMEOUT_ACTOR);
        outcome.setOperation(null);
        outcome.setStart(startTime.get());
        outcome.setEnd(Instant.now());
        outcome.setFinalOutcome(true);
        params.getCompleteCallback().accept(outcome);

        // cancel the operation, if it's still running
        future.cancel(false);

        // this outcome is not used so just return "null"
        return null;
    }

    /**
     * Cancels the operation, if it's running.
     */
    public void cancel() {
        if (future != null) {
            future.cancel(false);
        }
    }

    /**
     * Initializes the start time, if it's still unset.
     */
    private void initStartTime() {
        if (startTime.get() == null) {
            startTime.set(Instant.now());
        }
    }

    /**
     * Gets the start time.
     *
     * @return the start time, or {@code null} if it hasn't been initialized yet
     */
    public Instant getStartTime() {
        return startTime.get();
    }

    /**
     * Builds the operation. The default method simply invokes
     * {@link ControlLoopOperationParams#build()}.
     *
     * @return a new operation
     */
    protected Operation buildOperation() {
        return params.build();
    }

    @Override
    public String toString() {
        return "Step(actor=" + getActorName() + ", operation=" + getOperationName() + ")";
    }
}