aboutsummaryrefslogtreecommitdiffstats
path: root/common/onap-sdc-artifact-generator-lib/onap-sdc-artifact-generator-core/src/main/java/org/onap/sdc/generator/util/ArtifactGeneratorUtil.java
blob: afb61f873b770daa64449ccf7c82705738210499 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.sdc.generator.util;

import org.onap.sdc.generator.data.Artifact;
import org.onap.sdc.generator.logging.ArtifactGeneratorLogResponseCode;
import org.onap.sdc.generator.logging.CategoryLogLevel;
import org.onap.sdc.generator.logging.StatusCode;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.slf4j.MDC;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import static org.onap.sdc.generator.data.GeneratorConstants.*;
import static org.onap.sdc.generator.logging.ArtifactGeneratorLogResponseCode.*;


public class ArtifactGeneratorUtil {

  private static Logger log = LoggerFactory.getLogger(ArtifactGeneratorUtil.class.getName());
  private static final String LOG_UTC_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";

  /**
   * Artifact Generator Error logging Helper.
   * @param errorDescription Description of the error
   */
  public static void logError(String errorDescription) {
    logError(errorDescription, "");
  }

  /**
   * Artifact Generator Error logging Helper.
   * @param errorDescription Description of the error
   * @param ex Exception object for stackstrace
   */
  public static void logError(String errorDescription, Exception ex) {
    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    String detailMessage = sw.toString();
    logError(CategoryLogLevel.ERROR, errorDescription, detailMessage);
  }

  /**
   * Artifact Generator Error logging Helper.
   * @param errorDescription Description of the error
   * @param detailMessage Detailed Error message
   */
  public static void logError(String errorDescription, String detailMessage) {
    logError(CategoryLogLevel.ERROR, errorDescription, detailMessage);
  }

  /**
   * Artifact Generator Error logging Helper.
   * @param errorCategory    ERROR
   * @param errorDescription Description of the error
   * @param detailMessage Detailed Error message
   */
  public static void logError(CategoryLogLevel errorCategory,
                              String errorDescription, String detailMessage) {
    MDC.put(ERROR_CATEGORY, errorCategory.name());
    MDC.put(STATUS_CODE, StatusCode.ERROR.name());
    artifactGeneratorErrorLogProcessor(errorCategory,errorDescription);
    log.error(detailMessage);
    resetLoggingContext();
  }

