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