serializing OAM async task
[appc.git] / appc-oam / appc-oam-bundle / src / main / java / org / openecomp / appc / oam / processor / BaseCommon.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.oam.processor;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.i18n.EELFResourceManager;
29 import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader;
30 import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.Status;
31 import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.StatusBuilder;
32 import org.openecomp.appc.exceptions.InvalidInputException;
33 import org.openecomp.appc.exceptions.InvalidStateException;
34 import org.openecomp.appc.executor.objects.Params;
35 import org.openecomp.appc.i18n.Msg;
36 import org.openecomp.appc.logging.LoggingConstants;
37 import org.openecomp.appc.logging.LoggingUtils;
38 import org.openecomp.appc.oam.AppcOam;
39 import org.openecomp.appc.oam.OAMCommandStatus;
40 import org.openecomp.appc.oam.util.ConfigurationHelper;
41 import org.openecomp.appc.oam.util.OperationHelper;
42 import org.openecomp.appc.oam.util.StateHelper;
43 import org.slf4j.MDC;
44
45 import java.net.InetAddress;
46 import java.util.Arrays;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51
52 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
53 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
54 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
55 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
56 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
57
58 /**
59  * Common handling methods of <br>
60  *     - BaseProcessor (for REST sync handling) <br>
61  *     - BaseActionRunnable (for REST async handling)
62  */
63 public abstract class BaseCommon {
64     final EELFLogger logger;
65     final ConfigurationHelper configurationHelper;
66     final StateHelper stateHelper;
67     final OperationHelper operationHelper;
68
69     Status status;
70     Date startTime;
71
72     AppcOam.RPC rpc;
73     CommonHeader commonHeader;
74
75     private final List<String> MDC_KEYS = Arrays.asList(
76         LoggingConstants.MDCKeys.PARTNER_NAME,
77         LoggingConstants.MDCKeys.SERVER_NAME,
78         MDC_INSTANCE_UUID,
79         MDC_KEY_REQUEST_ID,
80         MDC_SERVER_FQDN,
81         MDC_SERVER_IP_ADDRESS,
82         MDC_SERVICE_NAME
83     );
84     private Map<String, String> oldMdcContent = new HashMap<>();
85
86     /**
87      * Constructor
88      *
89      * @param eelfLogger            for logging
90      * @param configurationHelperIn for property reading
91      * @param stateHelperIn         for APP-C OAM state checking
92      * @param operationHelperIn for operational helper
93      */
94     BaseCommon(EELFLogger eelfLogger,
95                ConfigurationHelper configurationHelperIn,
96                StateHelper stateHelperIn,
97                OperationHelper operationHelperIn) {
98         logger = eelfLogger;
99         configurationHelper = configurationHelperIn;
100         stateHelper = stateHelperIn;
101         operationHelper = operationHelperIn;
102     }
103
104     /**
105      * Audit log the passed in message at INFO level.
106      * @param msg the Msg to be audit logged.
107      */
108     void auditInfoLog(Msg msg) {
109         LoggingUtils.auditInfo(startTime.toInstant(),
110                 new Date(System.currentTimeMillis()).toInstant(),
111             String.valueOf(status.getCode()),
112             status.getMessage(),
113             getClass().getCanonicalName(),
114             msg,
115             configurationHelper.getAppcName(),
116             stateHelper.getCurrentOamState().toString()
117         );
118     }
119
120     /**
121      * Set MDC properties.
122      */
123     public final void setInitialLogProperties() {
124         MDC.put(MDC_KEY_REQUEST_ID, commonHeader.getRequestId());
125         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, commonHeader.getOriginatorId());
126         MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future
127         MDC.put(MDC_SERVICE_NAME, rpc.name());
128         try {
129             //!!!Don't change the following to a .getHostName() again please. It's wrong!MDC.put(MDC_SERVER_FQDN,
130             // InetAddress.getLocalHost().getCanonicalHostName());
131             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
132             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
133             MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
134         } catch (Exception e) {
135             logger.error("MDC constant error", e);
136         }
137     }
138
139     /**
140      * Clear MDC properties.
141      */
142     public final void clearRequestLogProperties() {
143         for (String key : MDC_KEYS) {
144             try {
145                 MDC.remove(key);
146             } catch (Exception e) {
147                 logger.error(
148                     String.format("Unable to clear the Log properties (%s) due to exception: %s", key, e.getMessage()));
149             }
150         }
151     }
152
153     /**
154      * Reset MDC log properties based on passed in condition. does:<br>
155      *   - persist existing MDC setting and set my MDC log properties <br>
156      *   - or re-apply persisted MDC log properties
157      * @param useMdcMap boolean to indicate whether to persist the existing MDC setting and set my MDC log properties,
158      *                  or to re-apply the persisted MDC log properties.
159      */
160     void resetLogProperties(boolean useMdcMap) {
161         if (useMdcMap) {
162             for (Map.Entry<String, String> aEntry : oldMdcContent.entrySet()) {
163                 MDC.put(aEntry.getKey(), aEntry.getValue());
164             }
165             return;
166         }
167
168         // persist existing log properties and set my log properties
169         oldMdcContent.clear();
170         for (String key : MDC_KEYS) {
171             String value = MDC.get(key);
172             if (value != null) {
173                 oldMdcContent.put(key, value);
174             }
175         }
176         setInitialLogProperties();
177     }
178
179     /**
180      * Set class <b>status</b> by calling setStatus(OAMCommandStatus, Params) with null paramter.
181      * @see #setStatus(OAMCommandStatus, String)
182      *
183      * @param oamCommandStatus of the to be set new state
184      */
185     void setStatus(OAMCommandStatus oamCommandStatus) {
186         setStatus(oamCommandStatus, null);
187     }
188
189     /**
190      * Create Status based on the passed in parameter, then set the class <b>status</b> with it.
191      *
192      * @param oamCommandStatus of the current OAM command status
193      * @param message to be set in the new status
194      */
195     void setStatus(OAMCommandStatus oamCommandStatus, String message) {
196         Params params = new Params().addParam("errorMsg", message);
197
198         StatusBuilder statusBuilder = new StatusBuilder();
199         statusBuilder.setCode(oamCommandStatus.getResponseCode());
200         if (params != null) {
201             statusBuilder.setMessage(oamCommandStatus.getFormattedMessage(params));
202         } else {
203             statusBuilder.setMessage(oamCommandStatus.getResponseMessage());
204         }
205
206         status = statusBuilder.build();
207     }
208
209     /**
210      * Set class <b>status</b> with error status calculated from the passed in paremeter
211      * and audit log the error message.
212      * @param t of the error Throwable.
213      */
214     void setErrorStatus(Throwable t) {
215         resetLogProperties(false);
216
217         final String appName = configurationHelper.getAppcName();
218         String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString();
219
220         OAMCommandStatus oamCommandStatus;
221         String errorMessage;
222         if (t instanceof InvalidInputException) {
223             oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER;
224             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_INVALID_INPUT, t.getMessage());
225         } else if (t instanceof InvalidStateException) {
226             exceptionMessage = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT,
227                 rpc.getAppcOperation(), appName, stateHelper.getCurrentOamState());
228             oamCommandStatus = OAMCommandStatus.REJECTED;
229             errorMessage = EELFResourceManager.format(Msg.INVALID_STATE_TRANSITION, exceptionMessage);
230         } else {
231             oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR;
232             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t,
233                 appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage);
234         }
235
236         setStatus(oamCommandStatus, exceptionMessage);
237
238         LoggingUtils.logErrorMessage(
239             String.valueOf(status.getCode()),
240             status.getMessage(),
241             LoggingConstants.TargetNames.APPC,
242             LoggingConstants.TargetNames.APPC_OAM_PROVIDER,
243             errorMessage,
244             AppcOam.class.getCanonicalName());
245
246         resetLogProperties(true);
247     }
248
249     /**
250      * Genral debug log when debug logging level is enabled.
251      * @param message of the log message format
252      * @param args of the objects listed in the message format
253      */
254     void logDebug(String message, Object... args) {
255         if (logger.isDebugEnabled()) {
256             logger.debug(String.format(message, args));
257         }
258     }
259 }