OAM operations 2 - oam
[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.Date;
47
48 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
49 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
50 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
51 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
52 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
53 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
54
55 /**
56  * Common handling methods of <br>
57  *     - BaseProcessor (for REST sync handling) <br>
58  *     - BaseActionRunnable (for REST async handling)
59  */
60 abstract class BaseCommon {
61     final EELFLogger logger;
62     final ConfigurationHelper configurationHelper;
63     final StateHelper stateHelper;
64     final OperationHelper operationHelper;
65
66     Status status;
67     Date startTime;
68
69     AppcOam.RPC rpc;
70     CommonHeader commonHeader;
71
72     /**
73      * Constructor
74      *
75      * @param eelfLogger            for logging
76      * @param configurationHelperIn for property reading
77      * @param stateHelperIn         for APP-C OAM state checking
78      * @param operationHelperIn for operational helper
79      */
80     BaseCommon(EELFLogger eelfLogger,
81                ConfigurationHelper configurationHelperIn,
82                StateHelper stateHelperIn,
83                OperationHelper operationHelperIn) {
84         logger = eelfLogger;
85         configurationHelper = configurationHelperIn;
86         stateHelper = stateHelperIn;
87         operationHelper = operationHelperIn;
88     }
89
90     /**
91      * Audit log the passed in message at INFO level.
92      * @param msg the Msg to be audit logged.
93      */
94     void auditInfoLog(Msg msg) {
95         LoggingUtils.auditInfo(startTime.toInstant(),
96                 new Date(System.currentTimeMillis()).toInstant(),
97                 String.valueOf(status.getCode()),
98                 status.getMessage(),
99                 getClass().getCanonicalName(),
100                 msg,
101                 configurationHelper.getAppcName(),
102                 stateHelper.getCurrentOamState().toString()
103         );
104     }
105
106     /**
107      * Set MDC properties.
108      */
109     void setInitialLogProperties() {
110         MDC.put(MDC_KEY_REQUEST_ID, commonHeader.getRequestId());
111         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, commonHeader.getOriginatorId());
112         MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future
113         MDC.put(MDC_SERVICE_NAME, rpc.name());
114         try {
115             //!!!Don't change the following to a .getHostName() again please. It's wrong!MDC.put(MDC_SERVER_FQDN,
116             // InetAddress.getLocalHost().getCanonicalHostName());
117             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
118             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
119             MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
120         } catch (Exception e) {
121             logger.error("MDC constant error", e);
122         }
123     }
124
125     /**
126      * Clear MDC properties.
127      */
128     void clearRequestLogProperties() {
129         try {
130             MDC.remove(MDC_KEY_REQUEST_ID);
131             MDC.remove(MDC_SERVICE_INSTANCE_ID);
132             MDC.remove(MDC_SERVICE_NAME);
133             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
134             MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY);
135         } catch (Exception e) {
136             logger.error("Unable to clear the Request Log properties" + e.getMessage());
137         }
138     }
139
140     /**
141      * Set class <b>status</b> by calling setStatus(OAMCommandStatus, Params) with null paramter.
142      * @see #setStatus(OAMCommandStatus, String)
143      *
144      * @param oamCommandStatus of the to be set new state
145      */
146     void setStatus(OAMCommandStatus oamCommandStatus) {
147         setStatus(oamCommandStatus, null);
148     }
149
150     /**
151      * Create Status based on the passed in parameter, then set the class <b>status</b> with it.
152      *
153      * @param oamCommandStatus of the current OAM command status
154      * @param message to be set in the new status
155      */
156     void setStatus(OAMCommandStatus oamCommandStatus, String message) {
157         Params params = new Params().addParam("errorMsg", message);
158
159         StatusBuilder statusBuilder = new StatusBuilder();
160         statusBuilder.setCode(oamCommandStatus.getResponseCode());
161         if (params != null) {
162             statusBuilder.setMessage(oamCommandStatus.getFormattedMessage(params));
163         } else {
164             statusBuilder.setMessage(oamCommandStatus.getResponseMessage());
165         }
166
167         status = statusBuilder.build();
168     }
169
170     /**
171      * Set class <b>status</b> with error status calculated from the passed in paremeter
172      * and audit log the error message.
173      * @param t of the erro Throwable.
174      */
175     void setErrorStatus(Throwable t) {
176         final String appName = configurationHelper.getAppcName();
177         String exceptionMessage = t.getMessage() != null ? t.getMessage() : t.toString();
178
179         OAMCommandStatus oamCommandStatus;
180         String errorMessage;
181         if (t instanceof InvalidInputException) {
182             oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER;
183             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_INVALID_INPUT, t.getMessage());
184         } else if (t instanceof InvalidStateException) {
185             exceptionMessage = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT,
186                     rpc.getAppcOperation(), appName, stateHelper.getCurrentOamState());
187             oamCommandStatus = OAMCommandStatus.REJECTED;
188             errorMessage = EELFResourceManager.format(Msg.INVALID_STATE_TRANSITION, exceptionMessage);
189         } else {
190             oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR;
191             errorMessage = EELFResourceManager.format(Msg.OAM_OPERATION_EXCEPTION, t,
192                     appName, t.getClass().getSimpleName(), rpc.name(), exceptionMessage);
193         }
194
195         setStatus(oamCommandStatus, exceptionMessage);
196
197         LoggingUtils.logErrorMessage(
198                 String.valueOf(status.getCode()),
199                 status.getMessage(),
200                 LoggingConstants.TargetNames.APPC,
201                 LoggingConstants.TargetNames.APPC_OAM_PROVIDER,
202                 errorMessage,
203                 AppcOam.class.getCanonicalName());
204     }
205
206     /**
207      * Genral debug log when debug logging level is enabled.
208      * @param message of the log message format
209      * @param args of the objects listed in the message format
210      */
211     void logDebug(String message, Object... args) {
212         if (logger.isDebugEnabled()) {
213             logger.debug(String.format(message, args));
214         }
215     }
216 }