  /**
   * Initialize generic MDC attributes for logging the current request.
   *
   */
  public static void initializeLoggingContext() {
    log.debug("Initializing generic logging context ");
    MDC.put(PARTNER_NAME, GENERATOR_PARTNER_NAME);
    MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
    MDC.put(INSTANCE_UUID, MDC_SDC_INSTANCE_UUID);
    MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
    MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));

    try {
      InetAddress ip = InetAddress.getLocalHost();
      MDC.put(LOCAL_ADDR, ip.getHostAddress());
      String hostname = ip.getHostName();
      MDC.put(BE_FQDN, hostname);
    } catch (UnknownHostException uhe) {
      log.error("Failed to get server FQDN", uhe);
    }

    if (log.isDebugEnabled()) {
      MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
    } else if (log.isInfoEnabled()) {
      MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
    } else if (log.isWarnEnabled()) {
      MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
    } else if (log.isErrorEnabled()) {
      MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
    }
  }

  /**
   * Initialize MDC for logging the current artifact request.
   *
   * @param artifact Current artifact
   */
  public static void initializeArtifactLoggingContext(Artifact artifact) {
    log.debug("Initializing logging context for " + artifact.getLabel());
    MDC.put(REQUEST_ID, artifact.getLabel());
    MDC.put(SERVICE_NAME, artifact.getType());
    MDC.put(SERVICE_INSTANCE_ID, artifact.getName());
  }

  /**
   * Reset the logging context after a Audit/Metrics logging operation.
   */
  public static void resetLoggingContext() {
    MDC.remove(ERROR_CATEGORY);
    MDC.remove(ERROR_CODE);
    MDC.remove(STATUS_CODE);
    MDC.remove(ERROR_DESCRIPTION);
    MDC.remove(BEGIN_TIMESTAMP);
    MDC.remove(END_TIMESTAMP);
    MDC.remove(ELAPSED_TIME);
    MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
    MDC.remove(RESPONSE_CODE);
    MDC.remove(RESPONSE_DESCRIPTION);
    MDC.remove(TARGET_ENTITY);
    MDC.remove(TARGET_SERVICE_NAME);
  }

  /**
   * Convert timestamp to UTC format date string.
   *
   * @param timeStamp UTC timestamp to be converted to the UTC Date format.
   * @return UTC formatted Date string from timestamp.
   */
  public static String getLogUtcDateStringFromTimestamp(Date timeStamp) {
    DateFormat df = new SimpleDateFormat(LOG_UTC_DATE_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    return df.format(timeStamp);
  }

  /**
   * Artifact Gnenerator Error logging Helper.
   *
   * @param errorCategory    WARN or ERROR.
   * @param errorDescription Description of the error.
   */
  public static void artifactGeneratorErrorLogProcessor(CategoryLogLevel errorCategory,
                                                        String errorDescription) {
    MDC.put(ERROR_CATEGORY, errorCategory.name());
    if (errorDescription != null) {
      String errorType = "";
      switch (errorCategory) {
        case WARN:
          errorType = "W";
          break;
        case ERROR:
          errorType = "E";
          break;
        case FATAL:
          errorType = "F";
          break;
        default:
          break;
      }
      MDC.put(ERROR_CODE, getLogResponseCode(errorDescription) + errorType);
    }
    MDC.put(ERROR_DESCRIPTION, errorDescription);
  }


  /**
   *
   * @return Audit log code corresponding to the Artifact Generator exception.
   */
  public static int getLogResponseCode(String errorDescription) {
    ArtifactGeneratorLogResponseCode responseCode = INTERNAL_SERVER_ERROR;
    if (errorDescription.contains(GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION_MSG)) {
      responseCode = MANDATORY_ATTRIBUTE_MISSING;
    } else if (errorDescription.contains(GENERATOR_AAI_ERROR_INVALID_TOSCA_MSG)) {
      responseCode = INVALID_TOSCA_YAML;
    } else if (errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA_MSG)) {
      responseCode = SERVICE_TOSCA_MISSING;
    } else if (errorDescription.contains(GENERATOR_ERROR_INVALID_CLIENT_CONFIGURATION_MSG)) {
      responseCode = INVALID_CLIENT_CONFIGURATION;
    } else if (errorDescription.contains(GENERATOR_ERROR_ARTIFACT_GENERATION_FAILED_MSG)) {
      responseCode = UNABLE_TO_GENERATE_ARTIFACT;
    } else if (errorDescription.contains(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND.split("%s")[0])) {
      responseCode = MISSING_SYSTME_PROPERY_CONFIGURATION;
    } else if (errorDescription.contains(GENERATOR_AAI_CONFIGFILE_NOT_FOUND.split("%s")[0])) {
      responseCode = MISSING_CONFIG_PROPERTIES_FILE;
    } else if (errorDescription.contains(GENERATOR_AAI_CONFIGLPROP_NOT_FOUND.split("%s")[0])) {
      responseCode = MISSING_WIDGET_CONFIGURATION;
    } else if (errorDescription.contains(GENERATOR_AAI_ERROR_INVALID_ID.split("%s")[0])) {
      responseCode = INVALID_ID_VALUE;
    } else if (errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_RESOURCE_TOSCA.split("%s")[0]))
      {
         responseCode = RESOURCE_TOSCA_MISSING;
    } else if(errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION)) {
      responseCode = MISSING_SERVICE_VERSION;
    } else if(errorDescription.contains(GENERATOR_AAI_INVALID_SERVICE_VERSION))
    {
      responseCode = INVALID_SERVICE_VERSION;
    } else if(errorDescription.contains(GENERATOR_AAI_ERROR_NULL_RESOURCE_VERSION_IN_SERVICE_TOSCA.
        split("%s")[0])) {
      responseCode = MISSING_RESOURCE_VERSION;
    } else if(errorDescription.contains(
        GENERATOR_AAI_ERROR_INVALID_RESOURCE_VERSION_IN_SERVICE_TOSCA.split("%s")[0])) {
      responseCode = INVALID_RESOURCE_VERSION;
    } else if(errorDescription.contains(GENERATOR_AAI_PROVIDING_SERVICE_MISSING.split("%s")[0])) {
      responseCode = MISSING_PRO_SERVICE;
    } else if(errorDescription.contains(
        GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING.split("%s")[0])) {
      responseCode = MISSING_PRO_SERVICE_METADATA;
    }
    return responseCode.getValue();
  }
}