summaryrefslogtreecommitdiffstats
path: root/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/processor/BaseActionRunnable.java
blob: 542e53d639dc0034377df5a1381327726223a561 (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
265
266
/*-
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Copyright (C) 2017 Amdocs
 * =============================================================================
 * 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.
 * 
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.appc.oam.processor;

import org.openecomp.appc.i18n.Msg;
import org.openecomp.appc.oam.AppcOam;
import org.openecomp.appc.oam.OAMCommandStatus;
import org.openecomp.appc.statemachine.impl.readers.AppcOamStates;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * Base runnable actions for OAM APIs, such as maintenance mode, restart, start and stop API.
 *
 * <p>This class holds the general action async handling methods for all OAM APIs.
 * <p>Specific API action runnable will overwrite the general methods to add specific behaviors.
 *
 * <p>Subclass constructor must set the following class variables:
 *   <br>  - actionName
 *   <br>  - auditMsg
 *   <br>  - finalState
 */
public abstract class BaseActionRunnable extends BaseCommon implements Runnable {
    final String OAM_OPERATION_TIMEOUT_SECOND = "appc.OAM.api.timeout";
    /** Default operation tiemout set to 1 minute */
    final int DEFAULT_OAM_OPERATION_TIMEOUT = 60;
    /** Abort due to rejection message format with flexible operation name */
    final String ABORT_MESSAGE_FORMAT = "Aborting %s operation due to %s.";
    /** Timeout message format with flexible operation name */
    final String TIMEOUT_MESSAGE_FORMAT = "%s operation has reached timeout %d milliseconds.";
    /** Failure message format with flexible number of bundles */
    final String BUNDLE_OPERATION_FAILED_FORMAT = "%d bundle(s) failed, see logs for details.";
    final String NEW_RPC_OPERATION_REQUEST = "new %s operation request";
    final String DUE_TO_EXECUTION_ERROR = "due to execution error.";

    private boolean isWaiting = false;
    private AppcOamStates currentState;
    long startTimeMs = 0;
    long timeoutMs = 0;
    boolean doTimeoutChecking = false;

    String actionName = "Need to be reset";
    Msg auditMsg;
    AppcOamStates finalState;

    BaseProcessor myParent;
    Map<String, Future<?>> bundleNameToFuture = new HashMap<>();

    /**
     * Constructor
     *
     * @param parent BaseProcessor who has called this constructor.
     */
    BaseActionRunnable(BaseProcessor parent) {
        super(parent.logger, parent.configurationHelper, parent.stateHelper, parent.operationHelper);

        rpc = parent.rpc;
        commonHeader = parent.commonHeader;
        startTime = parent.startTime;
        myParent = parent;

        setTimeoutValues();
    }

    /**
     * Set timeout in milliseconds
     */
    void setTimeoutValues() {
        Integer timeoutSeconds = myParent.timeoutSeconds;
        if (timeoutSeconds == null) {
            timeoutMs = configurationHelper.getConfig().getIntegerProperty(
                    OAM_OPERATION_TIMEOUT_SECOND, DEFAULT_OAM_OPERATION_TIMEOUT) * 1000;
        } else {
            timeoutMs = timeoutSeconds.longValue() * 1000;
        }

        doTimeoutChecking = timeoutMs != 0;
        if (doTimeoutChecking) {
            startTimeMs = startTime.getTime();
        }
        logDebug("%s action runnable check timeout (%s) with timeout (%d)ms, and startMs (%d)",
                rpc.name(), Boolean.toString(doTimeoutChecking), timeoutMs, startTimeMs);
    }

    /**
     * Abort operation handling due to outside interruption, does<br>
     *     - set ABORT status<br>
     *     - send notification message<br>
     *     - add audit log
     *
     * @param newRpc of the new AppcOam.RPC operation.
     */
    public void abortRunnable(final AppcOam.RPC newRpc) {
        resetLogProperties(false);

        String additionalMsg = String.format(NEW_RPC_OPERATION_REQUEST, newRpc);
        logDebug("%s action aborted due to %s", rpc.name(), additionalMsg);
        setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), additionalMsg));
        operationHelper.sendNotificationMessage(rpc, commonHeader, status);
        auditInfoLog(auditMsg);

        resetLogProperties(true);
    }

    @Override
    public void run() {
        try {
            setInitialLogProperties();
            logDebug(String.format("===========in %s run (waiting: %s)=======",
                    actionName, Boolean.toString(isWaiting)));

            if (isWaiting) {
                if (!checkState()) {
                    keepWaiting();
                }
            } else {
                if (doAction()) {
                    isWaiting = !checkState();
                } else {
                    postDoAction(false);
                }
            }
        } catch (Exception e) {
            logDebug(String.format("%s got exception %s", actionName, e.getMessage()));
            logger.error(actionName + " exception", e);

        } finally {
            clearRequestLogProperties();
        }
    }

    /**
     * Keep waiting to be override by children classes for different behaviors.
     * Timeout is validated here.
     */
    void keepWaiting() {
        logDebug(String.format("%s runnable waiting, current state is %s.",
                actionName, currentState == null ? "null" : currentState.toString()));

        isTimeout("keepWaiting");
    }

    /**
     * Check if the timeout milliseconds has reached.
     *
     * @param parentName String of the caller, for logging purpose.
     * @return true if the timeout has reached, otherwise false.
     */
    boolean isTimeout(String parentName) {
        logDebug(String.format("%s task isTimeout called from %s", actionName, parentName));
        if (doTimeoutChecking
                && System.currentTimeMillis() - startTimeMs > timeoutMs) {
            logger.error(String.format("%s operation timeout (%d) ms has reached, abort with error state.",
                    actionName, timeoutMs));

            setStatus(OAMCommandStatus.TIMEOUT, String.format(TIMEOUT_MESSAGE_FORMAT, rpc.name(), timeoutMs));
            postAction(AppcOamStates.Error);
            return true;
        }
        return false;
    }

    /**
     * Check if all bundle operations are successful through BundleHelper.
     * If there's failed bundler operation, set error status and trigger postAction with Error state.
     *
     * @return true if bundler operations have failure, otherwise false.
     */
    boolean hasBundleOperationFailure() {
        long failedTask = myParent.bundleHelper.getFailedMetrics(bundleNameToFuture);
        if (failedTask == 0) {
            return false;
        }

        setStatus(OAMCommandStatus.UNEXPECTED_ERROR, String.format(BUNDLE_OPERATION_FAILED_FORMAT, failedTask));
        postAction(AppcOamStates.Error);
        return true;
    }

    /**
     * Set class <b>status</b> to ABORT with abort message.
     */
    void setAbortStatus() {
        setStatus(OAMCommandStatus.ABORT, String.format(ABORT_MESSAGE_FORMAT, rpc.name(), DUE_TO_EXECUTION_ERROR));
    }

    /**
     * Final handling. The thread is cancelled.
     *
     * @param setState boolean to indicate if set OAM state or not
     */
    void postDoAction(boolean setState) {
        logDebug(String.format("Finished %s task", actionName));
    }

    /**
     * Handling for after doAction. does post notification, issue audit log and set OAM state based on input.
     *
     * @param state of AppcOamState to be set as OAM state when it is not null.
     */
    void postAction(AppcOamStates state) {
        operationHelper.sendNotificationMessage(rpc, commonHeader, status);

        if (state != null) {
            stateHelper.setState(state);
        }

        auditInfoLog(auditMsg);

        myParent.cancelAsyncTask();
    }

    /**
     * Check state
     *
     * @return true if final state reached, otherwise return false
     */
    boolean checkState() {
        if (isTimeout("checkState")) {
            myParent.bundleHelper.cancelUnfinished(bundleNameToFuture);
            return true;
        }

        if (!myParent.bundleHelper.isAllTaskDone(bundleNameToFuture)) {
            return false;
        }

        if (hasBundleOperationFailure()) {
            return true;
        }

        currentState = stateHelper.getBundlesState();
        if (currentState == finalState) {
            setStatus(OAMCommandStatus.SUCCESS);
            postDoAction(true);
            return true;
        }
        return false;
    }

    abstract boolean doAction();
}