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