ccb57305af844e8c50b123cffdec419a4476affc
[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_INSTANCE_ID;
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 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
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                 new Date(System.currentTimeMillis()).toInstant(),
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     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     void clearRequestLogProperties() {
145         try {
146             MDC.remove(MDC_KEY_REQUEST_ID);
147             MDC.remove(MDC_SERVICE_INSTANCE_ID);
148             MDC.remove(MDC_SERVICE_NAME);
149             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
150             MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY);
151         } catch (Exception e) {
152             logger.error("Unable to clear the Request Log properties" + e.getMessage());
153         }
154     }
155
156     /**
157      * Reset MDC log properties based on passed in condition. does:<br>
158      *   - persist existing MDC setting and set my MDC log properties <br>
159      *   - or re-apply persisted MDC log properties
160      * @param useMdcMap boolean to indicate whether to persist the existing MDC setting and set my MDC log properties,
161      *                  or to re-apply the persisted MDC log properties.
162      */
163     void resetLogProperties(boolean useMdcMap) {
164         if (useMdcMap) {
165             for (Map.Entry<String, String> aEntry : oldMdcContent.entrySet()) {
166                 MDC.put(aEntry.getKey(), aEntry.getValue());
167             }
168             return;
169         }
170
171         // persist existing log properties and set my log properties
172         oldMdcContent.clear();
173         for (String key : MDC_KEYS) {
174             String value = MDC.get(key);
175             if (value != null) {
176                 oldMdcContent.put(key, value);
177             }
178         }
179         setInitialLogProperties();
180     }
181
182     /**
183      * Set class <b>status</b> by calling setStatus(OAMCommandStatus, Params) with null paramter.
184      * @see #setStatus(OAMCommandStatus, String)
185      *
186      * @param oamCommandStatus of the to be set new state
187      */
188     void setStatus(OAMCommandStatus oamCommandStatus) {
189         setStatus(oamCommandStatus, null);
190     }
191
192     /**
193      * Create Status based on the passed in parameter, then set the class <b>status</b> with it.
194      *
195      * @param oamCommandStatus of the current OAM command status
196      * @param message to be set in the new status
197      */
198     void setStatus(OAMCommandStatus oamCommandStatus, String message) {
199         Params params = new Params().addParam("errorMsg", message);
200
201         StatusBuilder statusBuilder = new StatusBuilder();
202         statusBuilder.setCode(oamCommandStatus.getResponseCode());
203         if (params != null) {
204             statusBuilder.setMessage(oamCommandStatus.getFormattedMessage(params));
205         } else {
206             statusBuilder.setMessage(oamCommandStatus.getResponseMessage());
207         }
208
209         status = statusBuilder.build();
210     }
211
212     /**
213      * Set class <b>status</b> with error status calculated from the passed in paremeter
214      * and audit log the error message.
215      * @param t of the error Throwable.
216      */
217     void setErrorStatus(Throwable t) {
218         resetLogProperties(false);
219
220         final String appName = configurationHelper.getAppcName();
221         String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString();
222
223         OAMCommandStatus oamCommandStatus;
224         String errorMessage;
225         if (t instanceof InvalidInputException) {
226             oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER;
227             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_INVALID_INPUT, t.getMessage());
228         } else if (t instanceof InvalidStateException) {
229             exceptionMessage = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT,
230                     rpc.getAppcOperation(), appName, stateHelper.getCurrentOamState());
231             oamCommandStatus = OAMCommandStatus.REJECTED;
232             errorMessage = EELFResourceManager.format(Msg.INVALID_STATE_TRANSITION, exceptionMessage);
233         } else {
234             oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR;
235             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t,
236                     appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage);
237         }
238
239         setStatus(oamCommandStatus, exceptionMessage);
240
241         LoggingUtils.logErrorMessage(
242                 String.valueOf(status.getCode()),
243                 status.getMessage(),
244                 LoggingConstants.TargetNames.APPC,
245                 LoggingConstants.TargetNames.APPC_OAM_PROVIDER,
246                 errorMessage,
247                 AppcOam.class.getCanonicalName());
248
249         resetLogProperties(true);
250     }
251
252     /**
253      * Genral debug log when debug logging level is enabled.
254      * @param message of the log message format
255      * @param args of the objects listed in the message format
256      */
257     void logDebug(String message, Object... args) {
258         if (logger.isDebugEnabled()) {
259             logger.debug(String.format(message, args));
260         }
261     }
262 }