diff options
Diffstat (limited to 'common/src/main/java/org/openecomp/mso')
18 files changed, 3079 insertions, 0 deletions
diff --git a/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java b/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java new file mode 100644 index 0000000000..4f3a4ab9de --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.entity; + + + +/** + * This simple bean holds tracking information for MSO requests within + * the adapters. This tracking information should be added to logs, + * metrics, alarms as appropriate. + * + * + */ +public class MsoRequest +{ + private String requestId; + private String serviceInstanceId; + + public MsoRequest() { + this.requestId = null; + this.serviceInstanceId = null; + } + public MsoRequest(String r, String s) { + this.requestId = r; + this.serviceInstanceId = s; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } +} diff --git a/common/src/main/java/org/openecomp/mso/entity/package-info.java b/common/src/main/java/org/openecomp/mso/entity/package-info.java new file mode 100644 index 0000000000..e97a588e32 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/entity/package-info.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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========================================================= + */ + +/** + * Entities used for logging. + */ + +package org.openecomp.mso.entity; + diff --git a/common/src/main/java/org/openecomp/mso/logger/LogFilter.java b/common/src/main/java/org/openecomp/mso/logger/LogFilter.java new file mode 100644 index 0000000000..ca25ad2e22 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/LogFilter.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.MDC; + +import java.io.IOException; +import java.security.Principal; + +public class LogFilter implements Filter { + @Override + public void destroy() { + // Nothing to do. + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { + final HttpServletRequest httpRequest = (HttpServletRequest) request; + final HttpServletResponse httpResponse = (HttpServletResponse) response; + + MDC.clear (); + MDC.put (MsoLogger.REMOTE_HOST, httpRequest.getRemoteAddr()); + + Principal userPrincipal = httpRequest.getUserPrincipal(); + if (null != userPrincipal) { + MDC.put (MsoLogger.PARTNERNAME, userPrincipal.getName ()); + } + chain.doFilter(httpRequest, httpResponse); + } + + @Override + public void init(final FilterConfig config) throws ServletException { + // Nothing to do + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java b/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java new file mode 100644 index 0000000000..89f6df93b7 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +public enum MessageEnum implements EELFResolvableErrorEnum{ + // Api Handler Messages + APIH_REQUEST_NULL, + APIH_QUERY_FOUND, + APIH_QUERY_NOT_FOUND, + APIH_QUERY_PARAM_WRONG, + APIH_DB_ACCESS_EXC, + APIH_DB_ACCESS_EXC_REASON, + APIH_VALIDATION_ERROR, + APIH_REQUEST_VALIDATION_ERROR, + APIH_SERVICE_VALIDATION_ERROR, + APIH_GENERAL_EXCEPTION_ARG, + APIH_GENERAL_EXCEPTION, + APIH_GENERAL_WARNING, + APIH_AUDIT_EXEC, + APIH_GENERAL_METRICS, + APIH_DUPLICATE_CHECK_EXC, + APIH_DUPLICATE_FOUND, + APIH_BAD_ORDER, + APIH_DB_ATTRIBUTE_NOT_FOUND, + APIH_BPEL_COMMUNICATE_ERROR, + APIH_BPEL_RESPONSE_ERROR, + APIH_WARP_REQUEST, + APIH_ERROR_FROM_BPEL_SERVER, + APIH_DB_INSERT_EXC, + APIH_DB_UPDATE_EXC, + APIH_NO_PROPERTIES, + APIH_PROPERTY_LOAD_SUC, + APIH_LOAD_PROPERTIES_FAIL, + APIH_SDNC_COMMUNICATE_ERROR, + APIH_SDNC_RESPONSE_ERROR, + APIH_CANNOT_READ_SCHEMA, + APIH_HEALTH_CHECK_EXCEPTION, + APIH_REQUEST_VALIDATION_ERROR_REASON, + APIH_JAXB_MARSH_ERROR, + APIH_JAXB_UNMARSH_ERROR, + APIH_VNFREQUEST_VALIDATION_ERROR, + APIH_DOM2STR_ERROR, + APIH_READ_VNFOUTPUT_CLOB_EXCEPTION, + APIH_DUPLICATE_CHECK_EXC_ATT, + APIH_GENERATED_REQUEST_ID, + APIH_GENERATED_SERVICE_INSTANCE_ID, + APIH_REPLACE_REQUEST_ID, + // Resource Adapter Messages + RA_GENERAL_EXCEPTION_ARG, + RA_GENERAL_EXCEPTION, + RA_GENERAL_WARNING, + RA_MISSING_PARAM, + RA_AUDIT_EXEC, + RA_GENERAL_METRICS, + RA_CREATE_STACK_TIMEOUT, + RA_DELETE_STACK_TIMEOUT, + RA_UPDATE_STACK_TIMEOUT, + RA_CONNECTION_EXCEPTION, + RA_PARSING_ERROR, + RA_PROPERTIES_NOT_FOUND, + RA_LOAD_PROPERTIES_SUC, + RA_NETWORK_ALREADY_EXIST, + RA_UPDATE_NETWORK_ERR, + RA_CREATE_STACK_ERR, + RA_UPDATE_STACK_ERR, + RA_CREATE_TENANT_ERR, + RA_NETWORK_NOT_FOUND, + RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, + RA_CREATE_NETWORK_EXC, + RA_PARAM_NOT_FOUND, + RA_CONFIG_EXC, + RA_UNKOWN_PARAM, + RA_VLAN_PARSE, + RA_DELETE_NETWORK_EXC, + RA_ROLLBACK_NULL, + RA_TENANT_NOT_FOUND, + RA_QUERY_NETWORK_EXC, + RA_CREATE_NETWORK_NOTIF_EXC, + RA_ASYNC_ROLLBACK, + RA_WSDL_NOT_FOUND, + RA_WSDL_URL_CONVENTION_EXC, + RA_INIT_NOTIF_EXC, + RA_SET_CALLBACK_AUTH_EXC, + RA_FAULT_INFO_EXC, + RA_MARSHING_ERROR, + RA_PARSING_REQUEST_ERROR, + RA_SEND_REQUEST_SDNC, + RA_RESPONSE_FROM_SDNC, + RA_EXCEPTION_COMMUNICATE_SDNC, + RA_EVALUATE_XPATH_ERROR, + RA_ANALYZE_ERROR_EXC, + RA_ERROR_GET_RESPONSE_SDNC, + RA_CALLBACK_BPEL, + RA_INIT_CALLBACK_WSDL_ERR, + RA_CALLBACK_BPEL_EXC, + RA_CALLBACK_BPEL_COMPLETE, + RA_SDNC_MISS_CONFIG_PARAM, + RA_SDNC_INVALID_CONFIG, + RA_PRINT_URL, + RA_ERROR_CREATE_SDNC_REQUEST, + RA_ERROR_CREATE_SDNC_RESPONSE, + RA_ERROR_CONVERT_XML2STR, + RA_RECEIVE_SDNC_NOTIF, + RA_INIT_SDNC_ADAPTER, + RA_SEND_REQUEST_APPC_ERR, + RA_SEND_REQUEST_SDNC_ERR, + RA_RECEIVE_BPEL_REQUEST, + RA_TENANT_ALREADY_EXIST, + RA_UPDATE_TENANT_ERR, + RA_DELETE_TEMAMT_ERR, + RA_ROLLBACK_TENANT_ERR, + RA_QUERY_VNF_ERR, + RA_VNF_ALREADY_EXIST, + RA_VNF_UNKNOWN_PARAM, + RA_VNF_EXTRA_PARAM, + RA_CREATE_VNF_ERR, + RA_VNF_NOT_EXIST, + RA_UPDATE_VNF_ERR, + RA_DELETE_VNF_ERR, + RA_ASYNC_CREATE_VNF, + RA_SEND_VNF_NOTIF_ERR, + RA_ASYNC_CREATE_VNF_COMPLETE, + RA_ASYNC_UPDATE_VNF, + RA_ASYNC_UPDATE_VNF_COMPLETE, + RA_ASYNC_QUERY_VNF, + RA_ASYNC_QUERY_VNF_COMPLETE, + RA_ASYNC_DELETE_VNF, + RA_ASYNC_DELETE_VNF_COMPLETE, + RA_ASYNC_ROLLBACK_VNF, + RA_ASYNC_ROLLBACK_VNF_COMPLETE, + RA_ROLLBACK_VNF_ERR, + RA_DB_INVALID_STATUS, + RA_CANT_UPDATE_REQUEST, + RA_DB_REQUEST_NOT_EXIST, + RA_CONFIG_NOT_FOUND, + RA_CONFIG_LOAD, + // BPEL engine Messages + BPMN_GENERAL_INFO, + BPMN_GENERAL_EXCEPTION_ARG, + BPMN_GENERAL_EXCEPTION, + BPMN_GENERAL_WARNING, + BPMN_AUDIT_EXEC, + BPMN_GENERAL_METRICS, + BPMN_URN_MAPPING_FAIL, + BPMN_VARIABLE_NULL, + BPMN_SDNC_CALLBACK_EXCEPTION, + // ASDC Messages + ASDC_GENERAL_EXCEPTION_ARG, + ASDC_GENERAL_EXCEPTION, + ASDC_GENERAL_WARNING, + ASDC_AUDIT_EXEC, + ASDC_GENERAL_METRICS, + ASDC_CREATE_SERVICE, + ASDC_ARTIFACT_ALREADY_DEPLOYED, + ASDC_CREATE_ARTIFACT, + ASDC_ARTIFACT_INSTALL_EXC, + ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, + ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, + ASDC_ARTIFACT_CHECK_EXC, + ASDC_INIT_ASDC_CLIENT_EXC, + ASDC_INIT_ASDC_CLIENT_SUC, + ASDC_LOAD_ASDC_CLIENT_EXC, + ASDC_SINGLETON_CHECKT_EXC, + ASDC_SHUTDOWN_ASDC_CLIENT_EXC, + ASDC_CHECK_HEAT_TEMPLATE, + ASDC_START_INSTALL_ARTIFACT, + ASDC_ARTIFACT_TYPE_NOT_SUPPORT, + ASDC_ARTIFACT_ALREADY_EXIST, + ASDC_ARTIFACT_DOWNLOAD_SUC, + ASDC_ARTIFACT_DOWNLOAD_FAIL, + ASDC_START_DEPLOY_ARTIFACT, + ASDC_SEND_NOTIF_ASDC, + ASDC_SEND_NOTIF_ASDC_EXEC, + ASDC_RECEIVE_CALLBACK_NOTIF, + ASDC_RECEIVE_SERVICE_NOTIF, + ASDC_ARTIFACT_NULL, + ASDC_SERVICE_NOT_SUPPORT, + ASDC_ARTIFACT_DEPLOY_SUC, + ASDC_PROPERTIES_NOT_FOUND, + // Default Messages, in case Log catalog is not defined + GENERAL_EXCEPTION_ARG, + GENERAL_EXCEPTION, + GENERAL_WARNING, + AUDIT_EXEC, + GENERAL_METRICS, + LOGGER_SETUP, + LOGGER_NOT_FOUND, + LOGGER_UPDATE_SUC, + LOGGER_UPDATE_DEBUG, + LOGGER_UPDATE_DEBUG_SUC, + LOAD_PROPERTIES_SUC, + NO_PROPERTIES, + MADATORY_PARAM_MISSING, + LOAD_PROPERTIES_FAIL, + INIT_LOGGER, + INIT_LOGGER_FAIL, + JAXB_EXCEPTION, + IDENTITY_SERVICE_NOT_FOUND; + + static { + EELFResourceManager.loadMessageBundle("GenericMessages"); + EELFResourceManager.loadMessageBundle("ApiHandler"); + EELFResourceManager.loadMessageBundle("BPMN"); + EELFResourceManager.loadMessageBundle("ResourceAdapter"); + EELFResourceManager.loadMessageBundle("ASDC"); + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java new file mode 100644 index 0000000000..147c1ad4f1 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + + +import java.io.File; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.rolling.RollingFileAppender; +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; + +/** + * Wrapper around log4j and Nagios NRDP passive alarming for MSO. + * + * For local alarm logging, this class will look for an alarm log file name + * in the servlet context parameter "mso.alarms.file". If none is found, + * it will look for an MsoProperty of the same name. As a last resort, + * it will use the default path "/var/log/ecomp/MSO/alarms/alarm.log". + * It is expected that all alarms within an application will use the same + * alarm file, so there is no way to dynamically add other alarm files. + * + * Alarms are logged as a simple pipe-delimited string of the format: + * <dateTime>|<alarmType>|<state>|<detailMessage> + * + * This class also supports real-time Nagios NRDP alarming. If enabled via + * MsoProperties, all alarms generated and logged to the local alarm file will + * also be transmitted to a Nagios NRDP instance. NRDP requires 4 parameters + * in service alarm events (all Mso Alarms will be Service Alarms): + * hostname, servicename, state, detail + * + * The log file format is also intended to be compatible with Nagios NRDP for + * non-real-time reporting. The command-line tool for sending alarms is + * is "send_nrdp.php", which takes the same 4 parameters as input. + * It will be easy enough to translate entries from an alarm.log file to + * NRDP if real-time NRDP alarming is not enabled. + * + * For Nagios integration, the alarmTypes should all match "service names" + * configured in the receiving Nagios server. Also, the alarm state will + * be limited to the 4 values defined by Nagios: + * 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown + * + * + */ +public class MsoAlarmLogger implements ServletContextListener { + + private Logger alarmLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(MSO_ALARM_CONTEXT); + private static RollingFileAppender<ILoggingEvent> fileAppender = null; + public static final String DEFAULT_MSO_ALARM_FILE = "/var/log/ecomp/MSO/alarms/alarm.log"; + public static final String MSO_ALARM_CONTEXT = "mso.alarms"; + + public static final int OK = 0; + public static final int WARNING = 1; + public static final int CRITICAL = 2; + public static final int UNKNOWN = 3; + + /** + * Get the default MSO Alarm Logger + */ + public MsoAlarmLogger () { + + initializeAlarmLogger(null); + + } + + public MsoAlarmLogger (String alarmFile) { + initializeAlarmLogger(alarmFile); + + } + + /** + * Method to record an alarm. + * + * @param alarm - the alarm identifier (Nagios "service") + * @param state - the alarm state/severity, based on Nagios service + * state values: 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown + * @param detail - detail message (may contain additional internal + * structure per alarm type) + */ + public void sendAlarm (String alarm, int state, String detail) { + // Write the alarm to Log file + if (alarmLogger != null) { + String output = alarm + "|" + state + "|" + detail; + alarmLogger.info (output); + } + + } + + @Override + public void contextDestroyed (ServletContextEvent event) { + // Nothing to do... + } + + @Override + public void contextInitialized (ServletContextEvent event) { + String msoAlarmFile = event.getServletContext ().getInitParameter ("mso.alarm.file"); + if (msoAlarmFile == null) { + msoAlarmFile = DEFAULT_MSO_ALARM_FILE; + } + + initializeAlarmLogger (msoAlarmFile); + } + + private void initializeAlarmLogger (String alarmFile) { + synchronized (MsoAlarmLogger.class) { + if (fileAppender == null) { + if (alarmFile != null) { + fileAppender = MsoAlarmLogger.getAppender (alarmFile); + } else { + fileAppender = MsoAlarmLogger.getAppender (DEFAULT_MSO_ALARM_FILE); + } + } + } + // The alarmLogger was static originally. + // The initialization of the alarmLogger was fine, but not sure why, it lost its appender info later + // Due to that issue, the alarmLogger is not static any more. + // Instead static attribute fileAppender is added and will be assigned to the alarmLogger every time new MsoAlarmLogger is created. + alarmLogger.setLevel (Level.INFO); + alarmLogger.addAppender (fileAppender); + alarmLogger.setAdditive (false); + } + + + private static RollingFileAppender<ILoggingEvent> getAppender (String msoAlarmFile) { + // Create a Logger for alarms. Just use a default Pattern that outputs + // a message. MsoAlarmLogger will handle the formatting. + File alarmFile = new File (msoAlarmFile); + File alarmDir = alarmFile.getParentFile (); + if (!alarmDir.exists ()) { + alarmDir.mkdirs (); + } + + String logPattern = "%d{yyyy-MM-dd HH:mm:ss}|%m%n"; + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + PatternLayoutEncoder encoder=new PatternLayoutEncoder(); + encoder.setPattern(logPattern); + encoder.setContext(context); + encoder.start(); + RollingFileAppender<ILoggingEvent> fileAppender=new RollingFileAppender<ILoggingEvent>(); + TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy=new TimeBasedRollingPolicy<ILoggingEvent>(); + rollingPolicy.setContext(context); + rollingPolicy.setFileNamePattern(msoAlarmFile + ".%d"); + rollingPolicy.setParent(fileAppender); + rollingPolicy.start(); + fileAppender.setFile(msoAlarmFile); + fileAppender.setAppend(true); + fileAppender.setEncoder(encoder); + fileAppender.setRollingPolicy(rollingPolicy); + fileAppender.setContext(context); + fileAppender.start(); + + return fileAppender; + } + +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java new file mode 100644 index 0000000000..0c96dabbea --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + + +import java.io.File; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; + + +/** + * This class will attempt to initialize MSO log4j when part of a web application. + * It will look for the logback configuration file logback.xml in the + * following order: + * 1. In an init-param "log.configuration" in web.xml + * 2. TODO: In a property "log.configuration" in an "application.properties" file + * 3. In the default location "/etc/ecomp/mso/config" + * 4. Using the log4j default (check system property log.configuration or + * just look on the classpath for logback.xml) + * + * + */ +@WebListener +public class MsoLogInitializer implements ServletContextListener +{ + private static String DEFAULT_LOG4J_PROPERTIES_FILE = "/etc/ecomp/mso/config/logback.xml"; + private static String prefixMsoPropertiesPath = System.getProperty("mso.config.path"); + static { + if (prefixMsoPropertiesPath == null) { + prefixMsoPropertiesPath = "/"; + } else if (!(prefixMsoPropertiesPath.charAt(prefixMsoPropertiesPath.length() - 1) == '/')) { + prefixMsoPropertiesPath = prefixMsoPropertiesPath + "/"; + } + } + + public MsoLogInitializer () { + } + + + @Override + public void contextDestroyed(ServletContextEvent event) { + // Nothing to do... + } + + @Override + public void contextInitialized(ServletContextEvent event) + { + String logPropertiesFile = null; + try { + // Look first in the init-parameters + String initParam = event.getServletContext().getInitParameter("log.configuration"); + if (initParam != null && fileIsReadable(prefixMsoPropertiesPath + initParam)) { + logPropertiesFile = prefixMsoPropertiesPath + initParam; + } + else if (fileIsReadable(DEFAULT_LOG4J_PROPERTIES_FILE)) { + logPropertiesFile = DEFAULT_LOG4J_PROPERTIES_FILE; + } + + if (logPropertiesFile != null) { + // Initialize loggers with the specified file. If no such file was + // specified, will use the default Log4j resolution. + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + context.reset(); + jc.doConfigure(logPropertiesFile); + // Try it out + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + initLogger.info(MessageEnum.INIT_LOGGER, logPropertiesFile, "", ""); + } + } catch (Exception e) { + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + initLogger.error (MessageEnum.INIT_LOGGER_FAIL, "", "", MsoLogger.ErrorCode.UnknownError, "", e); + } + } + + private boolean fileIsReadable (String filePath) { + File f = new File(filePath); + if (f.exists() && f.canRead()) + return true; + return false; + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java new file mode 100644 index 0000000000..c53022734f --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java @@ -0,0 +1,973 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.slf4j.MDC; + +import org.openecomp.mso.entity.MsoRequest; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Simple wrapper around the EELF Logger class for MSO usage. + * This class supports all of the normal logging functions (debug, info, etc.), + * prepending a string of format "[<requestId>|<serviceId]" to each message. + * + * MSO code should initialize with these IDs when available, so that individual + * requests and/or services can be tracked throughout the various MSO component + * logs (API Handler, BPEL, and Adapters). + * + * + */ +public class MsoLogger { + // MDC parameters + public static final String REQUEST_ID = "RequestId"; + public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; + public static final String SERVICE_NAME = "ServiceName"; + private static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName"; + private static final String INSTANCE_UUID = "InstanceUUID"; + private static final String SERVER_IP = "ServerIPAddress"; + private static final String FQDN = "ServerFQDN"; + public static final String REMOTE_HOST = "RemoteHost"; + public static final String ALERT_SEVERITY = "AlertSeverity"; + public static final String TIMER = "Timer"; + private static final String USER = "User"; + private static final String DUMMY_VALUE = "trace-#"; + public static final String UNKNOWN = "UNKNOWN"; + // Audit/Metric log specigic + private static final String BEGINTIME = "BeginTimestamp"; + private static final String ENDTIME = "EndTimestamp"; + public static final String PARTNERNAME = "PartnerName"; + private static final String STATUSCODE = "StatusCode"; + private static final String RESPONSECODE = "ResponseCode"; + private static final String RESPONSEDESC = "ResponseDesc"; + // Metric log specigic + private static final String TARGETENTITY = "TargetEntity"; + private static final String TARGETSERVICENAME = "TargetServiceName"; + private static final String TARGETVIRTUALENTITY = "TargetVirtualEntity"; + + private static final String FATAL_LEVEL = "FATAL"; + private static final String ERROR_LEVEL = "ERROR"; + private static final String WARN_LEVEL = "WARN"; + private static final String INFO_LEVEL = "INFO"; + private static final String DEBUG_LEVEL = "DEBUG"; + + private static final String ERRORCODE = "ErrorCode"; + private static final String ERRORDESC = "ErrorDesc"; + +public enum Catalog {APIH, BPEL, RA, ASDC, GENERAL}; + public enum StatusCode {COMPLETE, ERROR}; + public enum ResponseCode {Suc(0), PermissionError(100), + DataError(300), DataNotFound(301), BadRequest (302), + SchemaError(400), + BusinessProcesssError(500), ServiceNotAvailable (501), InternalError (502), Conflict (503), DBAccessError(504), CommunicationError(505), + UnknownError(900); + + private int value; + public int getValue () { + return this.value; + } + private ResponseCode (int value) { + this.value = value; + } + }; + + public enum ErrorCode {PermissionError(100), AvailabilityError(200), + DataError(300), SchemaError(400), + BusinessProcesssError(500), + UnknownError(900); + + private int value; + public int getValue () { + return this.value; + } + private ErrorCode (int value) { + this.value = value; + } + }; + + private EELFLogger logger, auditLogger, metricsLogger; + private static final String CONFIG_FILE = System.getProperty ("jboss.home.dir") + "/mso-config/uuid/uuid_" + + System.getProperty ("jboss.server.name"); + private static String instanceUUID, serverIP, serverName; + private MessageEnum exceptionArg, defaultException, defaultWarning, defaultAudit, defaultMetrics; + + // For internal logging of the initialization of MSO logs + private static final Logger LOGGER = Logger.getLogger (MsoLogger.class.getName ()); + + + private MsoLogger (MsoLogger.Catalog cat) { + this.logger = EELFManager.getInstance().getErrorLogger(); + this.auditLogger = EELFManager.getInstance().getAuditLogger(); + this.metricsLogger = EELFManager.getInstance().getMetricsLogger(); + MsoLogger.initialization (); + setDefaultLogCatalog (cat); + } + + private static synchronized void initialization () { + if (instanceUUID == null || ("").equals (instanceUUID)) { + instanceUUID = getInstanceUUID (); + } + + if (serverIP == null || serverName == null || ("").equals (serverIP) || ("").equals (serverName)) { + try { + InetAddress server = InetAddress.getLocalHost (); + serverIP = server.getHostAddress (); + serverName = server.getHostName (); + } catch (UnknownHostException e) { + LOGGER.log (Level.SEVERE, "Could not get local hostname", e); + serverIP = ""; + serverName = ""; + } + } + } + + /** + * Get the MsoLogger based on the catalog + * @param cat Catalog of the logger + * @return the MsoLogger + */ + public static synchronized MsoLogger getMsoLogger (MsoLogger.Catalog cat) { + return new MsoLogger (cat); + } + + /** + * Record the Metrics event with no argument + * @param startTime Transaction starting time in millieseconds + * @param statusCode StatusCode of the transaction, either COMPLETE or ERROR + * @param responseCode The response code returned by the sub-components + * @param responseDesc Human redable description of the response code + * @param targetEntity The component which is invoked for this sub-operation + * @param targetServiceName API invoked on the TargetEntity + * @param targetVEntity Target VNF or VM acted opon by the component, if available + */ + public void recordMetricEvent (Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc, String targetEntity, String targetServiceName, String targetVEntity) { + prepareMetricMsg (startTime, statusCode, responseCode.getValue (), responseDesc, targetEntity, targetServiceName, targetVEntity); + metricsLogger.info (""); + MDC.remove(TIMER); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Audit event + * + * @param startTime Transaction starting time in millieseconds + * @param statusCode StatusCode of the transaction, either COMPLETE or ERROR + * @param responseCode The application specific response code + * @param responseDesc Human redable description of the application response code + */ + public void recordAuditEvent (Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc) { + prepareAuditMsg (startTime, statusCode, responseCode.getValue (), responseDesc); + auditLogger.info (""); + MDC.remove(TIMER); + } + + // Debug methods + /** + * Record the Debug event + * + * @param msg The log message to put + */ + public void debug (String msg) { + prepareMsg (DEBUG_LEVEL); + logger.debug (msg); + } + + /** + * Record the Debug event + * + * @param msg The log message to put + * @param t The exception to put + */ + public void debug (String msg, Throwable t) { + prepareMsg (DEBUG_LEVEL); + logger.debug (msg, t); + } + + // Info methods + /** + * Record the Info event + * + * @param msg The log message to put + */ + public void info (MessageEnum msg, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 1 argument + * + * @param msg The log message to put + * @param arg0 The argument used in the log message + */ + public void info (MessageEnum msg, String arg0, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 6 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4,arg5 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), normalize(arg5)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + // Warning methods + /** + * Record the Warning event + * + * @param msg The log message to put + */ + public void warn (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + + logger.warn (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warning event + * + * @param msg The log message to put + * @param t The exception info + */ + public void warn (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 1 argument + * + * @param msg The log message to put + * @param arg The argument used in the log message + */ + public void warn (MessageEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, arg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 1 argument + * + * @param msg The log message to put + * @param arg The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, arg); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2, arg3 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + // Error methods + /** + * Record the Error event + * + * @param msg The log message to put + */ + public void error (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event + * + * @param msg The log message to put + * @param t The exception info + */ + public void error (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 1 argument + * + * @param msg The log message to put + * @param arg0 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 1 argument + * + * @param msg The log message to put + * @param arg0 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + + + public boolean isDebugEnabled () { + return logger.isDebugEnabled(); + } + + private void prepareMsg (String loggingLevel) { + prepareMsg (loggingLevel, null, null); + } + + private void prepareMsg (String loggingLevel, String serviceNamep, String timer) { + String reqId = MDC.get (REQUEST_ID); + String svcId = MDC.get (SERVICE_INSTANCE_ID); + + // Based on the discussion with Adrian, + // if these 2 parameters is not available, using dummy value "trace-#" + if (reqId == null || reqId.isEmpty()) { + MDC.put (REQUEST_ID, DUMMY_VALUE); + } + + if (svcId == null || svcId.isEmpty()) { + MDC.put (SERVICE_INSTANCE_ID, DUMMY_VALUE); + } + + if (timer != null) { + MDC.put (TIMER, timer); + } else { + MDC.remove(TIMER); + } + + MDC.put (SERVICE_NAME, getFinalServiceName (serviceNamep)); + MDC.put (ALERT_SEVERITY, getSeverityLevel (loggingLevel)); + MDC.put (INSTANCE_UUID, instanceUUID); + MDC.put (SERVER_IP, serverIP); + MDC.put (FQDN, serverName); + } + + private void prepareAuditMsg ( long startTime, StatusCode statusCode, int responseCode, String responseDesc) { + long endTime = System.currentTimeMillis(); + prepareMsg (INFO_LEVEL, null, String.valueOf(endTime - startTime)); + prepareAuditMetricMsg (startTime, endTime, statusCode, responseCode, responseDesc); + } + + private void prepareAuditMetricMsg ( long startTime, long endTime, StatusCode statusCode, int responseCode, String responseDesc) { + Date startDate = new Date(startTime); + Date endDate = new Date(endTime); + DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + MDC.put (BEGINTIME, String.valueOf(formatter.format(startDate))); + MDC.put (ENDTIME, String.valueOf(formatter.format(endDate))); + MDC.put (STATUSCODE, statusCode.name()); + MDC.put (RESPONSECODE, String.valueOf(responseCode)); + MDC.put (RESPONSEDESC, responseDesc); + } + + private void prepareErrorMsg (String loggingLevel, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + MDC.put (ALERT_SEVERITY, getSeverityLevel (loggingLevel)); + MDC.put (ERRORCODE, String.valueOf(errorCode)); + MDC.put (ERRORDESC, errorDesc); + MDC.put (TARGETENTITY, targetEntity); + MDC.put (TARGETSERVICENAME, targetServiceName); + MDC.put (SERVICE_NAME, getFinalServiceName (getServiceName())); + } + + private void prepareMetricMsg ( long startTime, StatusCode statusCode, int responseCode, String responseDesc, String targetEntity, String targetServiceName, String targetVEntity) { + long endTime = System.currentTimeMillis(); + prepareMsg (INFO_LEVEL, null, String.valueOf(endTime - startTime)); + prepareAuditMetricMsg (startTime, endTime, statusCode, responseCode, responseDesc); + + // Populate Metric log specific parameter + MDC.put (TARGETENTITY, targetEntity); + MDC.put (TARGETSERVICENAME, targetServiceName); + + if (null != targetVEntity) { + MDC.put(TARGETVIRTUALENTITY, targetVEntity); + } + } + + private String getSeverityLevel (String loggingLevel) { + String severity; + // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; 3=CRITICAL + switch (loggingLevel) { + case ERROR_LEVEL: + severity = "2"; + break; + case FATAL_LEVEL: + severity = "3"; + break; + case WARN_LEVEL: + severity = "1"; + break; + default: + severity = "0"; + break; + } + return severity; + } + + private String getFinalServiceName (String serviceNamep) { + // This step to set the serviceName should be put after the className is get, + // since the default serviceName is obtained during the method to get the className. + // + // There's 3 ways to set the serviceName. The first method has the most priority to set the value. + // a) If the serviceName is set within the log method, this value will be used first + // b) If serviceName is not set within the log method, the value defined in the MDC will be used + // c) If nothing is set specifically, then MsoLogger will assign a default(MSO.<method_name>) value to it + String serName = MDC.get (MsoLogger.SERVICE_NAME); + + // Check if service name was already set as the method name by a previous call to this method. + String isMethodNameStr = MDC.get (MsoLogger.SERVICE_NAME_IS_METHOD_NAME); + boolean isMethodName = isMethodNameStr != null && isMethodNameStr.equals (Boolean.TRUE.toString ()); + if (serviceNamep != null) { + return serviceNamep; + } else if (serName != null && !isMethodName) { + return serName; + } + + MDC.put (MsoLogger.SERVICE_NAME_IS_METHOD_NAME, Boolean.TRUE.toString ()); + int limit; + StackTraceElement[] classArr = new Exception ().getStackTrace (); + if (classArr.length >=6) { + limit = 7; + } else { + limit = classArr.length; + } + for (int i = 1; i < limit; i++) { + String className = classArr[i].getClassName (); + if (!className.equals (this.getClass ().getName ())) { + return classArr[i].getMethodName (); + } + } + return classArr[0].getMethodName (); + } + + // Based on the discussion with Adrian, instanceUUID is used to identifiy the mso instance, + // it is generated during mso instance initialization period + // The same mso instnace will use the same instanceUUID value, even after restart + private static String getInstanceUUID () { + // Avoid creation during build and tests + if (System.getProperty ("jboss.server.name") == null) { + return "Test UUID as JBoss not found"; + } + File configFile = new File (CONFIG_FILE); + String uuid = ""; + BufferedReader in = null; + BufferedWriter bw = null; + try { + // Verify whether instanceUUID file exist, + // If yes, read the content; if not, generate the instanceUUID and write to the file + if (configFile.exists ()) { + // read the content of the file + in = new BufferedReader (new FileReader (CONFIG_FILE)); + if ((uuid = in.readLine ()) == null) { + // the file is empty, regenerate the file + uuid = UUID.randomUUID ().toString (); + FileWriter fw = new FileWriter (configFile.getAbsoluteFile ()); + bw = new BufferedWriter (fw); + bw.write (uuid); + bw.close (); + } + in.close (); + } else { + // file doesn't exist yet -> create the file and generate the instanceUUID + uuid = UUID.randomUUID ().toString (); + configFile.getParentFile ().mkdirs (); + configFile.createNewFile (); + FileWriter fw = new FileWriter (configFile.getAbsoluteFile ()); + bw = new BufferedWriter (fw); + bw.write (uuid); + bw.close (); + } + } catch (IOException e) { + LOGGER.log (Level.SEVERE, "Error trying to read UUID file", e); + } finally { + try { + if (in != null) { + in.close (); + } + if (bw != null) { + bw.close (); + } + } catch (IOException ex) { + LOGGER.log (Level.SEVERE, "Error trying to close UUID file", ex); + } + } + return uuid; + } + + /** + * Set the requestId and serviceInstanceId + * @param reqId The requestId + * @param svcId The serviceInstanceId + */ + public static void setLogContext (String reqId, String svcId) { + if (null != reqId) { + MDC.put (REQUEST_ID, reqId); + } + + if (null != svcId) { + MDC.put (SERVICE_INSTANCE_ID, svcId); + } + } + + /** + * Set the remoteIp and the basic HTTP Authentication user + * @param remoteIpp The remote ip address + * @param userp The basic http authencitation user + */ + public static void setLoggerParameters (String remoteIpp, String userp) { + if (null != remoteIpp) { + MDC.put (REMOTE_HOST, remoteIpp); + } + if (null != userp) { + MDC.put (USER, userp); + } + } + + /** + * Set the serviceName + * @param serviceNamep The service name + */ + public static void setServiceName (String serviceNamep) { + if (null != serviceNamep) { + MDC.put (SERVICE_NAME, serviceNamep); + MDC.remove (SERVICE_NAME_IS_METHOD_NAME); + } + } + + /** + * Get the serviceName + * @return The service name + */ + public static String getServiceName () { + return MDC.get (SERVICE_NAME); + } + + /** + * Reset the serviceName + */ + public static void resetServiceName () { + MDC.remove (SERVICE_NAME); + } + + /** + * Set the requestId and serviceInstanceId based on the mso request + * @param msoRequest The mso request + */ + public static void setLogContext (MsoRequest msoRequest) { + if (msoRequest != null) { + MDC.put (REQUEST_ID, msoRequest.getRequestId()); + MDC.put (SERVICE_INSTANCE_ID, msoRequest.getServiceInstanceId()); + } + else { + MDC.put (REQUEST_ID, DUMMY_VALUE); + MDC.put (SERVICE_INSTANCE_ID, DUMMY_VALUE); + } + } + + private String normalize (String input) { + if (input == null) { + return null; + } + String result = input.replace ('|', '!'); + result = result.replace ("\n", " - "); + return result; + } + + private String getNormalizedStackTrace (Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString().replace ('|', '!').replace ("\n", " - "); + } + + private void setDefaultLogCatalog (MsoLogger.Catalog cat) { + if ("APIH".equals(cat.toString())) { + exceptionArg = MessageEnum.APIH_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.APIH_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.APIH_GENERAL_WARNING; + defaultAudit = MessageEnum.APIH_AUDIT_EXEC; + defaultMetrics = MessageEnum.APIH_GENERAL_METRICS; + } else if ("RA".equals(cat.toString())) { + exceptionArg = MessageEnum.RA_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.RA_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.RA_GENERAL_WARNING; + defaultAudit = MessageEnum.RA_AUDIT_EXEC; + defaultMetrics = MessageEnum.RA_GENERAL_METRICS; + } else if ("BPEL".equals(cat.toString())) { + exceptionArg = MessageEnum.BPMN_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.BPMN_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.BPMN_GENERAL_WARNING; + defaultAudit = MessageEnum.BPMN_AUDIT_EXEC; + defaultMetrics = MessageEnum.BPMN_GENERAL_METRICS; + } else if ("ASDC".equals(cat.toString())) { + exceptionArg = MessageEnum.ASDC_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.ASDC_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.ASDC_GENERAL_WARNING; + defaultAudit = MessageEnum.ASDC_AUDIT_EXEC; + defaultMetrics = MessageEnum.ASDC_GENERAL_METRICS; + } else { + exceptionArg = MessageEnum.GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.GENERAL_EXCEPTION; + defaultWarning = MessageEnum.GENERAL_WARNING; + defaultAudit = MessageEnum.AUDIT_EXEC; + defaultMetrics = MessageEnum.GENERAL_METRICS; + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java b/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java new file mode 100644 index 0000000000..568ab22447 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.logger; + + +import java.util.List; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.core.Appender; + +@Path("/logging") +public class MsoLoggingServlet { + + private static final String DEBUGLOG = "asyncEELFDebug"; + private MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL); + private static final String GENERAL_LOGGER = "com.att.eelf.error"; + private static final String AUDIT_LOGGER = "com.att.eelf.audit"; + private static final String METRICS_LOGGER = "com.att.eelf.metrics"; + + @GET + @Path("/setLevel/{logContext}/{level}") + @Produces("text/plain") + public Response setLogLevel (@PathParam("logContext") String logContext, @PathParam("level") String level) { + logger.info (MessageEnum.LOGGER_SETUP, "", ""); + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + Logger updateLogger = context.getLogger (logContext); + + if (updateLogger == null) { + logger.info (MessageEnum.LOGGER_NOT_FOUND, logContext, "", ""); + String response = "Unknown logger: " + logContext; + return Response.status (200).entity (response).build (); + } + + Level currentLevel = updateLogger.getLevel(); + if (!currentLevel.equals(Level.toLevel(level))) { + Level newLevel = Level.toLevel (level); + updateLogger.setLevel (newLevel); + logger.info (MessageEnum.LOGGER_UPDATE_SUC, updateLogger.getName (), currentLevel.toString(), newLevel.toString()); + } + + String response = "Log level set to: " + level + " for " + updateLogger.getName (); + return Response.status (200).entity (response).build (); + + } + + @GET + @Path("/loggers") + @Produces("text/plain") + @SuppressWarnings("rawtypes") + public Response getLoggers () { + StringBuilder response = new StringBuilder (); + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + List <Logger> loggerList = context.getLoggerList(); + for (Logger logger:loggerList) { + //if (logger.getLevel() != null) { + response.append (logger.getName () + ":" + logger.getLevel () + " (" + logger.getEffectiveLevel () + ")\n"); + //} + } + return Response.status (200).entity (response).build (); + + } + + @GET + @Path("/debug") + @Produces("text/plain") + @SuppressWarnings("rawtypes") + /* + * Debug log is used as a general log to store all the logs events, including events generated by MSO code or by + * components used by MSO. + * This method will only enable/disable the function to store MSO generated events into debug log, + * since those events will also be generated to error, audit, metrics log. + * The events generated by other components will not be affected by this interface. + */ + public Response updateDebugAppender (@DefaultValue("true") @QueryParam("enable") Boolean enable) { + String response; + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + List <Logger> loggerList = context.getLoggerList(); + Logger rootLogger = context.getLogger("ROOT"); + Appender appender = rootLogger.getAppender(DEBUGLOG); + + if (null == appender) { + return Response.status (500).entity ("Not able to found Debug appender. Please verify to make sure the needed logback file is present in the config folder.").build (); + } + + if (enable) { + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG, "", ""); + + for (Logger logger: loggerList) { + if (isMsoLogger (logger.getName ()) && logger.getAppender (DEBUGLOG) == null && logger.getLevel () != null) { + logger.addAppender (appender); + logger.setAdditive(false); + } + } + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG_SUC, "enabled", "", ""); + response = "Debuglog successfully enabled."; + } else { + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG, "", ""); + for (Logger logger: loggerList) { + if (isMsoLogger (logger.getName ())) { + logger.detachAppender (appender); + } + } + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG_SUC, "disabled", "", ""); + response = "Debuglog successfully disabled."; + } + return Response.status (200).entity (response).build (); + + + } + + private boolean isMsoLogger (String loggerName) { + return loggerName.contains (GENERAL_LOGGER) || loggerName.equals (AUDIT_LOGGER) + || loggerName.equals (METRICS_LOGGER); + } + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java b/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java new file mode 100644 index 0000000000..69d2f98324 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +import java.io.IOException; +import java.util.Properties; + +import org.openecomp.mso.logger.MsoLogger; + +public abstract class AbstractMsoProperties { + + public static final int DEFAULT_RELOAD_TIME_MIN=1; + + public static final String RELOAD_TIME_PROPERTY="mso.properties.reload.time.minutes"; + + protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + + protected String propertiesFileName; + + protected int automaticRefreshInMinutes=0; + + public String getPropertiesFileName() { + return propertiesFileName; + } + + public int getAutomaticRefreshInMinutes() { + return automaticRefreshInMinutes; + } + + protected synchronized void reloadPropertiesFile() throws IOException { + this.loadPropertiesFile(this.propertiesFileName); + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + + protected abstract void loadPropertiesFile(String propertiesPath) throws IOException; + + @Override + protected abstract AbstractMsoProperties clone(); + + @Override + public abstract int hashCode(); + + @Override + public abstract boolean equals(Object obj); + + @Override + public abstract String toString(); + + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java b/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java new file mode 100644 index 0000000000..aa791f896e --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +import java.io.FileReader; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; +import org.openecomp.mso.utils.CryptoUtils; + +public class MsoJavaProperties extends AbstractMsoProperties { + + + private Properties msoProperties = new Properties(); + + + public MsoJavaProperties() { + + } + + public synchronized void setProperty(String key,String value) { + msoProperties.setProperty(key, value); + } + + public synchronized String getProperty(String key, String defaultValue) { + if (msoProperties.containsKey(key)) { + return msoProperties.getProperty(key); + } else { + return defaultValue; + } + } + + public synchronized int getIntProperty(String key, int defaultValue) { + + int value = defaultValue; + if (msoProperties.containsKey(key)) { + try { + value = Integer.parseInt(msoProperties.getProperty(key)); + } catch (NumberFormatException e) { + LOGGER.debug("Exception while parsing integer: " + msoProperties.getProperty(key), e); + } + } + return value; + + } + + public synchronized boolean getBooleanProperty(String key, boolean defaultValue) { + + if (msoProperties.containsKey(key)) { + return Boolean.parseBoolean(msoProperties.getProperty(key)); + } else { + return defaultValue; + } + + } + + public synchronized String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { + + if (msoProperties.containsKey(key)) { + try { + return CryptoUtils.decrypt(msoProperties.getProperty(key), encryptionKey); + } catch (GeneralSecurityException e) { + LOGGER.debug("Exception while decrypting property: " + msoProperties.getProperty(key), e); + } + } + return defaultValue; + + } + + public synchronized int size() { + return this.msoProperties.size(); + } + + + @Override + protected synchronized void reloadPropertiesFile() throws IOException { + this.loadPropertiesFile(this.propertiesFileName); + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + @Override + protected synchronized void loadPropertiesFile(String propertiesPath) throws IOException { + + FileReader reader = null; + + propertiesFileName = propertiesPath; + try { + msoProperties.clear(); + reader = new FileReader(propertiesPath); + msoProperties.load(reader); + + } finally { + this.automaticRefreshInMinutes = this.getIntProperty(RELOAD_TIME_PROPERTY, DEFAULT_RELOAD_TIME_MIN); + // Always close the file + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + LOGGER.debug("Exception while closing reader for file:" + propertiesPath, e); + } + } + } + + @Override + public synchronized MsoJavaProperties clone() { + MsoJavaProperties msoCopy = new MsoJavaProperties(); + msoCopy.msoProperties.putAll(msoProperties); + msoCopy.propertiesFileName = this.propertiesFileName; + msoCopy.automaticRefreshInMinutes = this.automaticRefreshInMinutes; + return msoCopy; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((msoProperties == null) ? 0 : msoProperties.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MsoJavaProperties other = (MsoJavaProperties) obj; + if (!msoProperties.equals(other.msoProperties)) { + return false; + } + return true; + } + + @Override + public String toString() { + + StringBuffer response = new StringBuffer(); + response.append("Config file " + propertiesFileName + "(Timer:" + automaticRefreshInMinutes + "mins):" + + System.getProperty("line.separator")); + for (Object key : this.msoProperties.keySet()) { + String propertyName = (String) key; + response.append(propertyName); + response.append("="); + response.append(this.msoProperties.getProperty(propertyName)); + response.append(System.getProperty("line.separator")); + } + response.append(System.getProperty("line.separator")); + response.append(System.getProperty("line.separator")); + return response.toString(); + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java b/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java new file mode 100644 index 0000000000..323c4dbe99 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +import java.io.FileReader; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.mso.utils.CryptoUtils; + + +public class MsoJsonProperties extends AbstractMsoProperties { + + protected ObjectMapper mapper = new ObjectMapper(); + + protected JsonNode jsonRootNode = mapper.createObjectNode(); + + protected MsoJsonProperties() { + + } + + public synchronized JsonNode getJsonRootNode () { + return this.jsonRootNode; + } + + /** + * This method is used to get the text encrypted in the string value of the node. + * @param jsonNode The JsonNode containing the strig to decode + * @param defaultValue The default value in case of issue + * @param encryptionKey The encryption Key in AES 128 bits + * @return the String decrypted + */ + public synchronized String getEncryptedProperty(JsonNode jsonNode, String defaultValue, String encryptionKey) { + + if (jsonNode.isTextual()) { + try { + return CryptoUtils.decrypt(jsonNode.asText(), encryptionKey); + } catch (GeneralSecurityException e) { + LOGGER.debug("Exception while decrypting property: " + jsonNode.asText(), e); + } + } + + return defaultValue; + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + @Override + protected synchronized void loadPropertiesFile(String propertiesPath) throws IOException { + + FileReader reader = null; + + this.propertiesFileName = propertiesPath; + + try { + // Clean + this.jsonRootNode = mapper.createObjectNode(); + + reader = new FileReader(propertiesPath); + + // Try a tree load + this.jsonRootNode = mapper.readValue(reader, JsonNode.class); + + + } finally { + JsonNode reloadJsonProp = this.jsonRootNode.get(RELOAD_TIME_PROPERTY); + if (reloadJsonProp != null) { + this.automaticRefreshInMinutes = reloadJsonProp.asInt(DEFAULT_RELOAD_TIME_MIN); + } else { + this.automaticRefreshInMinutes = DEFAULT_RELOAD_TIME_MIN; + } + + // Always close the file + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + LOGGER.debug("Exception while closing reader for file:" + propertiesFileName, e); + } + } + } + + @Override + public synchronized MsoJsonProperties clone() { + MsoJsonProperties msoCopy = new MsoJsonProperties(); + + ObjectMapper mapper = new ObjectMapper(); + try { + msoCopy.jsonRootNode = mapper.createObjectNode(); + msoCopy.jsonRootNode = mapper.readValue(this.jsonRootNode.toString(), JsonNode.class); + } catch (JsonParseException e) { + LOGGER.debug("JsonParseException when cloning the object:" + this.propertiesFileName, e); + } catch (JsonMappingException e) { + LOGGER.debug("JsonMappingException when cloning the object:" + this.propertiesFileName, e); + } catch (IOException e) { + LOGGER.debug("IOException when cloning the object:" + this.propertiesFileName, e); + } + + msoCopy.propertiesFileName = this.propertiesFileName; + msoCopy.automaticRefreshInMinutes = this.automaticRefreshInMinutes; + return msoCopy; + } + + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((jsonRootNode == null) ? 0 : jsonRootNode.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MsoJsonProperties other = (MsoJsonProperties) obj; + if (jsonRootNode == null) { + if (other.jsonRootNode != null) + return false; + } else if (!jsonRootNode.equals(other.jsonRootNode)) + return false; + return true; + } + + @Override + public String toString() { + StringBuffer response = new StringBuffer(); + response.append("Config file " + propertiesFileName + "(Timer:" + automaticRefreshInMinutes + "mins):" + + System.getProperty("line.separator")); + response.append(this.jsonRootNode.toString()); + response.append(System.getProperty("line.separator")); + response.append(System.getProperty("line.separator")); + return response.toString(); + + } + + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java new file mode 100644 index 0000000000..caf0ffad46 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +/** + * Exception during artifact installation. + */ +public class MsoPropertiesException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = 4095937499475915021L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public MsoPropertiesException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public MsoPropertiesException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java new file mode 100644 index 0000000000..77676314bc --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java @@ -0,0 +1,395 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.ejb.ConcurrencyManagement; +import javax.ejb.ConcurrencyManagementType; +import javax.ejb.LocalBean; +import javax.ejb.Schedule; +import javax.ejb.Singleton; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.utils.CryptoUtils; + +/** + * This EJB Singleton class returns an instance of the mso properties for a specified file. + * This class can handle many config at the same time and is thread safe. + * This instance is a copy of the one cached so it can be modified or reloaded without impacting the others class using + * it. + * The mso properties files loaded and cached here will be reloaded every X second (it's configurable with the init + * method) + * This class can be used as an EJB or can be instantiated directly as long as the EJB has been initialized for the current + * module. Locks are made manually and not using EJB locks to allow this. + * + * + */ +@Singleton(name = "MsoPropertiesFactory") +@ConcurrencyManagement(ConcurrencyManagementType.BEAN) +@LocalBean +@Path("/properties") +public class MsoPropertiesFactory implements Serializable { + + private static final long serialVersionUID = 4365495305496742113L; + + protected static String prefixMsoPropertiesPath = System.getProperty ("mso.config.path"); + + private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL); + + // Keep a static copy of properties for global usage + private static final ConcurrentHashMap <String, MsoPropertiesParameters> msoPropertiesCache; + + static { + if (prefixMsoPropertiesPath == null) { + // Hardcode if nothing is received + prefixMsoPropertiesPath = ""; + } + msoPropertiesCache = new ConcurrentHashMap <String, MsoPropertiesParameters> (); + } + + private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock (); + + public MsoPropertiesFactory () { + + } + + private boolean isJsonFile(String propertiesFilePath) { + return propertiesFilePath.endsWith(".json"); + } + + + private boolean isJavaPropertiesFile (String propertiesFilePath) { + return propertiesFilePath.endsWith(".properties"); + } + + private MsoPropertiesParameters createObjectType (MsoPropertiesParameters msoPropParams, String propertiesFilePath) throws MsoPropertiesException, IOException { + + try { + if (this.isJavaPropertiesFile(propertiesFilePath)) { + + msoPropParams.msoProperties = new MsoJavaProperties(); + msoPropParams.msoPropertiesType = MsoPropertiesParameters.MsoPropertiesType.JAVA_PROP; + } else if (this.isJsonFile(propertiesFilePath)) { + + msoPropParams.msoProperties = new MsoJsonProperties(); + msoPropParams.msoPropertiesType = MsoPropertiesParameters.MsoPropertiesType.JSON_PROP; + } else { + throw new MsoPropertiesException("Unable to load the MSO properties file because format is not recognized (only .json or .properties): " + propertiesFilePath); + } + + msoPropParams.msoProperties.loadPropertiesFile (propertiesFilePath); + + return msoPropParams; + } finally { + if (msoPropParams.msoProperties!=null) { + msoPropParams.refreshCounter = msoPropParams.msoProperties.getAutomaticRefreshInMinutes(); + } + } + + } + + /** + * This method is used to create a MsoProperties file cache and factory. + * The ID is kept in cache even if the config fails to be loaded. + * This is used to maintain the config ID until someone fixes the config file. + * + * @param msoPropertiesID A string representing the key of the config + * @param propertiesFilePath The mso properties file to load + * + * @throws MsoPropertiesException In case of issues with the mso properties loading + * + * @see MsoPropertiesFactory#getMsoJavaProperties() + * @see MsoPropertiesFactory#getMsoJsonProperties() + */ + public void initializeMsoProperties (String msoPropertiesID, + String propertiesFilePath) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + + String msoPropPath="none"; + MsoPropertiesParameters msoPropertiesParams=new MsoPropertiesParameters(); + try { + msoPropPath = prefixMsoPropertiesPath + propertiesFilePath; + if (msoPropertiesCache.get (msoPropertiesID) != null) { + throw new MsoPropertiesException ("The factory contains already an instance of this mso properties: " + + msoPropPath); + } + // Create the global MsoProperties object + msoPropertiesParams = createObjectType(msoPropertiesParams, msoPropPath); + + } catch (FileNotFoundException e) { + throw new MsoPropertiesException ("Unable to load the MSO properties file because it has not been found:" + + msoPropPath, e); + + } catch (IOException e) { + throw new MsoPropertiesException ("Unable to load the MSO properties file because IOException occurs: " + + msoPropPath, e); + } finally { + // put it in all cases, just to not forget about him and attempt a default reload + msoPropertiesCache.put (msoPropertiesID, msoPropertiesParams); + rwl.writeLock ().unlock (); + } + } + + public void removeMsoProperties (String msoPropertiesID) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + try { + if (MsoPropertiesFactory.msoPropertiesCache.remove (msoPropertiesID) == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * This method clears all the configs in cache, the factory will then be free of any config. + * + * @see MsoPropertiesFactory#initializeMsoProperties(String, String) + */ + public void removeAllMsoProperties () { + + rwl.writeLock ().lock (); + try { + MsoPropertiesFactory.msoPropertiesCache.clear (); + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * THis method can be used to change the file and timer fields of an existing MSO properties file. + * + * @param msoPropertiesID The MSO properties ID + * @param newMsoPropPath The new file Path + * @throws MsoPropertiesException In case of the MSO Properties is not found in cache + */ + public void changeMsoPropertiesFilePath (String msoPropertiesID, + String newMsoPropPath) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + try { + MsoPropertiesParameters msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID); + + if (msoPropInCache != null) { + msoPropInCache.msoProperties.propertiesFileName = prefixMsoPropertiesPath + newMsoPropPath; + + } else { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + } finally { + rwl.writeLock ().unlock (); + } + } + + private AbstractMsoProperties getAndCloneProperties(String msoPropertiesID, MsoPropertiesParameters.MsoPropertiesType type) throws MsoPropertiesException { + rwl.readLock ().lock (); + try { + MsoPropertiesParameters msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID); + if (msoPropInCache == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } else { + if (type.equals(msoPropInCache.msoPropertiesType)) { + return msoPropInCache.msoProperties.clone (); + } else { + throw new MsoPropertiesException ("Mso properties is not "+type.name()+" properties type:" + msoPropertiesID); + } + + } + } finally { + rwl.readLock ().unlock (); + } + } + + /** + * Get the MSO Properties (As Java Properties) as a copy of the mso properties cache. + * The object returned can therefore be modified. + * + * @return A copy of the mso properties, properties class can be empty if the file has not been read properly + * @throws MsoPropertiesException If the mso properties does not exist in the cache + */ + public MsoJavaProperties getMsoJavaProperties (String msoPropertiesID) throws MsoPropertiesException { + + return (MsoJavaProperties)getAndCloneProperties(msoPropertiesID,MsoPropertiesParameters.MsoPropertiesType.JAVA_PROP); + } + + /** + * Get the MSO Properties (As JSON Properties) as a copy of the mso properties cache. + * The object returned can therefore be modified. + * + * @return A copy of the mso properties, properties class can be empty if the file has not been read properly + * @throws MsoPropertiesException If the mso properties does not exist in the cache + */ + public MsoJsonProperties getMsoJsonProperties (String msoPropertiesID) throws MsoPropertiesException { + + return (MsoJsonProperties)getAndCloneProperties(msoPropertiesID,MsoPropertiesParameters.MsoPropertiesType.JSON_PROP); + } + + /** + * Get all MSO Properties as a copy of the mso properties cache. + * The objects returned can therefore be modified. + * + * @return A List of copies of the mso properties, can be empty + */ + public List <AbstractMsoProperties> getAllMsoProperties () { + + List <AbstractMsoProperties> resultList = new LinkedList <AbstractMsoProperties> (); + rwl.readLock ().lock (); + try { + + for (MsoPropertiesParameters msoProp:MsoPropertiesFactory.msoPropertiesCache.values ()) { + resultList.add(msoProp.msoProperties.clone()); + } + return resultList; + + } finally { + rwl.readLock ().unlock (); + } + + } + + /** + * This method is not intended to be called, it's used to refresh the config automatically + * + * @return true if Properties have been reloaded, false otherwise + */ + @Schedule(minute = "*/1", hour = "*", persistent = false) + public boolean reloadMsoProperties () { + AbstractMsoProperties msoPropInCache = null; + try { + if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) { + LOGGER.debug ("Busy write lock on mso properties factory, skipping the reloading"); + return false; + } + } catch (InterruptedException e1) { + LOGGER.debug ("Interrupted while trying to acquire write lock on mso properties factory, skipping the reloading"); + Thread.currentThread ().interrupt (); + return false; + } + try { + for (Entry <String, MsoPropertiesParameters> entryMsoPropTimer : MsoPropertiesFactory.msoPropertiesCache.entrySet ()) { + + if (entryMsoPropTimer.getValue ().refreshCounter <= 1) { + // It's time to reload the config + msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (entryMsoPropTimer.getKey ()).msoProperties; + try { + AbstractMsoProperties oldProps = msoPropInCache.clone (); + msoPropInCache.reloadPropertiesFile (); + entryMsoPropTimer.getValue().refreshCounter=entryMsoPropTimer.getValue().msoProperties.getAutomaticRefreshInMinutes(); + + if (!msoPropInCache.equals (oldProps)) { + LOGGER.info (MessageEnum.LOAD_PROPERTIES_SUC, msoPropInCache.getPropertiesFileName (), "", ""); + } + } catch (FileNotFoundException ef) { + LOGGER.error (MessageEnum.NO_PROPERTIES, msoPropInCache.propertiesFileName, "", "", MsoLogger.ErrorCode.PermissionError, "", ef); + } catch (Exception e) { + LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, msoPropInCache.propertiesFileName, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "", e); + } + + } else { + --entryMsoPropTimer.getValue().refreshCounter; + } + } + return true; + } catch (Exception e) { + LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "", e); + return false; + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * This method can be used to known if the MSO properties instance hold is different from the one in cache + * + * @param msoPropertiesID The MSO properties ID + * @param oldMsoProperties The MSO Properties instance that must be compared to + * @return True if they are the same, false otherwise + * @throws MsoPropertiesException + */ + public boolean propertiesHaveChanged (String msoPropertiesID, AbstractMsoProperties oldMsoProperties) throws MsoPropertiesException { + rwl.readLock ().lock (); + try { + if (MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID) == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + + AbstractMsoProperties msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID).msoProperties; + if (oldMsoProperties != null) { + return !oldMsoProperties.equals (msoPropInCache); + } else { + return msoPropInCache != null; + } + } finally { + rwl.readLock ().unlock (); + } + } + + @GET + @Path("/show") + @Produces("text/plain") + public Response showProperties () { + + List <AbstractMsoProperties> listMsoProp = this.getAllMsoProperties (); + StringBuffer response = new StringBuffer (); + + if (listMsoProp.isEmpty ()) { + response.append ("No file defined"); + } + + for (AbstractMsoProperties properties : listMsoProp) { + + response.append(properties.toString()); + } + + return Response.status (200).entity (response).build (); + } + + @GET + @Path("/encrypt/{value}/{cryptKey}") + @Produces("text/plain") + public Response encryptProperty (@PathParam("value") String value, @PathParam("cryptKey") String cryptKey) { + try { + String encryptedValue = CryptoUtils.encrypt (value, cryptKey); + return Response.status (200).entity (encryptedValue).build (); + } catch (Exception e) { + LOGGER.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Encryption error", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Error in encrypting property", e); + return Response.status (500).entity (e.getMessage ()).build (); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java new file mode 100644 index 0000000000..358550a2bb --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +public class MsoPropertiesParameters { + + protected enum MsoPropertiesType {JSON_PROP,JAVA_PROP}; + + protected MsoPropertiesType msoPropertiesType; + + protected int refreshCounter; + + protected AbstractMsoProperties msoProperties; +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java new file mode 100644 index 0000000000..38e3ae3650 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.properties; + + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +/** + * This class will attempt to initialize MSO Properties when part of a web application. + * It will look for the configuration file mso.properties in the + * following order: + * 1. In an init-param "mso.configuration" in web.xml + * 2. In a system property "mso.configuration" + * 3. In the default location "/etc/ecomp/mso/config/mso.properties" + * + * If all else fails, the MSO Properties will go uninitialized, and will + * attempt to use the default constructors within the MsoProperties class. + * + * + */ +@WebListener +public class MsoPropertyInitializer implements ServletContextListener +{ + + private MsoPropertiesFactory msoPropertiesFactory=new MsoPropertiesFactory(); + + public MsoPropertyInitializer () { + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + // Nothing to do... + } + + + @Override + public void contextInitialized(ServletContextEvent event) + { + + // Note - this logger may be before or after MSO Logging configuration applied + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + try { + // Look first in the init-parameters + String msoPropConfigParam = event.getServletContext().getInitParameter("mso.configuration"); + if (msoPropConfigParam != null && !msoPropConfigParam.isEmpty() ) { + String[] configFileSplit = msoPropConfigParam.split(","); + for (String msoPropConfig:configFileSplit) { + String[] msoPropDecoded = msoPropConfig.split("="); + + try { + msoPropertiesFactory.initializeMsoProperties(msoPropDecoded[0], msoPropDecoded[1]); + initLogger.info(MessageEnum.LOAD_PROPERTIES_SUC, msoPropDecoded[1], "", ""); + initLogger.debug("Mso properties successfully loaded:"+msoPropDecoded[1]+",ID:"+msoPropDecoded[0]+")"); + } catch (MsoPropertiesException e) { + initLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, msoPropDecoded[1] + ". MSO Properties failed due to an mso properties exception", "", "", MsoLogger.ErrorCode.DataError, "Error in contextInitialized", e); + } + } + } + } + catch (Exception e) { + initLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. MSO Properties failed to initialize completely", "", "", MsoLogger.ErrorCode.DataError, "", e); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/CheckResults.java b/common/src/main/java/org/openecomp/mso/utils/CheckResults.java new file mode 100644 index 0000000000..3e77a4c808 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/CheckResults.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.utils; + + + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "checkresults") +public class CheckResults { + + @XmlElement(name = "checkresult") + private List <CheckResult> results; + + public CheckResults () { + results = new ArrayList <CheckResult> (); + } + + public List <CheckResult> getResults () { + return results; + } + + public void addHostCheckResult (String hostname, int state, String output) { + CheckResult newResult = new CheckResult (); + newResult.setType ("host"); + newResult.setHostname (hostname); + newResult.setState (state); + newResult.setOutput (output); + results.add (newResult); + } + + public void addServiceCheckResult (String hostname, String servicename, int state, String output) { + CheckResult newResult = new CheckResult (); + newResult.setType ("service"); + newResult.setHostname (hostname); + newResult.setServicename (servicename); + newResult.setState (state); + newResult.setOutput (output); + results.add (newResult); + } + + public static class CheckResult { + + private String type; + private String hostname; + private String servicename; + private int state; + private String output; + + @XmlAttribute(required = true) + public String getType () { + return type; + } + + public void setType (String type) { + this.type = type; + } + + @XmlElement(required = true) + public String getHostname () { + return hostname; + } + + public void setHostname (String hostname) { + this.hostname = hostname; + } + + @XmlElement(required = false) + public String getServicename () { + return servicename; + } + + public void setServicename (String servicename) { + this.servicename = servicename; + } + + @XmlElement(required = true) + public int getState () { + return state; + } + + public void setState (int state) { + this.state = state; + } + + @XmlElement(required = true) + public String getOutput () { + return output; + } + + public void setOutput (String output) { + this.output = output; + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java b/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java new file mode 100644 index 0000000000..c926903cf3 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.utils; + + + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + + +/** + * CryptoUtils adapted from RTTP client. + * + */ +public final class CryptoUtils { + + public static final String AES = "AES"; + + /** + * encrypt a value and generate a keyfile + * if the keyfile is not found then a new one is created + * + * @throws GeneralSecurityException + */ + public static String encrypt (String value, String keyString) throws GeneralSecurityException { + SecretKeySpec sks = getSecretKeySpec (keyString); + Cipher cipher = Cipher.getInstance (CryptoUtils.AES); + cipher.init (Cipher.ENCRYPT_MODE, sks, cipher.getParameters ()); + byte[] encrypted = cipher.doFinal (value.getBytes ()); + return byteArrayToHexString (encrypted); + } + + /** + * decrypt a value + * + * @throws GeneralSecurityException + */ + public static String decrypt (String message, String keyString) throws GeneralSecurityException { + SecretKeySpec sks = getSecretKeySpec (keyString); + Cipher cipher = Cipher.getInstance (CryptoUtils.AES); + cipher.init (Cipher.DECRYPT_MODE, sks); + byte[] decrypted = cipher.doFinal (hexStringToByteArray (message)); + return new String (decrypted); + } + + private static SecretKeySpec getSecretKeySpec (String keyString) throws NoSuchAlgorithmException { + byte[] key = hexStringToByteArray (keyString); + SecretKeySpec sks = new SecretKeySpec (key, CryptoUtils.AES); + return sks; + } + + public static String byteArrayToHexString (byte[] b) { + StringBuffer sb = new StringBuffer (b.length * 2); + for (int i = 0; i < b.length; i++) { + int v = b[i] & 0xff; + if (v < 16) { + sb.append ('0'); + } + sb.append (Integer.toHexString (v)); + } + return sb.toString ().toUpperCase (); + } + + private static byte[] hexStringToByteArray (String s) { + byte[] b = new byte[s.length () / 2]; + for (int i = 0; i < b.length; i++) { + int index = i * 2; + int v = Integer.parseInt (s.substring (index, index + 2), 16); + b[i] = (byte) v; + } + return b; + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java b/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java new file mode 100644 index 0000000000..3e8c5e95d3 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.utils; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +import java.util.UUID; + +/** + */ +public class UUIDChecker { + + private UUIDChecker() { + + } + + public static boolean isValidUUID (String id) { + try { + if (null == id) { + return false; + } + UUID uuid = UUID.fromString(id); + return uuid.toString().equalsIgnoreCase(id); + } catch (IllegalArgumentException iae) { + return false; + } + } + + private static String getUUID () { + return UUID.randomUUID().toString(); + } + + public static String verifyOldUUID (String oldId, MsoLogger msoLogger) { + if (!UUIDChecker.isValidUUID(oldId)) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(newId, null); + msoLogger.info(MessageEnum.APIH_REPLACE_REQUEST_ID, oldId, "", ""); + return newId; + } + MsoLogger.setLogContext(oldId, null); + return oldId; + } + + public static String generateUUID (MsoLogger msoLogger) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(newId, null); + msoLogger.info(MessageEnum.APIH_GENERATED_REQUEST_ID, newId, "", ""); + return newId; + } + + public static String generateServiceInstanceID (MsoLogger msoLogger) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(null, newId); + msoLogger.info(MessageEnum.APIH_GENERATED_SERVICE_INSTANCE_ID, newId, "", ""); + return newId; + } +} |