diff options
author | 2019-12-14 00:50:38 +0100 | |
---|---|---|
committer | 2019-12-16 11:26:39 +0000 | |
commit | 6b98928b7b1b0ebc28d2ef286e8c932fca67c305 (patch) | |
tree | d734c78f257acfb7dd3dc4a74229ee23d93d79e3 /sdnr/wt/devicemanager/provider/src/main/java | |
parent | 2cf702de0b65fe132ec32b6abfffe4c2c976dca0 (diff) |
add new devicemanager
v2 add disaggregated devicemanager bundled
Issue-ID: SDNC-1007
Signed-off-by: herbert <herbert.eiselt@highstreet-technologies.com>
Change-Id: Ibb65f7f21deade7b3cef62c53b439519a931e301
Signed-off-by: herbert <herbert.eiselt@highstreet-technologies.com>
Diffstat (limited to 'sdnr/wt/devicemanager/provider/src/main/java')
110 files changed, 14897 insertions, 0 deletions
diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiProviderClient.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiProviderClient.java new file mode 100644 index 000000000..2cc878c72 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiProviderClient.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl; + +import java.util.List; +import java.util.Optional; +import javax.annotation.Nonnull; +import org.onap.ccsdk.features.sdnr.wt.common.HtAssert; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPResponseFromDevicemanager; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.InventoryProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.config.AaiConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.legacy.InventoryInformation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AaiProviderClient implements DeviceManagerService, AutoCloseable { + + private static Logger LOG = LoggerFactory.getLogger(AaiProviderClient.class); + @SuppressWarnings("unused") // @TODO Remove code + private static boolean reloadConfigFlag; + private static final IConfigChangedListener configChangedListener = () -> reloadConfigFlag = true; + + private final AaiConfig config; + private final DeviceManagerImpl deviceManager; + private final ConfigurationFileRepresentation htconfig; + + + public AaiProviderClient(@Nonnull ConfigurationFileRepresentation cfg, DeviceManagerImpl devMgr) { + HtAssert.nonnull(cfg); + this.config = new AaiConfig(cfg); + LOG.debug("AaiProviderClient configuration setting: {}", this.config); + this.htconfig = cfg; + this.htconfig.registerConfigChangedListener(configChangedListener); + this.deviceManager = devMgr; + + } + + public AaiConfig getConfig() { + return this.config; + } + + public void onDeviceRegistered(String mountPointName) { + if (this.config.isOff()) { + return; + } + NetworkElement ne = this.deviceManager != null ? this.deviceManager.getNeByMountpoint(mountPointName) : null; + Optional<InventoryProvider> oip = ne != null ? ne.getService(InventoryProvider.class) : Optional.empty(); + this.onDeviceRegistered(mountPointName, + oip.isPresent() ? oip.get().getInventoryInformation("MWPS") : InventoryInformation.getDefault()); + } + + public void onDeviceRegistered(String mountPointName, InventoryInformation i) { + if (this.config.isOff()) { + return; + } + new Thread(new AaiCreateRequestRunnable(mountPointName, i.getType(), i.getModel(), i.getVendor(), + i.getDeviceIpv4(), i.getInterfaceUuidList())).start(); + } + + public void onDeviceUnregistered(String mountPointName) { + if (this.config.isOff()) { + return; + } + if (this.config.doDeleteOnMountPointRemoved()) { + new Thread(new AaiDeleteRequestRunnable(mountPointName)).start(); + } else { + LOG.debug("prevent deleting device {} by config", mountPointName); + } + } + + @Override + public void close() throws Exception { + this.htconfig.unregisterConfigChangedListener(configChangedListener); + } + + private class AaiCreateRequestRunnable implements Runnable { + + private static final int RESPCODE_NOTFOUND = BaseHTTPResponseFromDevicemanager.CODE404; + private static final int RESPCODE_FOUND = BaseHTTPResponseFromDevicemanager.CODE200; + private final AaiWebApiClient mClient; + private final String pnfId; + private final String type; + private final String model; + private final String vendor; + private final String oamIp; + private final List<String> ifaces; + private final int timeout; + + public AaiCreateRequestRunnable(String pnfId, String type, String model, String vendor, String oamIp, + List<String> ifaces) { + this.pnfId = pnfId; + this.type = type; + this.model = model; + this.vendor = vendor; + this.oamIp = oamIp; + this.ifaces = ifaces; + this.timeout = AaiProviderClient.this.config.getConnectionTimeout(); + this.mClient = new AaiWebApiClient(AaiProviderClient.this.config.getBaseUrl(), + AaiProviderClient.this.config.getHeaders(), AaiProviderClient.this.config.getTrustAll(), + AaiProviderClient.this.config.getPcks12CertificateFilename(), + AaiProviderClient.this.config.getPcks12CertificatePassphrase()); + } + + @Override + public void run() { + LOG.debug("check if pnfid {} exists", pnfId); + this.mClient.setTimeout(timeout); + int responseCode = this.mClient.pnfCheckIfExists(pnfId); + if (responseCode == RESPCODE_NOTFOUND) { + LOG.debug("do pnfCreate for {}", pnfId); + this.mClient.pnfCreate(pnfId, type, model, vendor, oamIp, ifaces); + } else if (responseCode == RESPCODE_FOUND) { + LOG.debug("pnfid {} found, nothing to do", pnfId); + } else { + LOG.warn("unhandled response code: {}", responseCode); + } + } + }; + + private class AaiDeleteRequestRunnable implements Runnable { + + private final AaiWebApiClient mClient; + private final String pnfId; + private final int timeout; + + + public AaiDeleteRequestRunnable(String pnfId) { + this.pnfId = pnfId; + this.timeout = AaiProviderClient.this.config.getConnectionTimeout(); + this.mClient = new AaiWebApiClient(AaiProviderClient.this.config.getBaseUrl(), + AaiProviderClient.this.config.getHeaders(), AaiProviderClient.this.config.getTrustAll(), + AaiProviderClient.this.config.getPcks12CertificateFilename(), + AaiProviderClient.this.config.getPcks12CertificatePassphrase()); + } + + @Override + public void run() { + this.mClient.setTimeout(this.timeout); + this.mClient.pnfDelete(pnfId); + } + }; + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiWebApiClient.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiWebApiClient.java new file mode 100644 index 000000000..db2ba8d23 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/AaiWebApiClient.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPClientFromDevicemanager; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPResponseFromDevicemanager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AaiWebApiClient extends BaseHTTPClientFromDevicemanager { + + private static Logger LOG = LoggerFactory.getLogger(AaiWebApiClient.class); + private static final String PNF_JSON_INTERFACE_TEMPLATE = " {\n" + + " \"interface-name\": \"@interface@\",\n" + " \"speed-value\": \"300\",\n" + + " \"speed-units\": \"MBit/s\",\n" + + " \"port-description\": \"Air Interface (MWPS)\",\n" + + " \"equipment-identifier\": \"@pnfId@-@interface@\",\n" + + " \"interface-role\": \"Wireless\",\n" + + " \"interface-type\": \"Air Interface (MWPS)\",\n" + + " \"resource-version\": \"@model@\",\n" + " \"relationship-list\": [\n" + + " {\n" + + " \"related-to\": \"A keyword provided by A&AI to indicate type of node.\",\n" + + " \"related-link\": \"URL to the object in A&AI.\",\n" + + " \"relationship-data\": [\n" + " {\n" + + " \"relationship-key\": \"A keyword provided by A&AI to indicate an attribute.\",\n" + + " \"relationship-value\": \"Value of the attribute\"\n" + + " }\n" + " ],\n" + + " \"related-to-property\": [\n" + " {\n" + + " \"property-key\": \"Key part of a key/value pair\",\n" + + " \"property-value\": \"Value part of a key/value pair\"\n" + + " }\n" + " ]\n" + " }\n" + " ]\n" + + " }\n"; + private static final String PNF_JSON_TEMPLATE = "{\n" + " \"pnf-name\": \"@pnfId@\",\n" + + " \"pnf-id\": \"@pnfId@\",\n" + " \"equip-type\": \"@type@\",\n" + + " \"equip-model\": \"@model@\",\n" + " \"equip-vendor\": \"@vendor@\",\n" + + " \"ipaddress-v4-oam\": \"@oamIp@\",\n" + " \"in-maint\": false,\n" + + " \"prov-status\":\"PROV\",\n" + " \"p-interfaces\": @interface-list@\n" + "}\n" + ""; + private static final String PNF_URI = "network/pnfs/pnf/"; + private static final String EMPTY_MESSAGE = ""; + + private final Map<String, String> headerMap; + + + public AaiWebApiClient(String baseUrl, Map<String, String> headers, boolean trustAllCerts) { + this(baseUrl, headers, trustAllCerts, null, null); + } + + public AaiWebApiClient(String baseUrl, Map<String, String> headers, boolean trustAllCerts, String certFilename, + String passphrase) { + super(baseUrl, trustAllCerts, certFilename, passphrase, BaseHTTPClientFromDevicemanager.getSslCertPcks()); + + this.headerMap = new HashMap<>(); + this.headerMap.putAll(headers); + this.headerMap.put("Content-Type", "application/json"); + this.headerMap.put("Accept", "application/json"); + } + + /** + * Create and specify defition parametrs of pnf + * @param pnfId name + * @param type type + * @param model model + * @param vendor vendor + * @param oamIp ip + * @param ifaces interfaces + * @return true if http response code was 200 or false if not. + */ + public boolean pnfCreate(String pnfId, String type, String model, String vendor, String oamIp, + List<String> ifaces) { + LOG.debug("registering {} (type={}, model={}, vendor={},ip={})", pnfId, type, model, vendor, oamIp); + String message = getPnfTemplateFilled(pnfId, type, model, vendor, oamIp, ifaces); + return pnfRequest(pnfId, "PUT", message) == 200; + } + + /** + * Unregister + * @param pnfId name + * @return true if http response code was 200 or false if not. + */ + public boolean pnfDelete(String pnfId) { + LOG.debug("unregistering {}", pnfId); + return pnfRequest(pnfId, "DELETE", EMPTY_MESSAGE) == 200; + } + + /** + * Send registration request + * @param pnfId name + * @return error accoring to http response code or -1 + */ + public int pnfCheckIfExists(String pnfId) { + LOG.debug("check for {}", pnfId); + return pnfRequest(pnfId, "GET", EMPTY_MESSAGE); + } + + /* + * Private classes + */ + + private int pnfRequest(String pnfId, String method, String message) { + BaseHTTPResponseFromDevicemanager response; + try { + String uri = PNF_URI + URLParamEncoder.encode(pnfId); + response = this.sendRequest(uri, method, message, headerMap); + LOG.debug("finished with responsecode {}", response.code); + return response.code; + } catch (IOException e) { + LOG.warn("problem registering {} : {}", pnfId, e.getMessage()); + return -1; + } + } + + + private static String getPnfTemplateFilled(String pnfId, String type, String model, String vendor, String oamIp, + List<String> ifaces) { + return PNF_JSON_TEMPLATE.replace("@pnfId@", pnfId).replace("@type@", type).replace("@model@", model) + .replace("@vendor@", vendor).replace("@oamIp@", oamIp) + .replace("@interface-list@", getPnfTemplateInterfaceList(pnfId, ifaces, model)); + } + + private static String getPnfTemplateInterfaceList(String pnfId, List<String> ifaces, String model) { + StringBuffer s = new StringBuffer(); + s.append("["); + if (ifaces != null) { + for (int i = 0; i < ifaces.size(); i++) { + if (i > 0) { + s.append(","); + } + s.append(PNF_JSON_INTERFACE_TEMPLATE.replace("@interface@", ifaces.get(i))); + } + } + s.append("]"); + + return s.toString().replace("@pnfId@", pnfId).replace("@model@", model); + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/URLParamEncoder.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/URLParamEncoder.java new file mode 100644 index 000000000..2e8b44fd7 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/URLParamEncoder.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl; + +class URLParamEncoder { + + public static String encode(String input) { + StringBuilder resultStr = new StringBuilder(); + for (char ch : input.toCharArray()) { + if (isUnsafe(ch)) { + resultStr.append('%'); + resultStr.append(toHex(ch / 16)); + resultStr.append(toHex(ch % 16)); + } else { + resultStr.append(ch); + } + } + return resultStr.toString(); + } + + private static char toHex(int ch) { + return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10); + } + + private static boolean isUnsafe(char ch) { + if (ch > 128 || ch < 0) { + return true; + } + return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiClientPropertiesFile.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiClientPropertiesFile.java new file mode 100644 index 000000000..671aea5c2 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiClientPropertiesFile.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.config; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +public class AaiClientPropertiesFile { + + private final File mFile; + private String mPCKS12CertFilename; + private String mPCKS12Passphrase; + private boolean mTrustInsecureSSL; + private String mApplicationIdentifier; + private String mRemoteUrl; + private int mConnectionTimeout; + private int mReadTimeout; + + public String getFilename() { + return this.mFile.getAbsolutePath(); + } + + public String getPCKS12CertFilename() { + return this.mPCKS12CertFilename; + } + + public String getPCKS12Passphrase() { + return this.mPCKS12Passphrase; + } + + public boolean trustInsecureSSL() { + return this.mTrustInsecureSSL; + } + + public String getApplicationIdentifier() { + return this.mApplicationIdentifier; + } + + public String getRemoteUrl() { + return this.mRemoteUrl; + } + + public int getConnectionTimeout() { + return this.mConnectionTimeout; + } + + public int getReadTimeout() { + return this.mReadTimeout; + } + + public boolean exists() { + return this.mFile.exists(); + } + + public AaiClientPropertiesFile(String filename) { + this.mFile = new File(filename); + } + + public void load() throws IOException, NumberFormatException { + Properties defaultProps = new Properties(); + FileInputStream in = new FileInputStream(this.mFile); + defaultProps.load(in); + this.mPCKS12CertFilename = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.ssl.key", null); + this.mPCKS12Passphrase = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd", null); + this.mTrustInsecureSSL = defaultProps + .getProperty("org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore", "false").equals("true"); + this.mApplicationIdentifier = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.application", null); + this.mRemoteUrl = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.uri", null); + this.mConnectionTimeout = Integer.parseInt(defaultProps.getProperty("connection.timeout", "60000")); + this.mReadTimeout = Integer.parseInt(defaultProps.getProperty("read.timeout", "60000")); + in.close(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiConfig.java new file mode 100644 index 000000000..9991f782c --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/aaiconnector/impl/config/AaiConfig.java @@ -0,0 +1,262 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.config; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Properties; +import org.json.JSONArray; +import org.json.JSONException; +import org.onap.ccsdk.features.sdnr.wt.common.HtAssert; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AaiConfig implements Configuration { + + private static Logger LOG = LoggerFactory.getLogger(AaiConfig.class); + + private static final String SECTION_MARKER_AAI = "aai"; + + private enum Config { + AAIPROP_FILE("aaiPropertiesFile", "null"), + BASEURL("aaiUrl", "off", "org.onap.ccsdk.sli.adaptors.aai.uri"), + USERCREDENTIALS("aaiUserCredentials",""), + HEADERS("aaiHeaders","[\"X-TransactionId: 9999\"]"), + DELETEONMOUNTPOINTREMOVED("aaiDeleteOnMountpointRemove",false), + TRUSTALLCERTS("aaiTrustAllCerts",false, "org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore"), + APIVERSION("aaiApiVersion", "aai/v13"), + PCKS12CERTFILENAME("aaiPcks12ClientCertFile","", "org.onap.ccsdk.sli.adaptors.aai.ssl.key"), + PCKS12PASSPHRASE("aaiPcks12ClientCertPassphrase","", "org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd"), + CONNECTIONTIMEOUT("aaiClientConnectionTimeout",String.valueOf(DEFAULT_VALUE_CONNECTION_TIMEOUT), "connection.timeout"), //in ms; + APPLICATIONID("aaiApplicationId","SDNR", "org.onap.ccsdk.sli.adaptors.aai.application"), + HTTPREADTIMEOUT("aaiReadTimeout", "60000", "read.timeout"); + + private String propertyKey; + private String propertyValue; + private Optional<String> propertyKeySecondFile; + + Config(String propertyKey, Object propertyValue) { + this.propertyKey = propertyKey; + this.propertyValue = propertyValue.toString(); + this.propertyKeySecondFile = Optional.empty(); + } + + Config(String propertyKey, Object propertyValue, String propertyKeySecondFile) { + this(propertyKey, propertyValue); + this.propertyKeySecondFile = Optional.of(propertyKeySecondFile); + } + } + + private static final long DEFAULT_VALUE_CONNECTION_TIMEOUT = 30000; //in ms + private static final String HEADER_KEY_APPLICATION = "X-FromAppId"; + + private final ConfigurationFileRepresentation configuration; + + public AaiConfig(ConfigurationFileRepresentation configuration) { + HtAssert.nonnull(configuration); + this.configuration = configuration; + this.configuration.addSection(SECTION_MARKER_AAI); + defaults(); + } + + /* + * Getter + */ + + public boolean doDeleteOnMountPointRemoved() { + return configuration.getPropertyBoolean(SECTION_MARKER_AAI, Config.DELETEONMOUNTPOINTREMOVED.propertyKey); + } + + public boolean getTrustAll() { + return configuration.getPropertyBoolean(SECTION_MARKER_AAI, Config.TRUSTALLCERTS.propertyKey); + } + + public String getPcks12CertificateFilename() { + return configuration.getProperty(SECTION_MARKER_AAI, Config.PCKS12CERTFILENAME.propertyKey); + } + + public String getPcks12CertificatePassphrase() { + return configuration.getProperty(SECTION_MARKER_AAI, Config.PCKS12PASSPHRASE.propertyKey); + } + + public int getConnectionTimeout() { + long res = configuration.getPropertyLong(SECTION_MARKER_AAI, Config.PCKS12PASSPHRASE.propertyKey).orElse(DEFAULT_VALUE_CONNECTION_TIMEOUT); + return (int)res; + } + + public boolean isOff() { + return configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey).equalsIgnoreCase("off"); + } + + public String getBaseUri() { + String res = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey); + if (!res.startsWith("/")) { + res = "/" + res; + } + return res; + } + + public String getBaseUrl() { + if (isOff()) { + return ""; + } else { + String url = configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey); + if (!url.endsWith("/")) { + url += "/"; + } + String apiVersion = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey); + if (apiVersion.startsWith("/")) { + apiVersion = apiVersion.substring(1); + } + return url + apiVersion; + } + } + + public Map<String, String> getHeaders() { + + Map<String,String> headers = _parseHeadersMap(configuration.getProperty(SECTION_MARKER_AAI, Config.HEADERS.propertyKey)); + headers.put(HEADER_KEY_APPLICATION, configuration.getProperty(SECTION_MARKER_AAI, Config.APPLICATIONID.propertyKey)); + + String credentials = configuration.getProperty(SECTION_MARKER_AAI, Config.USERCREDENTIALS.propertyKey); + if (!nullorempty(credentials)) { + String credentialParts[] = credentials.split(":"); + if (credentialParts.length == 2) { + // 0:username 1:password + String s = headers.getOrDefault("Authorization", null); + if (nullorempty(s) && !nullorempty(credentialParts[0]) && !nullorempty(credentialParts[1])) { + headers.put("Authorization", + "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes()))); + } + } + } + return headers; + } + + @Override + public String getSectionName() { + return SECTION_MARKER_AAI; + } + + @Override + public void defaults() { + for (Config conf : Config.values()) { + configuration.setPropertyIfNotAvailable(SECTION_MARKER_AAI, conf.propertyKey, conf.propertyValue); + } + // If file is available, the content is assigned to related parameters. + getAaiPropertiesFile(); + } + + @Override + public String toString() { + return "AaiConfig [doDeleteOnMountPointRemoved()=" + doDeleteOnMountPointRemoved() + ", getTrustAll()=" + + getTrustAll() + ", getPcks12CertificateFilename()=" + getPcks12CertificateFilename() + + ", getPcks12CertificatePassphrase()=" + getPcks12CertificatePassphrase() + ", getConnectionTimeout()=" + + getConnectionTimeout() + ", isOff()=" + isOff() + ", getBaseUri()=" + getBaseUri() + ", getBaseUrl()=" + + getBaseUrl() + ", getHeaders()=" + getHeaders() + ", getSectionName()=" + getSectionName() + "]"; + } + + /* + * Private + */ + + private boolean nullorempty(String s) { + return s == null || s.isEmpty(); + } + + /** + * Convert headers to configuration string. + * @param headers + * @return + */ + @SuppressWarnings("unused") + private static String _printHeadersMap(Map<String, String> headers) { + String r = "["; + if (headers != null) { + int i = 0; + for (Entry<String, String> entry : headers.entrySet()) { + if (i > 0) { + r += ","; + } + r += "\"" + entry.getKey() + ":" + entry.getValue() + "\""; + i++; + } + } + r += "]"; + return r; + } + + private static Map<String, String> _parseHeadersMap(String s) throws JSONException { + Map<String, String> r = new HashMap<>(); + JSONArray a =null; + try { + a= new JSONArray(s); + } + catch(Exception e) { + LOG.warn("problem parsing aai headers {}: {}",s,e); + } + if (a != null && a.length() > 0) { + for (int i = 0; i < a.length(); i++) { + String item = a.getString(i); + String[] hlp = item.split(":"); + if (hlp.length > 1) { + r.put(hlp[0], hlp[1]); + } + } + } + return r; + } + + /** + * Read file if available and assign to configuration + */ + private void getAaiPropertiesFile() { + String aaiPropertiesFileName = configuration.getProperty(SECTION_MARKER_AAI, Config.AAIPROP_FILE.propertyKey); + File f = new File(aaiPropertiesFileName); + if (f.exists()) { + try { + FileInputStream in = new FileInputStream(f); + Properties defaultProps = new Properties(); + defaultProps.load(in); + + for (Config conf : Config.values()) { + if (conf.propertyKeySecondFile.isPresent()) { + String config = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.ssl.key", conf.propertyValue); + LOG.debug("Property file assign {} = {} ",conf.propertyKey, config ); + configuration.setPropertyIfNotAvailable( + SECTION_MARKER_AAI, + conf.propertyKey, + config); + } + } + + in.close(); + } catch (IOException e) { + LOG.warn("Problem during file read {} {}", f.getAbsoluteFile(), e); + } + } + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/archiveservice/ArchiveCleanService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/archiveservice/ArchiveCleanService.java new file mode 100644 index 000000000..d5e4ea618 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/archiveservice/ArchiveCleanService.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.archiveservice; + +import java.util.Date; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.eclipse.jdt.annotation.NonNull; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.database.config.EsConfig; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.ArchiveCleanProvider; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService; +import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; + +public class ArchiveCleanService implements AutoCloseable, IConfigChangedListener, Runnable,ClusterSingletonService { + + private static final Logger LOG = LoggerFactory.getLogger(ArchiveCleanService.class); + private static final ServiceGroupIdentifier IDENT = ServiceGroupIdentifier.create("ElasticSearchArchiveCleanService"); + + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private final ArchiveCleanProvider[] indexCleanList; + private final ConfigurationFileRepresentation htConfig; + private final Runnable doClean; + + private final EsConfig esConfig; + private Future<?> taskReference; + private boolean isMaster; + + public ArchiveCleanService(ConfigurationFileRepresentation config, ArchiveCleanProvider... indexCleanList) { + this.htConfig = config; + this.htConfig.registerConfigChangedListener(this); + this.esConfig = new EsConfig(htConfig); + this.indexCleanList = indexCleanList; + this.doClean = this; + this.taskReference = null; + + this.reinit(); + } + + private void reinit() { + + if (taskReference != null) { + taskReference.cancel(false); + } + if(this.isMaster) { + if (this.esConfig.getArchiveCheckIntervalSeconds() > 0) { + LOG.info("DBCleanService is turned on for entries older than {} seconds", + this.esConfig.getArchiveLifetimeSeconds()); + taskReference = this.scheduler.scheduleAtFixedRate(doClean, 0, + this.esConfig.getArchiveCheckIntervalSeconds(), TimeUnit.SECONDS); + } else { + LOG.info("DBCleanService is turned off"); + } + } + else { + LOG.info("service is inactive on this node. active on another node."); + } + } + + public Date getDateForOldElements() { + return new Date(System.currentTimeMillis() - esConfig.getArchiveLifetimeSeconds() * 1000); + } + + public int countOldEntries() { + int cnt = 0; + Date olderAreOutdated = getDateForOldElements(); + for (ArchiveCleanProvider indexCleanElement : indexCleanList) { + if (indexCleanElement != null) { + indexCleanElement.getNumberOfOldObjects(olderAreOutdated); + } + } + return cnt; + } + + @Override + public void run() { + + try { + int removed = 0; + Date olderElementToBeRemoved = getDateForOldElements(); + LOG.trace("cleaning logs from entries older than {}", olderElementToBeRemoved); + + for (ArchiveCleanProvider indexCleanElement : indexCleanList) { + if (indexCleanElement != null) { + removed += indexCleanElement.doIndexClean(olderElementToBeRemoved); + } + } + if (removed > 0) { + LOG.trace("Removed elements: {}",removed); + } + } catch (Exception e) { + LOG.warn("problem executing dbclean", e); + } + } + + @Override + public void onConfigChanged() { + LOG.debug("config changed. reninit timer"); + }; + + @Override + public void close() throws Exception { + this.htConfig.unregisterConfigChangedListener(this); + this.scheduler.shutdown(); + } + + @Override + public String toString() { + return "ArchivCleanService [ArchiveCheckIntervalSeconds=" + esConfig.getArchiveCheckIntervalSeconds() + + "ArchiveLifetimeSeconds=" + esConfig.getArchiveLifetimeSeconds() + "]"; + } + + @SuppressWarnings("null") + @Override + public @NonNull ServiceGroupIdentifier getIdentifier() { + return IDENT; + } + + @Override + public void instantiateServiceInstance() { + LOG.info("We take Leadership"); + this.isMaster=true; + this.reinit(); + } + + @Override + public ListenableFuture<? extends Object> closeServiceInstance() { + LOG.info("We lost Leadership"); + this.isMaster=false; + this.reinit(); + return Futures.immediateFuture(null); + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/NetworkElementCoreData.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/NetworkElementCoreData.java new file mode 100644 index 000000000..a86944c82 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/NetworkElementCoreData.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base; + +import org.eclipse.jdt.annotation.Nullable; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; + +public interface NetworkElementCoreData { + + public String getMountpoint(); + public DataBroker getDataBroker(); + public @Nullable NetworkElement getOptionalNetworkElement(); + public NetworkElementDeviceType getDeviceType(); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/CallBack.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/CallBack.java new file mode 100644 index 000000000..62e55a97c --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/CallBack.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +/** + * @author herbert + * + */ +public interface CallBack { + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationActor.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationActor.java new file mode 100644 index 000000000..4f2dfdeef --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationActor.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +public interface NotificationActor<T> { + + public void notificationActor(T item); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationWorker.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationWorker.java new file mode 100644 index 000000000..0c3014a0d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/NotificationWorker.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Provide a thread that is receiving and process notifications. + * @param <T> represents the object that is provided with a notification and + * forwarded to the NotificationActor<T>. + * + * @author herbert + */ + +public class NotificationWorker<T> implements AutoCloseable { + + private final BlockingQueue<T> workQueue; + private final ExecutorService service; + private final NotificationActor<T> actor; + + public NotificationWorker(int numWorkers, int workQueueSize, NotificationActor<T> actorObject) { + workQueue = new LinkedBlockingQueue<T>(workQueueSize); + service = Executors.newFixedThreadPool(numWorkers); + actor = actorObject; + + for (int i=0; i < numWorkers; i++) { + service.submit(new Worker<T>(workQueue, actor)); + } + } + + public void put(T item) { + try { + workQueue.put(item); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void close() throws Exception { + // TODO Auto-generated method stub + } + + private static class Worker<T> implements Runnable { + private final BlockingQueue<T> workQueue; + private final NotificationActor<T> actor; + + + public Worker(BlockingQueue<T> workQueue, NotificationActor<T> actor) { + this.workQueue = workQueue; + this.actor = actor; + } + + @Override + public void run() { + while (!Thread.currentThread().isInterrupted()) { + try { + T item = workQueue.take(); + actor.notificationActor(item); + // Process item + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + break; + } + } + } + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Base.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Base.java new file mode 100644 index 000000000..8464cc809 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Base.java @@ -0,0 +1,452 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElementService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.WrapperPTPModelRev170208; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.legacy.InventoryInformation; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ptp.dataset.rev170208.InstanceList; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.extension.g.Extension; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.network.element.Ltp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.pac.NetworkElementCurrentProblems; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * This class contains the ONF Core model Version 1.2 related functions.<br> + * Provides the basic ONF Core Model function.<br> + * - initialReadFromNetworkElement is not implemented in child classes. + */ +public abstract class ONFCoreNetworkElement12Base extends ONFCoreNetworkElementBase implements NetworkElementCoreData { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElement12Base.class); + + protected static final List<Extension> EMPTYLTPEXTENSIONLIST = new ArrayList<>(); + // private static final List<Ltp> EMPTYLTPLIST = new ArrayList<>(); + + protected static final InstanceIdentifier<NetworkElement> NETWORKELEMENT_IID = InstanceIdentifier + .builder(NetworkElement.class).build(); + + + /*----------------------------------------------------------------------------- + * Class members + */ + + // Non specific part. Used by all functions. + /** interfaceList is used by PM task and should be synchronized */ + private final @NonNull List<Lp> interfaceList = Collections.synchronizedList(new CopyOnWriteArrayList<>()); + private @Nullable NetworkElement optionalNe = null; + + // Performance monitoring specific part + /** Lock for the PM access specific elements that could be null */ + private final @NonNull Object pmLock = new Object(); + protected @Nullable Iterator<Lp> interfaceListIterator = null; + /** Actual pmLp used during iteration over interfaces */ + protected @Nullable Lp pmLp = null; + + // Device monitoring specific part + /** Lock for the DM access specific elements that could be null */ + protected final @NonNull Object dmLock = new Object(); + + protected final boolean isNetworkElementCurrentProblemsSupporting12; + + protected final ONFCoreNetworkElement12Equipment equipment; + + /* + * Constructor + */ + + protected ONFCoreNetworkElement12Base(INetconfAcessor acessor, String mountPointNodeName, DataBroker netconfNodeDataBroker, + Capabilities capabilities) { + super(acessor, mountPointNodeName, netconfNodeDataBroker, capabilities); + // TODO Auto-generated constructor stub + this.isNetworkElementCurrentProblemsSupporting12 = capabilities.isSupportingNamespaceAndRevision(NetworkElementPac.QNAME); + this.equipment = new ONFCoreNetworkElement12Equipment(acessor, this, capabilities); + WrapperPTPModelRev170208.initSynchronizationExtension(acessor); + LOG.debug("support necurrent-problem-list=" + this.isNetworkElementCurrentProblemsSupporting12); + LOG.info("Create NE instance {}", InstanceList.QNAME.getLocalName()); + } + + /*--------------------------------------------------------------- + * Getter/ Setter + */ + + @Override + public NetworkElement getOptionalNetworkElement() { + return optionalNe; + } + + List<Lp> getInterfaceList() { + return interfaceList; + } + + public Object getPmLock() { + return pmLock; + } + + /*--------------------------------------------------------------- + * Core model related function + */ + + /** + * Get uuid of Optional NE. + * + * @return Uuid or EMPTY String if optionNE is not available + */ + @SuppressWarnings("null") + protected String getUuId() { + String uuid = EMPTY; + + try { + uuid = optionalNe != null ? optionalNe.getUuid() != null ? optionalNe.getUuid().getValue() : EMPTY : EMPTY; + } catch (NullPointerException e) { + // Unfortunately throws null pointer if not definied + } + return uuid; + } + + /** + * Read from NetworkElement and verify LTPs have changed. If the NE has changed, update to the new + * structure. From initial state it changes also. + */ + protected synchronized boolean readNetworkElementAndInterfaces() { + + LOG.debug("Update mountpoint if changed {}", getMountPointNodeName()); + + optionalNe = getGenericTransactionUtils().readData(getNetconfNodeDataBroker(), LogicalDatastoreType.OPERATIONAL, + NETWORKELEMENT_IID);; + synchronized (pmLock) { + boolean change = false; + + if (optionalNe == null) { + LOG.debug("Unable to read NE data for mountpoint {}", getMountPointNodeName()); + if (!interfaceList.isEmpty()) { + interfaceList.clear(); + interfaceListIterator = null; + change = true; + } + + } else { + LOG.debug("Mountpoint '{}' NE-Name '{}'", getMountPointNodeName(), optionalNe.getName()); + List<Lp> actualInterfaceList = getLtpList(optionalNe); + if (!interfaceList.equals(actualInterfaceList)) { + LOG.debug("Mountpoint '{}' Update LTP List. Elements {}", getMountPointNodeName(), + actualInterfaceList.size()); + interfaceList.clear(); + interfaceList.addAll(actualInterfaceList); + interfaceListIterator = null; + change = true; + } + } + return change; + } + } + + /** + * Get List of UUIDs for conditional packages from Networkelement<br> + * Possible interfaces are:<br> + * MWPS, LTP(MWPS-TTP), MWAirInterfacePac, MicrowaveModel-ObjectClasses-AirInterface<br> + * ETH-CTP,LTP(Client), MW_EthernetContainer_Pac<br> + * MWS, LTP(MWS-CTP-xD), MWAirInterfaceDiversityPac, + * MicrowaveModel-ObjectClasses-AirInterfaceDiversity<br> + * MWS, LTP(MWS-TTP), ,MicrowaveModel-ObjectClasses-HybridMwStructure<br> + * MWS, LTP(MWS-TTP), ,MicrowaveModel-ObjectClasses-PureEthernetStructure<br> + * + * @param ne NetworkElement + * @return Id List, never null. + */ + + private static List<Lp> getLtpList(@Nullable NetworkElement ne) { + + List<Lp> res = Collections.synchronizedList(new ArrayList<Lp>()); + + if (ne != null) { + List<Ltp> ltpRefList = ne.getLtp(); + if (ltpRefList == null) { + LOG.debug("DBRead NE-Interfaces: null"); + } else { + for (Ltp ltRefListE : ltpRefList) { + List<Lp> lpList = ltRefListE.getLp(); + if (lpList == null) { + LOG.debug("DBRead NE-Interfaces Reference List: null"); + } else { + for (Lp ltp : lpList) { + res.add(ltp); + } + } + } + } + } else { + LOG.debug("DBRead NE: null"); + } + + // ---- Debug + if (LOG.isDebugEnabled()) { + StringBuffer strBuf = new StringBuffer(); + for (Lp ltp : res) { + if (strBuf.length() > 0) { + strBuf.append(", "); + } + strBuf.append(ltp.getLayerProtocolName().getValue()); + strBuf.append(':'); + strBuf.append(ltp.getUuid().getValue()); + } + LOG.debug("DBRead NE-Interfaces: {}", strBuf.toString()); + } + // ---- Debug end + + return res; + } + + /** + * Read current problems of AirInterfaces and EthernetContainer according to NE status into DB + * + * @return List with all problems + */ + protected List<ProblemNotificationXml> readAllCurrentProblemsOfNode() { + + // Step 2.3: read the existing faults and add to DB + List<ProblemNotificationXml> resultList = new ArrayList<>(); + int idxStart; // Start index for debug messages + UniversalId uuid; + + synchronized (pmLock) { + for (Lp lp : interfaceList) { + + idxStart = resultList.size(); + uuid = lp.getUuid(); + ProblemNotificationXml.debugResultList(LOG, uuid.getValue(), resultList, idxStart); + + } + } + + // Step 2.4: Read other problems from mountpoint + if (isNetworkElementCurrentProblemsSupporting12) { + idxStart = resultList.size(); + readNetworkElementCurrentProblems12(resultList); + ProblemNotificationXml.debugResultList(LOG, "CurrentProblems12", resultList, idxStart); + } + + return resultList; + + } + + /** + * Reading problems for the networkElement V1.2 + * @param resultList + * @return + */ + private List<ProblemNotificationXml> readNetworkElementCurrentProblems12(List<ProblemNotificationXml> resultList) { + + LOG.info("DBRead Get {} NetworkElementCurrentProblems12", getMountPointNodeName()); + + InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac> networkElementCurrentProblemsIID = + InstanceIdentifier.builder( + org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac.class) + .build(); + + // Step 2.3: read to the config data store + NetworkElementPac problemPac; + NetworkElementCurrentProblems problems = null; + try { + problemPac = getGenericTransactionUtils().readData(getNetconfNodeDataBroker(), LogicalDatastoreType.OPERATIONAL, + networkElementCurrentProblemsIID); + if (problemPac != null) { + problems = problemPac.getNetworkElementCurrentProblems(); + } + if (problems == null) { + LOG.debug("DBRead no NetworkElementCurrentProblems12"); + } else { + for (org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.current.problems.g.CurrentProblemList problem : problems + .nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(getMountPointNodeName(), problem.getObjectReference(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (Exception e) { + LOG.warn("DBRead {} NetworkElementCurrentProblems12 not supported. Message '{}' ", getMountPointNodeName(), + e.getMessage()); + } + return resultList; + } + + /*--------------------------------------------------------------- + * Device Monitor + */ + + @Override + public boolean checkIfConnectionToMediatorIsOk() { + synchronized (dmLock) { + return optionalNe != null; + } + } + + /* + * New implementation to interpret status with empty LTP List as notConnected => return false + * 30.10.2018 Since this behavior is very specific and implicit for specific NE Types + * it needs to be activated by extension or configuration. Change to be disabled at the moment + */ + @Override + public boolean checkIfConnectionToNeIsOk() { + return true; + } + + /*--------------------------------------------------------------- + * Synchronization + */ + + + + /*--------------------------------------------------------------- + * Equipment related functions + */ + + @Override + public @NonNull InventoryInformation getInventoryInformation(String layerProtocolFilter) { + LOG.debug("request inventory information. filter:" + layerProtocolFilter); + return this.equipment.getInventoryInformation(getFilteredInterfaceUuidsAsStringList(layerProtocolFilter)); + } + + @Override + public InventoryInformation getInventoryInformation() { + return getInventoryInformation(null); + } + + protected List<String> getFilteredInterfaceUuidsAsStringList(String layerProtocolFilter) { + List<String> uuids = new ArrayList<>(); + + LOG.debug("request inventory information. filter:" + layerProtocolFilter); + if (optionalNe != null) { + // uuids + for (Lp lp : this.interfaceList) { + if (layerProtocolFilter == null || layerProtocolFilter.isEmpty()) { + uuids.add(lp.getUuid().getValue()); + } else if (lp.getLayerProtocolName() != null && lp.getLayerProtocolName().getValue() != null + && lp.getLayerProtocolName().getValue().equals(layerProtocolFilter)) { + uuids.add(lp.getUuid().getValue()); + } + } + } + LOG.debug("uuids found: {}", uuids); + return uuids; + } + + + /*--------------------------------------------------------------- + * Performancemanagement specific interface + */ + + @Override + public void resetPMIterator() { + synchronized (pmLock) { + interfaceListIterator = interfaceList.iterator(); + } + LOG.debug("PM reset iterator"); + } + + @Override + public boolean hasNext() { + boolean res; + synchronized (pmLock) { + res = interfaceListIterator != null ? interfaceListIterator.hasNext() : false; + } + LOG.debug("PM hasNext LTP {}", res); + return res; + } + + @Override + public void next() { + synchronized (pmLock) { + if (interfaceListIterator == null) { + pmLp = null; + LOG.debug("PM next LTP null"); + } else { + pmLp = interfaceListIterator.next(); + LOG.debug("PM next LTP {}", pmLp.getLayerProtocolName().getValue()); + } + } + } + + @Override + public String pmStatusToString() { + StringBuffer res = new StringBuffer(); + synchronized (pmLock) { + res.append(pmLp == null ? "no interface" : pmLp.getLayerProtocolName().getValue()); + for (Lp lp : getInterfaceList()) { + res.append("IF:"); + res.append(lp.getLayerProtocolName().getValue()); + res.append(" "); + } + } + return res.toString(); + } + + @Override + public AllPm getHistoricalPM() { + return AllPm.getEmpty(); + } + + + @Override + public void doRegisterEventListener(MountPoint mountPoint) { + //Do nothing + } + + + @Override + public void register() { + } + + + @Override + public void deregister() { + } + + @SuppressWarnings("unchecked") + @Override + public <L extends NetworkElementService> Optional<L> getService(Class<L> clazz) { + return clazz.isInstance(this) ? Optional.of((L)this) : Optional.empty(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Basic.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Basic.java new file mode 100644 index 000000000..4ea6fee25 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Basic.java @@ -0,0 +1,230 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.List; +import org.eclipse.jdt.annotation.NonNull; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.NetconfEventListenerHandler12; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayService; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Get information over NETCONF device according to ONF Coremodel. Read networkelement and + * conditional packages. + * + * Get conditional packages from Networkelement Possible interfaces are: MWPS, LTP(MWPS-TTP), + * MWAirInterfacePac, MicrowaveModel-ObjectClasses-AirInterface ETH-CTP,LTP(Client), + * MW_EthernetContainer_Pac MWS, LTP(MWS-CTP-xD), MWAirInterfaceDiversityPac, + * MicrowaveModel-ObjectClasses-AirInterfaceDiversity MWS, LTP(MWS-TTP), + * ,MicrowaveModel-ObjectClasses-HybridMwStructure MWS, LTP(MWS-TTP), + * ,MicrowaveModel-ObjectClasses-PureEthernetStructure + * + * @author herbert + * + */ +public class ONFCoreNetworkElement12Basic extends ONFCoreNetworkElement12Base + implements ONFCoreNetworkElementCallback, NotificationActor<AttributeValueChangedNotificationXml> { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElement12Basic.class); + + /*----------------------------------------------------------------------------- + * Class members + */ + private final @NonNull NetconfEventListenerHandler12 netconfEventListener; + private final NotificationWorker<AttributeValueChangedNotificationXml> notificationQueue; + + /*----------------------------------------------------------------------------- + * Construction + */ + + /** + * Constructor + * + * @param mountPointNodeName as String + * @param capabilities of the specific network element + * @param netconfNodeDataBroker for the network element specific data + * @param webSocketService to forward event notifications + * @param databaseService to access the database + * @param dcaeProvider to forward problem / change notifications + */ + ONFCoreNetworkElement12Basic(INetconfAcessor acessor, String mountPointNodeName, Capabilities capabilities, + DataBroker netconfNodeDataBroker, WebSocketServiceClientInternal webSocketService, + DataProvider databaseService, DcaeForwarderInternal aotsDcaeForwarder, + NotificationDelayService<ProblemNotificationXml> notificationDelayService ) { + + super(acessor, mountPointNodeName, netconfNodeDataBroker, capabilities); + + this.netconfEventListener = new NetconfEventListenerHandler12(mountPointNodeName, webSocketService, + databaseService, aotsDcaeForwarder, notificationDelayService, this); + this.notificationQueue = new NotificationWorker<>(1, 100, this); + + } + + + /*----------------------------------------------------------------------------- + * Functions + */ + + /** + * DeviceMonitor Prepare check by updating NE state and reading all interfaces. + */ + @Override + public void prepareCheck() { + synchronized (dmLock) { + boolean change = readNetworkElementAndInterfaces(); + if (change) { + int problems = netconfEventListener.removeAllCurrentProblemsOfNode(); + List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode(); + netconfEventListener.initCurrentProblemStatus(resultList); + LOG.info("Resync mountpoint {} for device {}. Removed {}. Current problems: {}", getMountPointNodeName(), + getUuId(), problems, resultList.size()); + } + } + } + + // public boolean checkIfConnectionToMediatorIsOk() -> Shifted to super class + // public boolean checkIfConnectionToNeIsOk() -> Shifted to super class + + /*----------------------------------------------------------------------------- + * Synchronization + */ + + // public void initSynchronizationExtension() -> Shifted to super class + // private InstanceList readPTPClockInstances() -> Shifted to super class + + /*----------------------------------------------------------------------------- + * Services for NE/Device synchronization + */ + + /** + * Handling of specific Notifications from NE, indicating changes and need for synchronization. + * + * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model"> + * <attribute-name>/equipment-pac/equipment-current-problems</attribute-name> + * <object-id-ref>CARD-1.1.1.0</object-id-ref> <new-value></new-value> + * </attribute-value-changed-notification> + * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model"> + * <attribute-name>/network-element/extension[value-name="top-level-equipment"]/value</attribute-name> + * <object-id-ref>Hybrid-Z</object-id-ref> + * <new-value>SHELF-1.1.0.0,IDU-1.55.0.0,ODU-1.56.0.0,IDU-1.65.0.0</new-value> + * </attribute-value-changed-notification> + */ + + + @Override + public void notificationFromNeListener(AttributeValueChangedNotificationXml notificationXml) { + notificationQueue.put(notificationXml); + } + + @Override + public void notificationActor(AttributeValueChangedNotificationXml notificationXml) { + + LOG.debug("Enter change notification listener"); + if (LOG.isTraceEnabled()) { + LOG.trace("Notification: {}", notificationXml); + } + if (notificationXml.getAttributeName().equals("/equipment-pac/equipment-current-problems")) { + syncEquipmentPac(notificationXml.getObjectId()); + } else if (notificationXml.getAttributeName() + .equals("/network-element/extension[value-name=\"top-level-equipment\"]/value")) { + initialReadFromNetworkElement(); + } + LOG.debug("Leave change notification listener"); + } + + /** + * Synchronize problems for a specific equipment-pac + * + * @param uuidString of the equipment-pac + */ + private synchronized void syncEquipmentPac(String uuidString) { + + int problems = netconfEventListener.removeObjectsCurrentProblemsOfNode(uuidString); + LOG.debug("Removed {} problems for uuid {}", problems, uuidString); + + List<ProblemNotificationXml> resultList = equipment.addProblemsofNodeObject(uuidString); + netconfEventListener.initCurrentProblemStatus(resultList); + LOG.debug("Added {} problems for uuid {}", resultList.size(), uuidString); + + } + + + /*----------------------------------------------------------------------------- + * Problem/Fault related functions + */ + + /** + * Read during startup all relevant structure and status parameters from device + */ + @Override + public synchronized void initialReadFromNetworkElement() { + // optionalNe.getLtp().get(0).getLp(); + LOG.debug("Get info about {}", getMountPointNodeName()); + + int problems = netconfEventListener.removeAllCurrentProblemsOfNode(); + LOG.debug("Removed all {} problems from database at registration", problems); + + // Step 2.1: access data broker within this mount point + LOG.debug("DBRead start"); + + // Step 2.2: read ne from data store + readNetworkElementAndInterfaces(); + equipment.readNetworkElementEquipment(); + + // Step 2.3: read the existing faults and add to DB + List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode(); + equipment.addProblemsofNode(resultList); + + netconfEventListener.initCurrentProblemStatus(resultList); + + netconfEventListener.writeEquipment(equipment); + + LOG.info("Found info at {} for device {} number of problems: {}", getMountPointNodeName(), getUuId(), + resultList.size()); + } + + /** + * Remove all entries from list + */ + @Override + public int removeAllCurrentProblemsOfNode() { + return netconfEventListener.removeAllCurrentProblemsOfNode(); + } + + + @Override + public void close() throws Exception { + } + + + @Override + public NetworkElementDeviceType getDeviceType() { + return NetworkElementDeviceType.Optical; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Equipment.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Equipment.java new file mode 100644 index 000000000..21309c02c --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Equipment.java @@ -0,0 +1,303 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedEquipment; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ValueNameList; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.OnfInterfacePac; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.WrapperEquipmentPacRev170402; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.legacy.InventoryInformation; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.Equipment; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.EquipmentKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.equipment.g.ContainedHolder; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.equipment.g.ManufacturedThing; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.manufactured.thing.g.EquipmentType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.manufactured.thing.g.ManufacturerProperties; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Contains equipment related information of ONFCore Network Element + */ +public class ONFCoreNetworkElement12Equipment { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElement12Equipment.class); + + private static final UniversalId EQUIPMENTROOT = new UniversalId("network-element"); + private static final int EQUIPMENTROOTLEVEL = 0; + + private final NetworkElementCoreData coreData; + private final OnfInterfacePac equipmentPac; + private final INetconfAcessor acessor; + + private final ValueNameList extensionList; + private final List<UniversalId> topLevelEqUuidList; + private final List<ProblemNotificationXml> globalProblemList; + private final List<ExtendedEquipment> globalEquipmentList; + + public ONFCoreNetworkElement12Equipment(INetconfAcessor acessor, NetworkElementCoreData coreData, Capabilities capabilities) { + LOG.debug("Initialize " + ONFCoreNetworkElement12Equipment.class.getName()); + this.acessor = acessor; + this.coreData = coreData; + if (capabilities.isSupportingNamespaceAndRevision(WrapperEquipmentPacRev170402.QNAME)) { + this.equipmentPac = new WrapperEquipmentPacRev170402(acessor, coreData); + LOG.debug("Equipement pac supported {}", WrapperEquipmentPacRev170402.QNAME); + } else { + this.equipmentPac = null; + LOG.debug("Equipement pac not supported {}", WrapperEquipmentPacRev170402.QNAME); + } + + extensionList = new ValueNameList(); + topLevelEqUuidList = new ArrayList<>(); + globalProblemList = new ArrayList<>(); + globalEquipmentList = new ArrayList<>(); + + initClassVars(); + } + + public void addProblemsofNode(List<ProblemNotificationXml> resultList) { + resultList.addAll(globalProblemList); + } + + public List<ProblemNotificationXml> addProblemsofNodeObject(String uuidString) { + List<ProblemNotificationXml> res = new ArrayList<>(); + + if (this.equipmentPac != null) { + this.equipmentPac.readTheFaults(new UniversalId(uuidString), res); + } + return res; + } + + public @NonNull InventoryInformation getInventoryInformation(List<String> uuids) { + return getInventoryInformation(this.extensionList, uuids); + } + + protected void readNetworkElementEquipment() { + doSyncNetworkElementEquipmentToClassVars(); + } + + public String getMountpoint() { + return coreData.getMountpoint(); + } + + public OnfInterfacePac getEquipmentPac() { + return equipmentPac; + } + + public List<UniversalId> getTopLevelEqUuidList() { + return topLevelEqUuidList; + } + + public List<ExtendedEquipment> getEquipmentList() { + return globalEquipmentList; + } + + public List<Equipment> getEquipmentAll() { + List<Equipment> equipmentListAll = new ArrayList<>(); + + Equipment equipment = readEquipmentAll(); + equipmentListAll.add(equipment); + + return equipmentListAll; + } + + TransactionUtils getGenericTransactionUtils() { + return acessor.getTransactionUtils(); + } + + /* + * --------------------------------------------------------------------------------- private + * functions + */ + + private void initClassVars() { + this.globalProblemList.clear(); + this.globalEquipmentList.clear(); + this.extensionList.clear(); + this.topLevelEqUuidList.clear(); + } + + private void doSyncNetworkElementEquipmentToClassVars() { + + NetworkElement optionalNe = coreData.getOptionalNetworkElement(); + initClassVars(); + + if (optionalNe != null) { + // extract Inventory + extensionList.put(optionalNe.getExtension()); + + if (!extensionList.isEmpty()) { + + /* + * Loop through network element extension to get "top-level-equipment" <extension> + * <value-name>top-level-equipment</value-name> <value>1.0.BKP,1.0.WCS</value> </extension> "ipv4" + * address + */ + extensionList.getAsUniversalIdList("top-level-equipment", topLevelEqUuidList); + + // If top-level-equipment exists get further information + if (topLevelEqUuidList.isEmpty()) { + LOG.debug("no top level equipment found"); + } else { + // Read equipment and problems + for (UniversalId uuid : topLevelEqUuidList) { + recurseReadEquipmentProblems(uuid, EQUIPMENTROOT, coreData.getMountpoint(), EQUIPMENTROOTLEVEL, globalProblemList, + globalEquipmentList); + } + } + } else { + LOG.debug("extension list is null"); + } + } + } + + private void recurseReadEquipmentProblems(UniversalId uuid, UniversalId parentUuid, String path, int treeLevel, + List<ProblemNotificationXml> problemList, List<ExtendedEquipment> equipmentList) { + + if (uuid != null) { + + Equipment equipment = this.readEquipment(uuid); + + if (equipment != null) { + equipmentList.add(new ExtendedEquipment(this.getMountpoint(),parentUuid.getValue(), equipment, path, treeLevel)); + + if (this.equipmentPac != null) { + this.equipmentPac.readTheFaults(uuid, problemList); + + List<ContainedHolder> containedHolderListe = equipment.getContainedHolder(); + if (containedHolderListe != null) { + for (ContainedHolder containedHolder : containedHolderListe) { + recurseReadEquipmentProblems(containedHolder.getOccupyingFru(), uuid, path+"/"+uuid.getValue(), treeLevel + 1, + problemList, equipmentList); + } + } + } + } + } + } + + private @NonNull InventoryInformation getInventoryInformation(ValueNameList extensions, List<String> uuids) { + + InventoryInformation inventoryInformation = new InventoryInformation(); + + // uuids + inventoryInformation.setInterfaceUuidList(uuids); + + if (!extensions.isEmpty()) { + + inventoryInformation.setDeviceIpv4(extensions.getOrNull("neIpAddress")); + + // If top-level-equipment exists get further information + if (topLevelEqUuidList.isEmpty()) { + LOG.debug("no top level equipment found"); + } else { + if (!globalEquipmentList.isEmpty()) { + Equipment e = globalEquipmentList.get(0).getEquipment(); + if (e != null) { + ManufacturedThing manufacturedThing = e.getManufacturedThing(); + if (manufacturedThing != null) { + EquipmentType et; + if ((et = manufacturedThing.getEquipmentType()) != null) { + inventoryInformation.setType(et.getTypeName()); + inventoryInformation.setModel(et.getModelIdentifier()); + } + ManufacturerProperties em; + if ((em = manufacturedThing.getManufacturerProperties()) != null) { + inventoryInformation.setVendor(em.getManufacturerIdentifier()); + } + } + } + } + } + } else { + LOG.debug("extension list is null"); + } + + LOG.debug("Inventory: {}", inventoryInformation); + return inventoryInformation; + + } + + + /** + * Read equipment information + * + * @param interfacePacUuid uuid as key for Equipment. + * @return Equipment or null + */ + private @Nullable Equipment readEquipment(UniversalId interfacePacUuid) { + + final Class<?> clazzPac = Equipment.class; + + LOG.info("DBRead Get equipment for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<Equipment> equipmentIID = + InstanceIdentifier.builder(Equipment.class, new EquipmentKey(interfacePacUuid)).build(); + + Equipment res = getGenericTransactionUtils().readData(coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, + equipmentIID); + + return res; + } + + /** + * Read equipment information + * + * @param interfacePacUuid uuid as key for Equipment. + * @return Equipment or null + */ + private @Nullable Equipment readEquipmentAll() { + + final Class<?> clazzPac = Equipment.class; + + LOG.info("DBRead Get all equipment for class {} from mountpoint {}", clazzPac.getSimpleName(), + coreData.getMountpoint()); + + InstanceIdentifier<Equipment> equipmentIID = InstanceIdentifier.builder(Equipment.class).build(); + + Equipment res = getGenericTransactionUtils().readData(coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, + equipmentIID); + + return res; + } + + /** + * specific toString() + */ + @Override + public String toString() { + return "ONFCoreNetworkElement12Equipment [coreData=" + coreData + ", equipmentPac=" + equipmentPac + + ", extensions=" + extensionList + ", topLevelEqUuidList=" + topLevelEqUuidList + ", problemList=" + + globalProblemList + ", equipmentList=" + globalEquipmentList + "]"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Microwave.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Microwave.java new file mode 100644 index 000000000..89f803a17 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElement12Microwave.java @@ -0,0 +1,516 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.OnfMicrowaveModel; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.NetconfEventListenerHandler12; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance15Minutes; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance24Hours; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayService; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.NotificationService; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.extension.g.Extension; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.pac.NetworkElementCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.NotificationListener; +import org.opendaylight.yangtools.yang.common.QName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Get information over NETCONF device according to ONF Coremodel. Read networkelement and + * conditional packages. + * + * Get conditional packages from Networkelement Possible interfaces are: MWPS, LTP(MWPS-TTP), + * MWAirInterfacePac, MicrowaveModel-ObjectClasses-AirInterface ETH-CTP,LTP(Client), + * MW_EthernetContainer_Pac MWS, LTP(MWS-CTP-xD), MWAirInterfaceDiversityPac, + * MicrowaveModel-ObjectClasses-AirInterfaceDiversity MWS, LTP(MWS-TTP), + * ,MicrowaveModel-ObjectClasses-HybridMwStructure MWS, LTP(MWS-TTP), + * ,MicrowaveModel-ObjectClasses-PureEthernetStructure + * + * @author herbert + * + */ +public class ONFCoreNetworkElement12Microwave extends ONFCoreNetworkElement12Base + implements ONFCoreNetworkElementCallback, NotificationActor<AttributeValueChangedNotificationXml> { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElement12Microwave.class); + + /*----------------------------------------------------------------------------- + * Class members + */ + private final @NonNull NetconfEventListenerHandler12 microwaveEventListener; + private final @NonNull OnfMicrowaveModel microwaveModel; + private final NotificationWorker<AttributeValueChangedNotificationXml> notificationQueue; + + private ListenerRegistration<NotificationListener> listenerRegistrationresult = null; + + /*----------------------------------------------------------------------------- + * Construction + */ + + /** + * Constructor + * + * @param mountPointNodeName as String + * @param capabilities of the specific network element + * @param netconfNodeDataBroker for the network element specific data + * @param webSocketService to forward event notifications + * @param databaseService to access the database + * @param dcaeProvider to forward problem / change notifications + */ + ONFCoreNetworkElement12Microwave(INetconfAcessor acessor, String mountPointNodeName, Capabilities capabilities, + DataBroker netconfNodeDataBroker, WebSocketServiceClientInternal webSocketService, + DataProvider databaseService, DcaeForwarderInternal aotsDcaeForwarder, + NotificationDelayService<ProblemNotificationXml> notificationDelayService, + OnfMicrowaveModel onfMicrowaveModel) { + + super(acessor, mountPointNodeName, netconfNodeDataBroker, capabilities); + + this.microwaveModel = onfMicrowaveModel; + this.microwaveModel.setCoreData(this); + + // Create MicrowaveService here + this.microwaveEventListener = new NetconfEventListenerHandler12(mountPointNodeName, webSocketService, + databaseService, aotsDcaeForwarder, notificationDelayService, this); + this.microwaveModel.setOnfMicrowaveModelListener(microwaveEventListener); + + this.notificationQueue = new NotificationWorker<>(1, 100, this); + + // ->Below shifted to super class + // this.isNetworkElementCurrentProblemsSupporting12 = + // capabilities.isSupportingNamespaceAndRevision(NetworkElementPac.QNAME); + // LOG.debug("support necurrent-problem-list=" + this.isNetworkElementCurrentProblemsSupporting12); + // LOG.info("Create NE instance {}", InstanceList.QNAME.getLocalName()); + + } + + /*----------------------------------------------------------------------------- + * Functions + */ + + /** + * DeviceMonitor Prepare check by updating NE state and reading all interfaces. + */ + @Override + public void prepareCheck() { + synchronized (dmLock) { + boolean change = readNetworkElementAndInterfaces(); + if (change) { + int problems = microwaveEventListener.removeAllCurrentProblemsOfNode(); + List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode(); + microwaveEventListener.initCurrentProblemStatus(resultList); + LOG.info("Resync mountpoint {} for device {}. Removed {}. Current problems: {}", getMountPointNodeName(), + getUuId(), problems, resultList.size()); + } + } + } + + // public boolean checkIfConnectionToMediatorIsOk() -> Shifted to super class + // public boolean checkIfConnectionToNeIsOk() -> Shifted to super class + + /*----------------------------------------------------------------------------- + * Synchronization + */ + + // public void initSynchronizationExtension() -> Shifted to super class + // private InstanceList readPTPClockInstances() -> Shifted to super class + + /*----------------------------------------------------------------------------- + * Services for NE/Device synchronization + */ + + /** + * Handling of specific Notifications from NE, indicating changes and need for synchronization. + * + * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model"> + * <attribute-name>/equipment-pac/equipment-current-problems</attribute-name> + * <object-id-ref>CARD-1.1.1.0</object-id-ref> <new-value></new-value> + * </attribute-value-changed-notification> + * <attribute-value-changed-notification xmlns="urn:onf:params:xml:ns:yang:microwave-model"> + * <attribute-name>/network-element/extension[value-name="top-level-equipment"]/value</attribute-name> + * <object-id-ref>Hybrid-Z</object-id-ref> + * <new-value>SHELF-1.1.0.0,IDU-1.55.0.0,ODU-1.56.0.0,IDU-1.65.0.0</new-value> + * </attribute-value-changed-notification> + */ + + + @Override + public void notificationFromNeListener(AttributeValueChangedNotificationXml notificationXml) { + notificationQueue.put(notificationXml); + } + + @Override + public void notificationActor(AttributeValueChangedNotificationXml notificationXml) { + + LOG.debug("Enter change notification listener"); + if (LOG.isTraceEnabled()) { + LOG.trace("Notification: {}", notificationXml); + } + if (notificationXml.getAttributeName().equals("/equipment-pac/equipment-current-problems")) { + syncEquipmentPac(notificationXml.getObjectId()); + } else if (notificationXml.getAttributeName() + .equals("/network-element/extension[value-name=\"top-level-equipment\"]/value")) { + initialReadFromNetworkElement(); + } + LOG.debug("Leave change notification listener"); + } + + /** + * Synchronize problems for a specific equipment-pac + * + * @param uuidString of the equipment-pac + */ + private synchronized void syncEquipmentPac(String uuidString) { + + int problems = microwaveEventListener.removeObjectsCurrentProblemsOfNode(uuidString); + LOG.debug("Removed {} problems for uuid {}", problems, uuidString); + + List<ProblemNotificationXml> resultList = equipment.addProblemsofNodeObject(uuidString); + microwaveEventListener.initCurrentProblemStatus(resultList); + LOG.debug("Added {} problems for uuid {}", resultList.size(), uuidString); + + } + + + /*----------------------------------------------------------------------------- + * Problem/Fault related functions + */ + + /** + * Read during startup all relevant structure and status parameters from device + */ + @Override + public synchronized void initialReadFromNetworkElement() { + // optionalNe.getLtp().get(0).getLp(); + LOG.debug("Get info about {}", getMountPointNodeName()); + + int problems = microwaveEventListener.removeAllCurrentProblemsOfNode(); + LOG.debug("Removed all {} problems from database at registration", problems); + + // Step 2.1: access data broker within this mount point + LOG.debug("DBRead start"); + + // Step 2.2: read ne from data store + readNetworkElementAndInterfaces(); + equipment.readNetworkElementEquipment(); + + // Step 2.3: read the existing faults and add to DB + List<ProblemNotificationXml> resultList = readAllCurrentProblemsOfNode(); + equipment.addProblemsofNode(resultList); + + microwaveEventListener.initCurrentProblemStatus(resultList); + + microwaveEventListener.writeEquipment(equipment); + + LOG.info("Found info at {} for device {} number of problems: {}", getMountPointNodeName(), getUuId(), + resultList.size()); + } + + /** + * LOG the newly added problems of the interface pac + * + * @param idxStart + * @param uuid + * @param resultList + */ + private void debugResultList(String uuid, List<ProblemNotificationXml> resultList, int idxStart) { + if (LOG.isDebugEnabled()) { + StringBuffer sb = new StringBuffer(); + int idx = 0; + for (int t = idxStart; t < resultList.size(); t++) { + sb.append(idx++); + sb.append(":{"); + sb.append(resultList.get(t)); + sb.append('}'); + } + LOG.debug("Found problems {} {}", uuid, sb.toString()); + } + } + + /** + * Read current problems of AirInterfaces and EthernetContainer according to NE status into DB + * + * @return List with all problems + */ + @Override + protected List<ProblemNotificationXml> readAllCurrentProblemsOfNode() { + + // Step 2.3: read the existing faults and add to DB + List<ProblemNotificationXml> resultList = new ArrayList<>(); + int idxStart; // Start index for debug messages + UniversalId uuid; + + synchronized (getPmLock()) { + for (Lp lp : getInterfaceList()) { + + idxStart = resultList.size(); + uuid = lp.getUuid(); + Class<?> lpClass = getLpExtension(lp); + + ONFLayerProtocolName lpName = ONFLayerProtocolName.valueOf(lp.getLayerProtocolName()); + + microwaveModel.readTheFaultsOfMicrowaveModel(lpName, lpClass, uuid, resultList); + + debugResultList(uuid.getValue(), resultList, idxStart); + + } + } + + // Step 2.4: Read other problems from mountpoint + if (isNetworkElementCurrentProblemsSupporting12) { + idxStart = resultList.size(); + readNetworkElementCurrentProblems12(resultList); + debugResultList("CurrentProblems12", resultList, idxStart); + } + + return resultList; + + } + + /** + * Get from LayerProtocolExtensions the related generated ONF Interface PAC class which represents it. + * + * @param lp logical termination point + * @return Class of InterfacePac + */ + @Nullable + private Class<?> getLpExtension(@Nullable Lp lp) { + + String capability = EMPTY; + String revision = EMPTY; + String conditionalPackage = EMPTY; + Class<?> res = null; + + if (lp != null) { + for (Extension e : getExtensionList(lp)) { + if (e.getValueName().contentEquals("capability")) { + capability = e.getValue(); + int idx = capability.indexOf("?"); + if (idx != -1) { + capability = capability.substring(0, idx); + } + } + if (e.getValueName().contentEquals("revision")) { + revision = e.getValue(); + } + if (e.getValueName().contentEquals("conditional-package")) { + conditionalPackage = e.getValue(); + } + } + } + // QName qName = + // org.opendaylight.yangtools.yang.common.QName.create("urn:onf:params:xml:ns:yang:microwave-model", + // "2017-03-24", "mw-air-interface-pac").intern(); + LOG.info("LpExtension capability={} revision={} conditionalPackage={}", capability, revision, + conditionalPackage); + if (!capability.isEmpty() && !revision.isEmpty() && !conditionalPackage.isEmpty()) { + try { + QName qName = QName.create(capability, revision, conditionalPackage); + res = this.microwaveModel.getClassForLtpExtension(qName); + } catch (IllegalArgumentException e) { + LOG.debug("Can not create QName from ({}{}{}): {}", capability, revision, conditionalPackage, + e.getMessage()); + } + } + return res; + } + + /** + * Read element from class that could be not available + * + * @param ltp layer termination point + * @return List with extension parameters or empty list + */ + @NonNull + private static List<Extension> getExtensionList(@Nullable Lp ltp) { + if (ltp != null && ltp.getExtension() != null) { + return ltp.getExtension(); + } else { + return EMPTYLTPEXTENSIONLIST; + } + } + + @NonNull + private List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(Lp lp) { + ONFLayerProtocolName lpName = ONFLayerProtocolName.valueOf(lp.getLayerProtocolName()); + + return this.microwaveModel.readTheHistoricalPerformanceData(lpName, lp); + } + + @Override + public AllPm getHistoricalPM() { + + synchronized (getPmLock()) { + if (pmLp != null) { + LOG.debug("Enter query PM"); + AllPm allPm = new AllPm(); + Lp lp = pmLp; + + List<? extends OtnHistoryDataG> resultList = readTheHistoricalPerformanceData(lp); + LOG.debug("Got records: {}", resultList.size()); + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType + GranularityPeriodType granularityPeriod; + for (OtnHistoryDataG perf : resultList) { + + granularityPeriod = perf.getGranularityPeriod(); + if (granularityPeriod == null) { + granularityPeriod = GranularityPeriodType.Unknown; + } + + switch (granularityPeriod) { + case Period15Min: { + EsHistoricalPerformance15Minutes pm = + new EsHistoricalPerformance15Minutes(getMountPointNodeName(), lp) + .setHistoricalRecord15Minutes(perf); + allPm.add(pm); + } + break; + + case Period24Hours: { + EsHistoricalPerformance24Hours pm = + new EsHistoricalPerformance24Hours(getMountPointNodeName(), lp) + .setHistoricalRecord24Hours(perf); + LOG.debug("Write 24h write to DB"); + allPm.add(pm); + } + break; + + default: + LOG.warn("Unknown granularity {}", perf.getGranularityPeriod()); + break; + + } + } + LOG.debug("Deliver normalized records: {}", allPm.size()); + return allPm; + } else { + LOG.debug("Deliver empty, no LTP"); + return AllPm.getEmpty(); + } + } + } + + + /** + * Remove all entries from list + */ + @Override + public int removeAllCurrentProblemsOfNode() { + return microwaveEventListener.removeAllCurrentProblemsOfNode(); + } + + /** + * Register the listener + */ + @Override + public void doRegisterEventListener(MountPoint mountPoint) { + LOG.info("End registration listener for Mountpoint {}", mountPoint.getIdentifier().toString()); + final Optional<NotificationService> optionalNotificationService = + mountPoint.getService(NotificationService.class); + final NotificationService notificationService = optionalNotificationService.get(); + // notificationService.registerNotificationListener(microwaveEventListener); + listenerRegistrationresult = + notificationService.registerNotificationListener(microwaveModel.getNotificationListener()); + LOG.info("End registration listener for Mountpoint {} Listener: {} Result: {}", + mountPoint.getIdentifier().toString(), optionalNotificationService, listenerRegistrationresult); + } + + /*------------------------------------------------------------ + * private function to access database + */ + + /*----------------------------------------------------------------------------- + * Reading problems for the networkElement V1.2 + */ + + private List<ProblemNotificationXml> readNetworkElementCurrentProblems12(List<ProblemNotificationXml> resultList) { + + LOG.info("DBRead Get {} NetworkElementCurrentProblems12", getMountPointNodeName()); + + InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac> networkElementCurrentProblemsIID = + InstanceIdentifier.builder( + org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.NetworkElementPac.class) + .build(); + + // Step 2.3: read to the config data store + NetworkElementPac problemPac; + NetworkElementCurrentProblems problems; + try { + problemPac = getGenericTransactionUtils().readData(getNetconfNodeDataBroker(), LogicalDatastoreType.OPERATIONAL, + networkElementCurrentProblemsIID); + problems = problemPac.getNetworkElementCurrentProblems(); + if (problems == null) { + LOG.debug("DBRead no NetworkElementCurrentProblems12"); + } else { + for (org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.network.element.current.problems.g.CurrentProblemList problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(getMountPointNodeName(), problem.getObjectReference(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOG.warn("DBRead {} NetworkElementCurrentProblems12 not supported. Message '{}' ", getMountPointNodeName(), pw.toString()); + } + return resultList; + + } + + @Override + public void close() throws Exception { + if (listenerRegistrationresult != null) { + listenerRegistrationresult.close(); + } + } + + @Override + public NetworkElementDeviceType getDeviceType() { + return NetworkElementDeviceType.Wireless; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementBase.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementBase.java new file mode 100644 index 000000000..7b8e1c0d3 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementBase.java @@ -0,0 +1,171 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import javax.annotation.Nonnull; +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.InternalConnectionStatus; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionLogStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.network.element.connection.entity.NodeDetailsBuilder; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author herbert + * + */ +@SuppressWarnings("deprecation") +public abstract class ONFCoreNetworkElementBase implements AutoCloseable, ONFCoreNetworkElementRepresentation { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElementBase.class); + + protected static final String EMPTY = ""; + + private final String mountPointNodeName; + private final NodeId nodeId; + private final DataBroker netconfNodeDataBroker; + private final Capabilities capabilities; + private final INetconfAcessor acessor; + + protected ONFCoreNetworkElementBase(INetconfAcessor acessor, String mountPointNodeName, DataBroker netconfNodeDataBroker, + Capabilities capabilities) { + LOG.info("Create ONFCoreNetworkElementBase"); + this.mountPointNodeName = mountPointNodeName; + this.nodeId = new NodeId(mountPointNodeName); + this.netconfNodeDataBroker = netconfNodeDataBroker; + this.capabilities = capabilities; + this.acessor = acessor; + + } + + @Override + public String getMountPointNodeName() { + return mountPointNodeName; + } + + /** + * @return the netconfNodeDataBroker + */ + public DataBroker getNetconfNodeDataBroker() { + return netconfNodeDataBroker; + } + + /** + * @return the capabilities + */ + public Capabilities getCapabilities() { + return capabilities; + } + + /** + * Update devicetype and let all other field empty + * @param deviceType that should be updated + * @return NetworkElementConnectionEntity with related parameter + */ + public static NetworkElementConnectionEntity getNetworkConnectionDeviceTpe(NetworkElementDeviceType deviceType) { + NetworkElementConnectionBuilder eb = new NetworkElementConnectionBuilder(); + eb.setDeviceType(deviceType); + return eb.build(); + } + + /** + * Provide device specific data + * @param nodeId mountpoint id + * @param nNode data + * @return NetworkElementConnectionEntity specific information + */ + public static NetworkElementConnectionEntity getNetworkConnection(String nodeId, @Nonnull NetconfNode nNode) { + + NetworkElementConnectionBuilder eb = new NetworkElementConnectionBuilder(); + // -- basics + eb.setId(nodeId).setNodeId(nodeId).setDeviceType(NetworkElementDeviceType.Unknown).setIsRequired(false); + + // -- connection status + ConnectionLogStatus status = InternalConnectionStatus.statusFromNodeStatus(nNode.getConnectionStatus()); + eb.setStatus(status); + + // -- capabilites + Capabilities availableCapabilities = Capabilities.getAvailableCapabilities(nNode); + Capabilities unAvailableCapabilities = Capabilities.getUnavailableCapabilities(nNode); + eb.setCoreModelCapability(availableCapabilities.getRevisionForNamespace(NetworkElement.QNAME)); + + NodeDetailsBuilder nodeDetails = new NodeDetailsBuilder() + .setAvailableCapabilities(availableCapabilities.getCapabilities()) + .setUnavailableCapabilities(unAvailableCapabilities.getCapabilities()); + eb.setNodeDetails(nodeDetails.build()); + // -- host information + Host host = nNode.getHost(); + PortNumber portNumber = nNode.getPort(); + if (host != null && portNumber != null) { + eb.setHost(host.stringValue()).setPort(portNumber.getValue().longValue()); + } + + Credentials credentials = nNode.getCredentials(); + if (credentials instanceof LoginPassword) { + LoginPassword loginPassword = (LoginPassword) credentials; + eb.setUsername(loginPassword.getUsername()).setPassword(loginPassword.getPassword()); + } + return eb.build(); + } + + + @Override + public void warmstart() { + int problems = removeAllCurrentProblemsOfNode(); + LOG.debug("Removed all {} problems from database at deregistration for {}", problems, mountPointNodeName); + } + + @Override + public NodeId getNodeId() { + return nodeId; + } + + public TransactionUtils getGenericTransactionUtils() { + return acessor.getTransactionUtils(); + } + + /*--------------------------------------------------------------- + * Getter/ Setter + */ + @Override + public String getMountpoint() { + return mountPointNodeName; + } + + @Override + public DataBroker getDataBroker() { + return netconfNodeDataBroker; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementCallback.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementCallback.java new file mode 100644 index 000000000..12790b30e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementCallback.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; + +public interface ONFCoreNetworkElementCallback { + + public void notificationFromNeListener(AttributeValueChangedNotificationXml notificationXml); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementEmpty.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementEmpty.java new file mode 100644 index 000000000..2c623d8d3 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementEmpty.java @@ -0,0 +1,161 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.Optional; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElementService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.legacy.InventoryInformation; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author herbert + * + */ +public class ONFCoreNetworkElementEmpty implements ONFCoreNetworkElementRepresentation { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElementEmpty.class); + + private final String mountPointNodeName; + private final NodeId nodeId; + + ONFCoreNetworkElementEmpty(String mountPointNodeName) { + LOG.info("Create {}",ONFCoreNetworkElementEmpty.class.getSimpleName()); + this.mountPointNodeName = mountPointNodeName; + this.nodeId = new NodeId(mountPointNodeName); + } + + @Override + public void initialReadFromNetworkElement() { + } + + @Override + public String getMountPointNodeName() { + return mountPointNodeName; + } + + @Override + public String getMountpoint() { + return mountPointNodeName; + } + + @Override + public void resetPMIterator() { + } + + @Override + public boolean hasNext() { + return false; + } + + @Override + public void next() { + } + + @Override + public AllPm getHistoricalPM() { + return AllPm.getEmpty(); + } + + @Override + public String pmStatusToString() { + return this.getClass().getSimpleName(); + } + + @Override + public int removeAllCurrentProblemsOfNode() { + return 0; + } + + @Override + public void doRegisterEventListener(MountPoint mointPoint) { + //Do nothing + } + + @Override + public void prepareCheck() { + //Do nothing here + } + + @Override + public boolean checkIfConnectionToMediatorIsOk() { + return true; + } + + @Override + public boolean checkIfConnectionToNeIsOk() { + return true; + } + + @Override + public InventoryInformation getInventoryInformation() { + return InventoryInformation.getDefault(); + } + + @Override + public InventoryInformation getInventoryInformation(String layerProtocolFilter) { + return InventoryInformation.getDefault(); + } + + @Override + public DataBroker getDataBroker() { + return null; + } + + @Override + public NetworkElement getOptionalNetworkElement() { + return null; + } + + @Override + public NetworkElementDeviceType getDeviceType() { + return NetworkElementDeviceType.Unknown; + } + + @Override + public void register() { + } + + @Override + public void deregister() { + } + + @Override + public NodeId getNodeId() { + return nodeId; + } + + @Override + public <L extends NetworkElementService> Optional<L> getService(Class<L> clazz) { + return Optional.empty(); + } + + @Override + public void warmstart() { + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementFactory.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementFactory.java new file mode 100644 index 000000000..58dcfd2d0 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementFactory.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import java.util.Optional; +import org.eclipse.jdt.annotation.NonNull; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerServiceProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElementFactory; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.UnkownDevicemanagerServiceException; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.OnfMicrowaveModel; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.WrapperMicrowaveModelRev170324; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.WrapperMicrowaveModelRev180907; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.WrapperMicrowaveModelRev181010; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DevicemanagerNotificationDelayService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.NetworkElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Create a Network Element representation according to the capability + * information. The capabilities are more than an ODL-QName. After the ? other + * terms than "revision" are provided. + * + */ +public class ONFCoreNetworkElementFactory implements NetworkElementFactory { + + private static final Logger LOG = LoggerFactory.getLogger(ONFCoreNetworkElementFactory.class); + + private static final ONFCoreNetworkElementRepresentation ONFCORE_NETWORKELEMENT_LOCK = new ONFCoreNetworkElementEmpty("NE-LOCK"); + + /** + * Used as Lock by devicemanager + * @return ONFCoreNetworkElementRepresentation for lock purpose + */ + public @NonNull ONFCoreNetworkElementRepresentation getLock() { + return ONFCORE_NETWORKELEMENT_LOCK; + } + + @Override + public Optional<org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement> create(INetconfAcessor acessor, + DeviceManagerServiceProvider serviceProvider) { + try { + DataProvider dataProvider = serviceProvider.getDataProvider(); + WebSocketServiceClientInternal webSocketService = serviceProvider.getService(WebSocketServiceClientInternal.class); + DcaeForwarderInternal aotsDcaeForwarder = serviceProvider.getService(DcaeForwarderInternal.class); + DevicemanagerNotificationDelayService notificationDelayService = serviceProvider + .getService(DevicemanagerNotificationDelayService.class); + + Capabilities capabilities = acessor.getCapabilites(); + + if (capabilities.isSupportingNamespaceAndRevision(NetworkElement.QNAME)) { + OnfMicrowaveModel onfMicrowaveModel = null; + + if (capabilities.isSupportingNamespaceAndRevision(WrapperMicrowaveModelRev170324.QNAME)) { + onfMicrowaveModel = new WrapperMicrowaveModelRev170324(acessor); + } else if (capabilities.isSupportingNamespaceAndRevision(WrapperMicrowaveModelRev180907.QNAME)) { + onfMicrowaveModel = new WrapperMicrowaveModelRev180907(acessor); + } else if (capabilities.isSupportingNamespaceAndRevision(WrapperMicrowaveModelRev181010.QNAME)) { + onfMicrowaveModel = new WrapperMicrowaveModelRev181010(acessor); + } + + String mountPointNodeName = acessor.getNodeId().getValue(); + DataBroker netconfNodeDataBroker = acessor.getDataBroker(); + + if (onfMicrowaveModel != null) { + return Optional.of(new ONFCoreNetworkElement12Microwave(acessor, mountPointNodeName, capabilities, netconfNodeDataBroker, + webSocketService, dataProvider, aotsDcaeForwarder, + notificationDelayService, onfMicrowaveModel)); + } else { + return Optional.of(new ONFCoreNetworkElement12Basic(acessor, mountPointNodeName, capabilities, netconfNodeDataBroker, + webSocketService, dataProvider, aotsDcaeForwarder, + notificationDelayService)); + } + } + + } catch (UnkownDevicemanagerServiceException e) { + LOG.warn("Service missing", e); + } + return Optional.empty(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementRepresentation.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementRepresentation.java new file mode 100644 index 000000000..565a0f591 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/ONFCoreNetworkElementRepresentation.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.InventoryProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.MicrowaveModelPerformanceDataProvider; +import org.opendaylight.mdsal.binding.api.MountPoint; + +public interface ONFCoreNetworkElementRepresentation + extends DeviceMonitoredNe, MicrowaveModelPerformanceDataProvider, NetworkElementCoreData, InventoryProvider, NetworkElement { + + /** + * Read during startup all relevant structure and status parameters from device. + * Remove all currentAlarms, read structure from networkElement with all + * interfacePacs, read current alarm status + */ + public void initialReadFromNetworkElement(); + + public String getMountPointNodeName(); + + public int removeAllCurrentProblemsOfNode(); + + public void doRegisterEventListener(MountPoint mountPoint); +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/AllPm.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/AllPm.java new file mode 100644 index 000000000..36f4b9709 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/AllPm.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance15Minutes; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance24Hours; + +public class AllPm { + + private final static AllPm EMPTY = new AllPm(); + + private final List<EsHistoricalPerformance15Minutes> pm15 = new ArrayList<>(); + private final List<EsHistoricalPerformance24Hours> pm24 = new ArrayList<>(); + + public void add(EsHistoricalPerformance15Minutes pm) { + pm15.add(pm); + } + + public void add(EsHistoricalPerformance24Hours pm) { + pm24.add(pm); + } + + public List<EsHistoricalPerformance15Minutes> getPm15() { + return pm15; + } + + public List<EsHistoricalPerformance24Hours> getPm24() { + return pm24; + } + + public Object size() { + return pm15.size()+pm24.size(); + } + + public static AllPm getEmpty() { + return EMPTY; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType12.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType12.java new file mode 100644 index 000000000..cbff0c9ef --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType12.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.LinkIdentifyingObject; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.ObjectIdentifier; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceConfigurationG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yangtools.yang.binding.DataContainer; + +public class ExtendedAirInterfaceHistoricalPerformanceType12 implements OtnHistoryDataG, LinkIdentifyingObject { + + private final AirInterfaceHistoricalPerformanceTypeG airInterfaceHistoricalPerformanceType; + private final AirInterfaceConfigurationG airInterfaceConfiguration; + + public ExtendedAirInterfaceHistoricalPerformanceType12(AirInterfaceHistoricalPerformanceTypeG data, AirInterfaceConfigurationG conf) { + this.airInterfaceHistoricalPerformanceType = data; + this.airInterfaceConfiguration = conf; + } + + + public AirInterfaceHistoricalPerformanceTypeG getAirInterfaceHistoricalPerformanceType() { + return airInterfaceHistoricalPerformanceType; + } + + + public AirInterfaceConfigurationG getAirInterfaceConfiguration() { + return airInterfaceConfiguration; + } + + + @Override + public Class<? extends DataContainer> getImplementedInterface() { + return airInterfaceHistoricalPerformanceType.getImplementedInterface(); + } + + @Override + public String getHistoryDataId() { + return airInterfaceHistoricalPerformanceType.getHistoryDataId(); + } + + @Override + public DateAndTime getPeriodEndTime() { + return airInterfaceHistoricalPerformanceType.getPeriodEndTime(); + } + + + @Override + public GranularityPeriodType getGranularityPeriod() { + return airInterfaceHistoricalPerformanceType.getGranularityPeriod(); + } + + + @Override + public ObjectIdentifier getObjectClass() { + return airInterfaceHistoricalPerformanceType.getObjectClass(); + } + + + @Override + public ObjectIdentifier getNameBinding() { + return airInterfaceHistoricalPerformanceType.getNameBinding(); + } + + @Override + public Boolean isSuspectIntervalFlag() { + return airInterfaceHistoricalPerformanceType.isSuspectIntervalFlag(); + } + + @Override + public String getSignalId() { + return airInterfaceConfiguration.getRadioSignalId(); + } + + + @Override + public String toString() { + return "ExtendedAirInterfaceHistoricalPerformanceType [airInterfaceHistoricalPerformanceType=" + + airInterfaceHistoricalPerformanceType + ", airInterfaceConfiguration=" + airInterfaceConfiguration + + "]"; + } + + + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211.java new file mode 100644 index 000000000..b21b04fe2 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.LinkIdentifyingObject; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.ObjectIdentifier; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceConfigurationG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yangtools.yang.binding.DataContainer; + +public class ExtendedAirInterfaceHistoricalPerformanceType1211 implements OtnHistoryDataG, LinkIdentifyingObject { + + private final AirInterfaceHistoricalPerformanceTypeG airInterfaceHistoricalPerformanceType; + private final AirInterfaceConfigurationG airInterfaceConfiguration; + + public ExtendedAirInterfaceHistoricalPerformanceType1211(AirInterfaceHistoricalPerformanceTypeG data, AirInterfaceConfigurationG conf) { + this.airInterfaceHistoricalPerformanceType = data; + this.airInterfaceConfiguration = conf; + } + + + public AirInterfaceHistoricalPerformanceTypeG getAirInterfaceHistoricalPerformanceType() { + return airInterfaceHistoricalPerformanceType; + } + + + public AirInterfaceConfigurationG getAirInterfaceConfiguration() { + return airInterfaceConfiguration; + } + + + @Override + public Class<? extends DataContainer> getImplementedInterface() { + return airInterfaceHistoricalPerformanceType.getImplementedInterface(); + } + + @Override + public String getHistoryDataId() { + return airInterfaceHistoricalPerformanceType.getHistoryDataId(); + } + + @Override + public DateAndTime getPeriodEndTime() { + return airInterfaceHistoricalPerformanceType.getPeriodEndTime(); + } + + + @Override + public GranularityPeriodType getGranularityPeriod() { + return airInterfaceHistoricalPerformanceType.getGranularityPeriod(); + } + + + @Override + public ObjectIdentifier getObjectClass() { + return airInterfaceHistoricalPerformanceType.getObjectClass(); + } + + + @Override + public ObjectIdentifier getNameBinding() { + return airInterfaceHistoricalPerformanceType.getNameBinding(); + } + + @Override + public Boolean isSuspectIntervalFlag() { + return airInterfaceHistoricalPerformanceType.isSuspectIntervalFlag(); + } + + @SuppressWarnings("deprecation") + @Override + public String getSignalId() { + return airInterfaceConfiguration.getRadioSignalId(); + } + + + @Override + public String toString() { + return "ExtendedAirInterfaceHistoricalPerformanceType [airInterfaceHistoricalPerformanceType=" + + airInterfaceHistoricalPerformanceType + ", airInterfaceConfiguration=" + airInterfaceConfiguration + + "]"; + } + + + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211p.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211p.java new file mode 100644 index 000000000..1fdadd090 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedAirInterfaceHistoricalPerformanceType1211p.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.LinkIdentifyingObject; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.ObjectIdentifier; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceConfigurationG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yangtools.yang.binding.DataContainer; + +public class ExtendedAirInterfaceHistoricalPerformanceType1211p implements OtnHistoryDataG, LinkIdentifyingObject { + + private final AirInterfaceHistoricalPerformanceTypeG airInterfaceHistoricalPerformanceType; + private final AirInterfaceConfigurationG airInterfaceConfiguration; + + public ExtendedAirInterfaceHistoricalPerformanceType1211p(AirInterfaceHistoricalPerformanceTypeG data, AirInterfaceConfigurationG conf) { + this.airInterfaceHistoricalPerformanceType = data; + this.airInterfaceConfiguration = conf; + } + + + public AirInterfaceHistoricalPerformanceTypeG getAirInterfaceHistoricalPerformanceType() { + return airInterfaceHistoricalPerformanceType; + } + + + public AirInterfaceConfigurationG getAirInterfaceConfiguration() { + return airInterfaceConfiguration; + } + + + @Override + public Class<? extends DataContainer> getImplementedInterface() { + return airInterfaceHistoricalPerformanceType.getImplementedInterface(); + } + + @Override + public String getHistoryDataId() { + return airInterfaceHistoricalPerformanceType.getHistoryDataId(); + } + + @Override + public DateAndTime getPeriodEndTime() { + return airInterfaceHistoricalPerformanceType.getPeriodEndTime(); + } + + + @Override + public GranularityPeriodType getGranularityPeriod() { + return airInterfaceHistoricalPerformanceType.getGranularityPeriod(); + } + + + @Override + public ObjectIdentifier getObjectClass() { + return airInterfaceHistoricalPerformanceType.getObjectClass(); + } + + + @Override + public ObjectIdentifier getNameBinding() { + return airInterfaceHistoricalPerformanceType.getNameBinding(); + } + + @Override + public Boolean isSuspectIntervalFlag() { + return airInterfaceHistoricalPerformanceType.isSuspectIntervalFlag(); + } + + @SuppressWarnings("deprecation") + @Override + public String getSignalId() { + return airInterfaceConfiguration.getRadioSignalId(); + } + + + @Override + public String toString() { + return "ExtendedAirInterfaceHistoricalPerformanceType [airInterfaceHistoricalPerformanceType=" + + airInterfaceHistoricalPerformanceType + ", airInterfaceConfiguration=" + airInterfaceConfiguration + + "]"; + } + + + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedEquipment.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedEquipment.java new file mode 100644 index 000000000..5bffd989a --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ExtendedEquipment.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import java.util.ArrayList; +import java.util.List; + +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.Equipment; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.equipment.g.ContainedHolder; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.equipment.g.ManufacturedThing; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.manufactured.thing.g.EquipmentInstance; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.manufactured.thing.g.EquipmentType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.manufactured.thing.g.ManufacturerProperties; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Inventory; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.InventoryBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExtendedEquipment { + + private static final Logger LOG = LoggerFactory.getLogger(ExtendedEquipment.class); + + public static final String ESDATATYPENAME = "inventoryequipment"; + private final String parentUuid; + private final int treeLevel; + private final Equipment equipment; + private final String nodeId; + private final String path; + /** + * Equipment with additional information beside NETCONF equipment + * + * @param parentUuid of parent equipment + * @param equipment NETCONF Equipment + * @param treeLevel level of tree starting with root at 0 + */ + public ExtendedEquipment(String nodeId, String parentUuid, Equipment equipment, String path, int treeLevel) { + super(); + this.nodeId = nodeId; + this.parentUuid = parentUuid; + this.equipment = equipment; + this.path = path; + this.treeLevel = treeLevel; + } + + public String getParentUuid() { + return parentUuid; + } + + public Equipment getEquipment() { + return equipment; + } + + public int getTreeLevel() { + return treeLevel; + } + public String getNodeId() { + return nodeId; + } + + public Inventory getCreateInventoryInput() { + + InventoryBuilder inventoryBuilder = new InventoryBuilder(); + + // General + inventoryBuilder.setNodeId(getNodeId()); + inventoryBuilder.setParentUuid(getParentUuid()); + inventoryBuilder.setTreeLevel(new Long(getTreeLevel())); + + if (equipment != null) { + inventoryBuilder.setUuid(equipment.getUuid().getValue()); + // -- String list with ids of holders + List<String> containerHolderKeyList = new ArrayList<>(); + List<ContainedHolder> containerHolderList = equipment.getContainedHolder(); + if (containerHolderList != null) { + for (ContainedHolder containerHolder : containerHolderList) { + containerHolderKeyList.add(containerHolder.getUuid().getValue()); + } + } + inventoryBuilder.setContainedHolder(containerHolderKeyList); + + // -- Manufacturer related things + ManufacturedThing mThing = equipment.getManufacturedThing(); + if (mThing != null) { + ManufacturerProperties mProperties = mThing.getManufacturerProperties(); + if (mProperties != null) { + inventoryBuilder.setManufacturerName(mProperties.getManufacturerName()); + inventoryBuilder.setManufacturerIdentifier(mProperties.getManufacturerIdentifier()); + } + EquipmentType mType = mThing.getEquipmentType(); + if (mType != null) { + inventoryBuilder.setDescription(mType.getDescription()); + inventoryBuilder.setModelIdentifier(mType.getModelIdentifier()); + inventoryBuilder.setPartTypeId(mType.getPartTypeIdentifier()); + inventoryBuilder.setTypeName(mType.getTypeName()); + inventoryBuilder.setVersion(mType.getVersion()); + } + EquipmentInstance mInstance = mThing.getEquipmentInstance(); + if (mInstance != null) { + String manufacturedDateString = mInstance.getManufactureDate(); + if (manufacturedDateString != null && !manufacturedDateString.isEmpty()) { + try { + inventoryBuilder.setDate(mInstance.getManufactureDate()); + } catch (IllegalArgumentException e) { + LOG.debug("Format problem", e); + } + } + inventoryBuilder.setSerial(mInstance.getSerialNumber()); + } + } + } + + return inventoryBuilder.build(); + } + + @Override + public String toString() { + return "ExtendedEquipment [parentUuid=" + parentUuid + ", treeLevel=" + treeLevel + ", equipment=" + equipment + + ", nodeId=" + nodeId + ", path=" + path + "]"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ONFLayerProtocolName.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ONFLayerProtocolName.java new file mode 100644 index 000000000..7f0e60d5e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ONFLayerProtocolName.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public enum ONFLayerProtocolName { + + MWAirInterface("MWPS"), //V1.0 + V1.2 + EthernetContainer10("ETH-CTP"), //V1.0 + EthernetContainer12("ETC"), //V1.2 + V1.2.1.1 + EthernetPhysical("ETY"), //V1.2 + TDMContainer("TDM"), //V1.2 + Structure("MWS"), //V1.0 + V1.2 + Ethernet("ETH"), //V1.2 + Unknown(""); + + private static final Logger LOG = LoggerFactory.getLogger(ONFLayerProtocolName.class); + + private final String myLayerProtocolName; + + ONFLayerProtocolName( String myLayerProtocolName ) { + this.myLayerProtocolName = myLayerProtocolName; + } + + public boolean is( org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.LayerProtocolName onfName ) { + return myLayerProtocolName.equals(onfName.getValue()); + } + + public static ONFLayerProtocolName valueOf( org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.LayerProtocolName onfName ) { + for (ONFLayerProtocolName protocol : ONFLayerProtocolName.values()) { + if (protocol.is(onfName)) { + return protocol; + } + } + LOG.info("Can not map {}. Use Unknown",onfName.getValue() ); + return Unknown; + } + + public String getValue() { + return myLayerProtocolName; + } + +} + diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ValueNameList.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ValueNameList.java new file mode 100644 index 000000000..1af59a007 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/container/ValueNameList.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container; + +import java.util.HashMap; +import java.util.List; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.extension.g.Extension; + +/** + * ValueNameList is an access Wrapper to NETCONF Extension lists + * Class is a specialized HashMap. + */ +public class ValueNameList extends HashMap<String, String> { + + private static final long serialVersionUID = 1L; + + /** + * Create ValueNameList for NETCONF extensions + * @param extensionList Parameters as received from device. Could be null. + */ + public void put(@Nullable List<Extension> extensionList) { + + if (extensionList != null) { + String name; + String value; + + for (Extension e : extensionList) { + name = e.getValueName(); + value = e.getValue(); + if (name != null && value != null) { + put(name, value); + } + } + } + } + + /** + * Return value or null + * @param name key for element + * @return value if key exists; if not nul + */ + public String getOrNull(String name) { + return containsKey(name) ? get(name) : null; + } + + /** + * Get element as id list + * @param name key of element + * @param topLevelEqUuidList as input to add elements + * @return List<UniversalId> + */ + public @NonNull List<UniversalId> getAsUniversalIdList(String name, List<UniversalId> topLevelEqUuidList) { + if (containsKey(name)) { + String[] result = get(name).split(",\\s*"); + if (result.length > 0) { + for (String e : result) { + topLevelEqUuidList.add(new UniversalId(e)); + } + } + } + return topLevelEqUuidList; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfInterfacePac.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfInterfacePac.java new file mode 100644 index 000000000..674f06768 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfInterfacePac.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + +import java.util.List; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; + +public interface OnfInterfacePac { + + /** + * Read problems of specific interfaces. TODO Goal for future implementation + * without usage of explicit new. Key is generated by newInstance() function + * here to verify this approach. + * + * @param interfacePacUuid Universal index of Interfacepac + * @param resultList List to add fault. If null new list is created. + * @return list of alarms + */ + public List<ProblemNotificationXml> readTheFaults(UniversalId interfacePacUuid, @Nullable List<ProblemNotificationXml> resultList); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModel.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModel.java new file mode 100644 index 000000000..bd7aa835c --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModel.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yangtools.yang.binding.NotificationListener; +import org.opendaylight.yangtools.yang.common.QName; + +public interface OnfMicrowaveModel { + + public void setCoreData(NetworkElementCoreData coreData); + + public void readTheFaultsOfMicrowaveModel(ONFLayerProtocolName lpName, Class<?> lpClass, UniversalId uuid, + List<ProblemNotificationXml> resultList); + + public List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(ONFLayerProtocolName lpName, Lp lp); + + public Class<?> getClassForLtpExtension(QName qName); + + public <T extends NotificationListener> T getNotificationListener(); + + public void setOnfMicrowaveModelListener(OnfMicrowaveModelNotification microwaveModelListener); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModelNotification.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModelNotification.java new file mode 100644 index 000000000..3f91f6f6c --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/OnfMicrowaveModelNotification.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; + +/** + * Abstraction of YANG specified notifications + * Each method converts from internal specific class to model unspecific class + * @author herbert + * + */ +public interface OnfMicrowaveModelNotification { + + void onObjectCreationNotification(ObjectCreationNotificationXml notificationXml); + void onObjectDeletionNotification(ObjectDeletionNotificationXml notificationXml); + void onProblemNotification(ProblemNotificationXml notificationXml); + void onAttributeValueChangedNotification(AttributeValueChangedNotificationXml notificationXml); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperEquipmentPacRev170402.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperEquipmentPacRev170402.java new file mode 100644 index 000000000..15a9cfd45 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperEquipmentPacRev170402.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.CurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.EquipmentPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.EquipmentPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.onf.core.model.conditional.packages.rev170402.equipment.pac.EquipmentCurrentProblems; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.common.QName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WrapperEquipmentPacRev170402 implements OnfInterfacePac { + + private static final Logger LOG = LoggerFactory.getLogger(WrapperEquipmentPacRev170402.class); + public static final QName QNAME = EquipmentPac.QNAME; + + private final NetworkElementCoreData coreData; + private final INetconfAcessor acessor; + + + public WrapperEquipmentPacRev170402(INetconfAcessor acessor, NetworkElementCoreData coreData) { + this.coreData = coreData; + this.acessor = acessor; + } + + private TransactionUtils getGenericTransactionUtils() { + return acessor.getTransactionUtils(); + } + + /** + * Read problems of specific interfaces. TODO Goal for future implementation without usage of + * explicit new. Key is generated by newInstance() function here to verify this approach. + * + * @param interfacePacUuid Universal index of onf interface-pac + * @param resultList list to add, or null for new list. + * @return list of alarms + */ + @Override + public List<ProblemNotificationXml> readTheFaults(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<EquipmentPac> clazzPac = EquipmentPac.class; + final Class<EquipmentPacKey> clazzPacKey = EquipmentPacKey.class; + final Class<EquipmentCurrentProblems> clazzProblems = EquipmentCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + try { + if (resultList == null) { + resultList = new ArrayList<>(); + } + // -- Specific part 1 + Constructor<EquipmentPacKey> cons = clazzPacKey.getConstructor(UniversalId.class); // Avoid new() + InstanceIdentifier<EquipmentCurrentProblems> interfaceIID = InstanceIdentifier + .builder(clazzPac, cons.newInstance(interfacePacUuid)).child(clazzProblems).build(); + + // -- Specific part 2 + EquipmentCurrentProblems problems = getGenericTransactionUtils().readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, interfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no {}", interfacePacUuid, clazzProblems, clazzProblems.getName()); + } else { + // -- Specific part 3 + for (CurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOG.warn("Could not reade instance of MwTdmContainerPacKey: ", e); + } + return resultList; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev170324.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev170324.java new file mode 100644 index 000000000..b0a9558c3 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev170324.java @@ -0,0 +1,593 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + + + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nonnull; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType12; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceDiversityCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AttributeValueChangedNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ContainerCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ContainerHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MicrowaveModelListener; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwAirInterfaceDiversityPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwAirInterfaceDiversityPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwAirInterfacePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwAirInterfacePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwEthernetContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwEthernetContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwHybridMwStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwHybridMwStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwPureEthernetStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwPureEthernetStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwTdmContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.MwTdmContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ObjectCreationNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ObjectDeletionNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ProblemNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.StructureCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.air._interface.diversity.pac.AirInterfaceDiversityCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.air._interface.pac.AirInterfaceConfiguration; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.air._interface.pac.AirInterfaceCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.air._interface.pac.AirInterfaceHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.ethernet.container.pac.EthernetContainerCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.ethernet.container.pac.EthernetContainerHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.hybrid.mw.structure.pac.HybridMwStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.pure.ethernet.structure.pac.PureEthernetStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.mw.tdm.container.pac.TdmContainerCurrentProblems; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.NotificationListener; +import org.opendaylight.yangtools.yang.common.QName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class WrapperMicrowaveModelRev170324 implements OnfMicrowaveModel, MicrowaveModelListener { + + private static final Logger LOG = LoggerFactory.getLogger(WrapperMicrowaveModelRev170324.class); + + public static final QName QNAME = MwAirInterfacePac.QNAME; + + + private NetworkElementCoreData coreData; + private OnfMicrowaveModelNotification microwaveModelListener; + private final TransactionUtils genericTransactionUtils; + + /*----------------------------------------------------------------------------- + * Setter/Getter + */ + + /** + * @param acessor + */ + public WrapperMicrowaveModelRev170324(INetconfAcessor acessor) { + genericTransactionUtils = acessor.getTransactionUtils(); + } + + @Override + public void setCoreData(NetworkElementCoreData coreData) { + this.coreData = coreData; + } + + public NetworkElementCoreData getCoreData() { + return coreData; + } + + @Override + public void setOnfMicrowaveModelListener(OnfMicrowaveModelNotification microwaveModelListener) { + this.microwaveModelListener = microwaveModelListener; + } + + @SuppressWarnings("unchecked") + @Override + public <T extends NotificationListener> T getNotificationListener() { + return (T)this; + } + + /*----------------------------------------------------------------------------- + * Interfacefunctions + */ + + @Override + public void readTheFaultsOfMicrowaveModel(ONFLayerProtocolName lpName, Class<?> lpClass, UniversalId uuid, + List<ProblemNotificationXml> resultList) { + + switch (lpName) { + case MWAirInterface: + readTheFaultsOfMwAirInterfacePac(uuid, resultList); + break; + + case EthernetContainer12: + readTheFaultsOfMwEthernetContainerPac(uuid, resultList); + break; + + case TDMContainer: + readTheFaultsOfMwTdmContainerPac(uuid, resultList); + break; + + case Structure: + if (lpClass == MwHybridMwStructurePac.class) { + readTheFaultsOfMwHybridMwStructurePac(uuid, resultList); + + } else if (lpClass == MwAirInterfaceDiversityPac.class) { + readTheFaultsOfMwAirInterfaceDiversityPac(uuid, resultList); + + } else if (lpClass == MwPureEthernetStructurePac.class) { + readTheFaultsOfMwPureEthernetStructurePac(uuid, resultList); + + } else { + LOG.warn("Unassigned lp model {} class {}", lpName, lpClass); + } + break; + case Ethernet: + // No alarms supported + break; + case EthernetContainer10: + default: + LOG.warn("Unassigned or not expected lp in model {}", lpName); + } + } + + @Override + public List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(@Nonnull ONFLayerProtocolName lpName, Lp lp) { + switch (lpName) { + case MWAirInterface: + return readTheHistoricalPerformanceDataOfMwAirInterfacePac(lp); + + case EthernetContainer12: + return readTheHistoricalPerformanceDataOfEthernetContainer(lp); + + case EthernetContainer10: + case EthernetPhysical: + case Ethernet: + case TDMContainer: + case Structure: + case Unknown: + LOG.debug("Do not read HistoricalPM data for {} {}", lpName, getUuid(lp)); + break; + } + return new ArrayList<>(); + } + @Override + public Class<?> getClassForLtpExtension(QName qName) { + Class<?> res = null; + if (qName.equals(MwAirInterfacePac.QNAME)) { + res = MwAirInterfacePac.class; + } else if (qName.equals(MwAirInterfaceDiversityPac.QNAME)) { + res = MwAirInterfaceDiversityPac.class; + } else if (qName.equals(MwPureEthernetStructurePac.QNAME)) { + res = MwPureEthernetStructurePac.class; + } else if (qName.equals(MwHybridMwStructurePac.QNAME)) { + res = MwHybridMwStructurePac.class; + } else if (qName.equals(MwEthernetContainerPac.QNAME)) { + res = MwEthernetContainerPac.class; + } else if (qName.equals(MwTdmContainerPac.QNAME)) { + res = MwTdmContainerPac.class; + } + LOG.info("Found QName {} mapped to {}", String.valueOf(qName), String.valueOf(res)); + return res; + } + + /*----------------------------------------------------------------------------- + * Reading problems for specific interface pacs + */ + + /** + * Read problems of specific interfaces + * + * @param uuId Universal Id String of the interface + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfacePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfacePac> clazzPac = MwAirInterfacePac.class; + // final Class<MwAirInterfacePacKey> clazzPacKey = MwAirInterfacePacKey.class; + // final Class<AirInterfaceCurrentProblems> clazzProblems = + // AirInterfaceCurrentProblems.class; + // final Class<AirInterfaceCurrentProblemTypeG> clazzProblem = + // AirInterfaceCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceCurrentProblems> mwAirInterfaceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(interfacePacUuid)) + .child(AirInterfaceCurrentProblems.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceIID); + + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceCurrentProblems", interfacePacUuid); + } else { + for (AirInterfaceCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwEthernetContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwEthernetContainerPac> clazzPac = MwEthernetContainerPac.class; + // final Class<MwEthernetContainerPacKey> clazzPacKey = + // MwEthernetContainerPacKey.class; + // final Class<EthernetContainerCurrentProblems> clazzProblems = + // EthernetContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<EthernetContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(interfacePacUuid)) + .child(EthernetContainerCurrentProblems.class).build(); + + EthernetContainerCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no EthernetContainerCurrentProblems", interfacePacUuid); + } else { + for (ContainerCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfaceDiversityPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfaceDiversityPac> clazzPac = MwAirInterfaceDiversityPac.class; + // final Class<MwAirInterfaceDiversityPacKey> clazzPacKey = + // MwAirInterfaceDiversityPacKey.class; + final Class<AirInterfaceDiversityCurrentProblems> clazzProblems = AirInterfaceDiversityCurrentProblems.class; + // final Class<AirInterfaceDiversityCurrentProblemTypeG> clazzProblem = + // AirInterfaceDiversityCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<AirInterfaceDiversityCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwAirInterfaceDiversityPacKey(interfacePacUuid)).child(clazzProblems).build(); + + AirInterfaceDiversityCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceDiversityCurrentProblems", interfacePacUuid); + } else { + for (AirInterfaceDiversityCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwPureEthernetStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwPureEthernetStructurePac> clazzPac = MwPureEthernetStructurePac.class; + // final Class<MwPureEthernetStructurePacKey> clazzPacKey = + // MwPureEthernetStructurePacKey.class; + final Class<PureEthernetStructureCurrentProblems> clazzProblems = PureEthernetStructureCurrentProblems.class; + // final Class<StructureCurrentProblemTypeG> clazzProblem = + // StructureCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<PureEthernetStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwPureEthernetStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + PureEthernetStructureCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no PureEthernetStructureCurrentProblems", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwHybridMwStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwHybridMwStructurePac> clazzPac = MwHybridMwStructurePac.class; + // final Class<MwHybridMwStructurePacKey> clazzPacKey = + // MwHybridMwStructurePacKey.class; + final Class<HybridMwStructureCurrentProblems> clazzProblems = HybridMwStructureCurrentProblems.class; + // final Class<HybridMwStructureCurrentProblemsG> clazzProblem = + // HybridMwStructureCurrentProblemsG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<HybridMwStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwHybridMwStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + HybridMwStructureCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no HybridMwStructureCurrentProblems", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces. TODO Goal for future implementation + * without usage of explicit new. Key is generated by newInstance() function + * here to verify this approach. + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + * @throws SecurityException + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private List<ProblemNotificationXml> readTheFaultsOfMwTdmContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwTdmContainerPac> clazzPac = MwTdmContainerPac.class; + final Class<MwTdmContainerPacKey> clazzPacKey = MwTdmContainerPacKey.class; + final Class<TdmContainerCurrentProblems> clazzProblems = TdmContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + try { + // -- Specific part 1 + Constructor<MwTdmContainerPacKey> cons = clazzPacKey.getConstructor(UniversalId.class); // Avoid new() + InstanceIdentifier<TdmContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, cons.newInstance(interfacePacUuid)).child(clazzProblems).build(); + + // -- Specific part 2 + TdmContainerCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no TdmContainerCurrentProblems", interfacePacUuid); + } else { + // -- Specific part 3 + for (ContainerCurrentProblemTypeG problem : problems.nonnullCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOG.warn("Could not reade instance of MwTdmContainerPacKey: ", e); + } + return resultList; + } + + /*----------------------------------------------------------------------------- + * Performance related data + */ + + /** + * PM MwAirInterfacePac + * + * @param lp + * @return + */ + private List<ExtendedAirInterfaceHistoricalPerformanceType12> readTheHistoricalPerformanceDataOfMwAirInterfacePac( + Lp lp) { + + List<ExtendedAirInterfaceHistoricalPerformanceType12> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} MWAirInterfacePac: {}", coreData.getMountpoint(), lp.getUuid()); + // ---- + UniversalId mwAirInterfacePacuuId = lp.getUuid(); + // Step 2.1: construct data and the relative iid + InstanceIdentifier<AirInterfaceConfiguration> mwAirInterfaceConfigurationIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceConfiguration.class).build(); + AirInterfaceConfiguration airConfiguration = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceConfigurationIID); + + if (airConfiguration == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceConfiguration", mwAirInterfacePacuuId); + + } else { + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceHistoricalPerformances> mwAirInterfaceHistoricalPerformanceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceHistoricalPerformances airHistoricalPerformanceData = genericTransactionUtils.readData( + coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, mwAirInterfaceHistoricalPerformanceIID); + + if (airHistoricalPerformanceData == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceHistoricalPerformances", + mwAirInterfacePacuuId); + } else { + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.air._interface.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.air._interface.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = airHistoricalPerformanceData + .nonnullHistoricalPerformanceDataList(); + LOG.debug("DBRead MWAirInterfacePac Id {} Records intermediate: {}", mwAirInterfacePacuuId, + airHistPMList.size()); + for (AirInterfaceHistoricalPerformanceTypeG pmRecord : airHistoricalPerformanceData + .nonnullHistoricalPerformanceDataList()) { + resultList.add(new ExtendedAirInterfaceHistoricalPerformanceType12(pmRecord, airConfiguration)); + } + } + } + LOG.debug("DBRead MWAirInterfacePac Id {} Records result: {}", mwAirInterfacePacuuId, resultList.size()); + return resultList; + } + + private List<ContainerHistoricalPerformanceTypeG> readTheHistoricalPerformanceDataOfEthernetContainer(Lp lp) { + + final String myName = "MWEthernetContainerPac"; + + List<ContainerHistoricalPerformanceTypeG> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} : {}", coreData.getMountpoint(), myName, lp.getUuid()); + // ---- + UniversalId ethContainerPacuuId = lp.getUuid(); + // Step 2.2: construct data and the relative iid + InstanceIdentifier<EthernetContainerHistoricalPerformances> ethContainerIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(ethContainerPacuuId)) + .child(EthernetContainerHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + EthernetContainerHistoricalPerformances ethContainerHistoricalPerformanceData = genericTransactionUtils + .readData(coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, ethContainerIID); + + if (ethContainerHistoricalPerformanceData == null) { + LOG.debug("DBRead {} Id {} no HistoricalPerformances", myName, ethContainerPacuuId); + } else { + // import + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.ethernet.container.historical.performances.g.HistoricalPerformanceDataList + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ethernet.container.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ethernet.container.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = ethContainerHistoricalPerformanceData + .nonnullHistoricalPerformanceDataList(); + LOG.debug("DBRead {} Id {} Records intermediate: {}", myName, ethContainerPacuuId, airHistPMList.size()); + for (ContainerHistoricalPerformanceTypeG pmRecord : airHistPMList) { + resultList.add(pmRecord); + } + } + LOG.debug("DBRead {} Id {} Records result: {}", myName, ethContainerPacuuId, resultList.size()); + return resultList; + } + + @Override + public void onObjectCreationNotification(ObjectCreationNotification notification) { + LOG.debug("Got event of type :: {}", ObjectCreationNotification.class.getSimpleName()); + if (notification != null) { + ObjectCreationNotificationXml notificationXml = new ObjectCreationNotificationXml(coreData.getMountpoint(), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue()); + microwaveModelListener.onObjectCreationNotification(notificationXml); + } + } + + + + @Override + public void onObjectDeletionNotification(ObjectDeletionNotification notification) { + LOG.debug("Got event of type :: {}", ObjectDeletionNotification.class.getSimpleName()); + + ObjectDeletionNotificationXml notificationXml = new ObjectDeletionNotificationXml(coreData.getMountpoint(), + notification.getCounter(), + InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue() + ); + microwaveModelListener.onObjectDeletionNotification(notificationXml); + } + + @Override + public void onProblemNotification(ProblemNotification notification) { + + LOG.debug("Got event of type :: {}", ProblemNotification.class.getSimpleName()); + + ProblemNotificationXml notificationXml = new ProblemNotificationXml(coreData.getMountpoint(), notification.getObjectIdRef().getValue(), + notification.getProblem(), InternalSeverity.valueOf(notification.getSeverity()), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp())); + + microwaveModelListener.onProblemNotification(notificationXml); + } + + @Override + public void onAttributeValueChangedNotification(AttributeValueChangedNotification notification) { + LOG.debug("Got event of type :: {}", AttributeValueChangedNotification.class.getSimpleName()); + + AttributeValueChangedNotificationXml notificationXml = new AttributeValueChangedNotificationXml(coreData.getMountpoint(), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue(), notification.getAttributeName(), notification.getNewValue()); + + microwaveModelListener.onAttributeValueChangedNotification(notificationXml); + } + + private static String getUuid(Lp lp) { + UniversalId uuid = lp.getUuid(); + return uuid != null ? uuid.getValue() : null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev180907.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev180907.java new file mode 100644 index 000000000..f01f9c83d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev180907.java @@ -0,0 +1,608 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + + + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType1211; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceDiversityCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AttributeValueChangedNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ContainerCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ContainerHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MicrowaveModelListener; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwAirInterfaceDiversityPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwAirInterfaceDiversityPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwAirInterfacePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwAirInterfacePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwEthernetContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwEthernetContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwHybridMwStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwHybridMwStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwPureEthernetStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwPureEthernetStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwTdmContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.MwTdmContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ObjectCreationNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ObjectDeletionNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ProblemNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.StructureCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.air._interface.diversity.pac.AirInterfaceDiversityCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.air._interface.pac.AirInterfaceConfiguration; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.air._interface.pac.AirInterfaceCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.air._interface.pac.AirInterfaceHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.ethernet.container.pac.EthernetContainerCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.ethernet.container.pac.EthernetContainerHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.hybrid.mw.structure.pac.HybridMwStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.pure.ethernet.structure.pac.PureEthernetStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.mw.tdm.container.pac.TdmContainerCurrentProblems; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.NotificationListener; +import org.opendaylight.yangtools.yang.common.QName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class WrapperMicrowaveModelRev180907 implements OnfMicrowaveModel, MicrowaveModelListener { + + private static final Logger LOG = LoggerFactory.getLogger(WrapperMicrowaveModelRev180907.class); + + public static final QName QNAME = MwAirInterfacePac.QNAME; + + + private NetworkElementCoreData coreData; + + private OnfMicrowaveModelNotification microwaveModelListener; + + private final TransactionUtils genericTransactionUtil; + + + /*----------------------------------------------------------------------------- + * Setter/Getter + */ + + /** + * @param acessor + */ + public WrapperMicrowaveModelRev180907(INetconfAcessor acessor) { + genericTransactionUtil = acessor.getTransactionUtils(); + } + + @Override + public void setCoreData(NetworkElementCoreData coreData) { + this.coreData = coreData; + } + + public NetworkElementCoreData getCoreData() { + return coreData; + } + + @Override + public void setOnfMicrowaveModelListener(OnfMicrowaveModelNotification microwaveModelListener) { + this.microwaveModelListener = microwaveModelListener; + } + + @SuppressWarnings("unchecked") + @Override + public <T extends NotificationListener> T getNotificationListener() { + return (T) this; + } + + /*----------------------------------------------------------------------------- + * Interfacefunctions + */ + + @Override + public void readTheFaultsOfMicrowaveModel(ONFLayerProtocolName lpName, Class<?> lpClass, UniversalId uuid, + List<ProblemNotificationXml> resultList) { + + switch (lpName) { + case MWAirInterface: + readTheFaultsOfMwAirInterfacePac(uuid, resultList); + break; + + case EthernetContainer12: + readTheFaultsOfMwEthernetContainerPac(uuid, resultList); + break; + + case TDMContainer: + readTheFaultsOfMwTdmContainerPac(uuid, resultList); + break; + + case Structure: + if (lpClass == MwHybridMwStructurePac.class) { + readTheFaultsOfMwHybridMwStructurePac(uuid, resultList); + + } else if (lpClass == MwAirInterfaceDiversityPac.class) { + readTheFaultsOfMwAirInterfaceDiversityPac(uuid, resultList); + + } else if (lpClass == MwPureEthernetStructurePac.class) { + readTheFaultsOfMwPureEthernetStructurePac(uuid, resultList); + + } else { + LOG.warn("Unassigned lp model {} class {}", lpName, lpClass); + } + break; + case Ethernet: + // No alarms supported + break; + case EthernetContainer10: + default: + LOG.warn("Unassigned or not expected lp in model {}", lpName); + } + } + + @Override + public List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(ONFLayerProtocolName lpName, Lp lp) { + switch (lpName) { + case MWAirInterface: + return readTheHistoricalPerformanceDataOfMwAirInterfacePac(lp); + + case EthernetContainer12: + return readTheHistoricalPerformanceDataOfEthernetContainer(lp); + + case EthernetContainer10: + case EthernetPhysical: + case Ethernet: + case TDMContainer: + case Structure: + case Unknown: + LOG.debug("Do not read HistoricalPM data for {} {}", lpName, lp.getUuid().getValue()); + break; + } + return new ArrayList<>(); + } + + @Override + public Class<?> getClassForLtpExtension(QName qName) { + Class<?> res = null; + if (qName.equals(MwAirInterfacePac.QNAME)) { + res = MwAirInterfacePac.class; + } else if (qName.equals(MwAirInterfaceDiversityPac.QNAME)) { + res = MwAirInterfaceDiversityPac.class; + } else if (qName.equals(MwPureEthernetStructurePac.QNAME)) { + res = MwPureEthernetStructurePac.class; + } else if (qName.equals(MwHybridMwStructurePac.QNAME)) { + res = MwHybridMwStructurePac.class; + } else if (qName.equals(MwEthernetContainerPac.QNAME)) { + res = MwEthernetContainerPac.class; + } else if (qName.equals(MwTdmContainerPac.QNAME)) { + res = MwTdmContainerPac.class; + } + LOG.info("Found QName {} mapped to {}", String.valueOf(qName), String.valueOf(res)); + return res; + } + + /*----------------------------------------------------------------------------- + * Reading problems for specific interface pacs + */ + + /** + * Read problems of specific interfaces + * + * @param uuId Universal Id String of the interface + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfacePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfacePac> clazzPac = MwAirInterfacePac.class; + // final Class<MwAirInterfacePacKey> clazzPacKey = MwAirInterfacePacKey.class; + // final Class<AirInterfaceCurrentProblems> clazzProblems = + // AirInterfaceCurrentProblems.class; + // final Class<AirInterfaceCurrentProblemTypeG> clazzProblem = + // AirInterfaceCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceCurrentProblems> mwAirInterfaceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(interfacePacUuid)) + .child(AirInterfaceCurrentProblems.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceIID); + + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemList", interfacePacUuid); + } else { + for (AirInterfaceCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwEthernetContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwEthernetContainerPac> clazzPac = MwEthernetContainerPac.class; + // final Class<MwEthernetContainerPacKey> clazzPacKey = + // MwEthernetContainerPacKey.class; + // final Class<EthernetContainerCurrentProblems> clazzProblems = + // EthernetContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<EthernetContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(interfacePacUuid)) + .child(EthernetContainerCurrentProblems.class).build(); + + EthernetContainerCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no EthernetContainerCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (ContainerCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfaceDiversityPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfaceDiversityPac> clazzPac = MwAirInterfaceDiversityPac.class; + // final Class<MwAirInterfaceDiversityPacKey> clazzPacKey = + // MwAirInterfaceDiversityPacKey.class; + final Class<AirInterfaceDiversityCurrentProblems> clazzProblems = AirInterfaceDiversityCurrentProblems.class; + // final Class<AirInterfaceDiversityCurrentProblemTypeG> clazzProblem = + // AirInterfaceDiversityCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<AirInterfaceDiversityCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwAirInterfaceDiversityPacKey(interfacePacUuid)).child(clazzProblems).build(); + + AirInterfaceDiversityCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceDiversityCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemList", interfacePacUuid); + } else { + for (AirInterfaceDiversityCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwPureEthernetStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwPureEthernetStructurePac> clazzPac = MwPureEthernetStructurePac.class; + // final Class<MwPureEthernetStructurePacKey> clazzPacKey = + // MwPureEthernetStructurePacKey.class; + final Class<PureEthernetStructureCurrentProblems> clazzProblems = PureEthernetStructureCurrentProblems.class; + // final Class<StructureCurrentProblemTypeG> clazzProblem = + // StructureCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<PureEthernetStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwPureEthernetStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + PureEthernetStructureCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no PureEthernetStructureCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwHybridMwStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwHybridMwStructurePac> clazzPac = MwHybridMwStructurePac.class; + // final Class<MwHybridMwStructurePacKey> clazzPacKey = + // MwHybridMwStructurePacKey.class; + final Class<HybridMwStructureCurrentProblems> clazzProblems = HybridMwStructureCurrentProblems.class; + // final Class<HybridMwStructureCurrentProblemsG> clazzProblem = + // HybridMwStructureCurrentProblemsG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<HybridMwStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwHybridMwStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + HybridMwStructureCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no HybridMwStructureCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces. TODO Goal for future implementation + * without usage of explicit new. Key is generated by newInstance() function + * here to verify this approach. + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + * @throws SecurityException + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private List<ProblemNotificationXml> readTheFaultsOfMwTdmContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwTdmContainerPac> clazzPac = MwTdmContainerPac.class; + final Class<MwTdmContainerPacKey> clazzPacKey = MwTdmContainerPacKey.class; + final Class<TdmContainerCurrentProblems> clazzProblems = TdmContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + try { + // -- Specific part 1 + Constructor<MwTdmContainerPacKey> cons = clazzPacKey.getConstructor(UniversalId.class); // Avoid new() + InstanceIdentifier<TdmContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, cons.newInstance(interfacePacUuid)).child(clazzProblems).build(); + + // -- Specific part 2 + TdmContainerCurrentProblems problems = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no TdmContainerCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + // -- Specific part 3 + for (ContainerCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOG.warn("Could not reade instance of MwTdmContainerPacKey: ", e); + } + return resultList; + } + + /*----------------------------------------------------------------------------- + * Performance related data + */ + + /** + * PM MwAirInterfacePac + * + * @param lp + * @return + */ + private List<ExtendedAirInterfaceHistoricalPerformanceType1211> readTheHistoricalPerformanceDataOfMwAirInterfacePac( + Lp lp) { + + String uuId = lp.getUuid().getValue(); + + List<ExtendedAirInterfaceHistoricalPerformanceType1211> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} MWAirInterfacePac: {}", coreData.getMountpoint(), uuId); + // ---- + UniversalId mwAirInterfacePacuuId = new UniversalId(uuId); + // Step 2.1: construct data and the relative iid + InstanceIdentifier<AirInterfaceConfiguration> mwAirInterfaceConfigurationIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceConfiguration.class).build(); + AirInterfaceConfiguration airConfiguration = genericTransactionUtil.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceConfigurationIID); + + if (airConfiguration == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceConfiguration", mwAirInterfacePacuuId); + + } else { + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceHistoricalPerformances> mwAirInterfaceHistoricalPerformanceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceHistoricalPerformances airHistoricalPerformanceData = genericTransactionUtil.readData( + coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, mwAirInterfaceHistoricalPerformanceIID); + + if (airHistoricalPerformanceData == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceHistoricalPerformances", + mwAirInterfacePacuuId); + } else { + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.air._interface.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.air._interface.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = airHistoricalPerformanceData + .getHistoricalPerformanceDataList(); + LOG.debug("DBRead MWAirInterfacePac Id {} Records intermediate: {}", mwAirInterfacePacuuId, + airHistPMList.size()); + if (airHistPMList != null) { + for (AirInterfaceHistoricalPerformanceTypeG pmRecord : airHistoricalPerformanceData + .getHistoricalPerformanceDataList()) { + resultList.add(new ExtendedAirInterfaceHistoricalPerformanceType1211(pmRecord, airConfiguration)); + } + } + } + } + LOG.debug("DBRead MWAirInterfacePac Id {} Records result: {}", mwAirInterfacePacuuId, resultList.size()); + return resultList; + } + + private List<ContainerHistoricalPerformanceTypeG> readTheHistoricalPerformanceDataOfEthernetContainer(Lp lp) { + + final String myName = "MWEthernetContainerPac"; + String uuId = lp.getUuid().getValue(); + + List<ContainerHistoricalPerformanceTypeG> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} : {}", coreData.getMountpoint(), myName, uuId); + // ---- + UniversalId ethContainerPacuuId = new UniversalId(uuId); + // Step 2.2: construct data and the relative iid + InstanceIdentifier<EthernetContainerHistoricalPerformances> ethContainerIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(ethContainerPacuuId)) + .child(EthernetContainerHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + EthernetContainerHistoricalPerformances ethContainerHistoricalPerformanceData = genericTransactionUtil + .readData(coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, ethContainerIID); + + if (ethContainerHistoricalPerformanceData == null) { + LOG.debug("DBRead {} Id {} no HistoricalPerformances", myName, ethContainerPacuuId); + } else { + // import + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.ethernet.container.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ethernet.container.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = ethContainerHistoricalPerformanceData + .getHistoricalPerformanceDataList(); + LOG.debug("DBRead {} Id {} Records intermediate: {}", myName, ethContainerPacuuId, airHistPMList.size()); + if (airHistPMList != null) { + for (ContainerHistoricalPerformanceTypeG pmRecord : airHistPMList) { + resultList.add(pmRecord); + } + } + } + LOG.debug("DBRead {} Id {} Records result: {}", myName, ethContainerPacuuId, resultList.size()); + return resultList; + } + + @Override + public void onObjectCreationNotification(ObjectCreationNotification notification) { + LOG.debug("Got event of type :: {}", ObjectCreationNotification.class.getSimpleName()); + + ObjectCreationNotificationXml notificationXml = new ObjectCreationNotificationXml(coreData.getMountpoint(), + notification.getCounter(), + InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue()); + microwaveModelListener.onObjectCreationNotification(notificationXml); + } + + @Override + public void onObjectDeletionNotification(ObjectDeletionNotification notification) { + LOG.debug("Got event of type :: {}", ObjectDeletionNotification.class.getSimpleName()); + + ObjectDeletionNotificationXml notificationXml = new ObjectDeletionNotificationXml(coreData.getMountpoint(), + notification.getCounter(), + InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue() + ); + microwaveModelListener.onObjectDeletionNotification(notificationXml); + } + + @Override + public void onProblemNotification(ProblemNotification notification) { + + LOG.debug("Got event of type :: {}", ProblemNotification.class.getSimpleName()); + + ProblemNotificationXml notificationXml = new ProblemNotificationXml(coreData.getMountpoint(), notification.getObjectIdRef().getValue(), + notification.getProblem(), InternalSeverity.valueOf(notification.getSeverity()), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp())); + + microwaveModelListener.onProblemNotification(notificationXml); + } + + @Override + public void onAttributeValueChangedNotification(AttributeValueChangedNotification notification) { + LOG.debug("Got event of type :: {}", AttributeValueChangedNotification.class.getSimpleName()); + + AttributeValueChangedNotificationXml notificationXml = new AttributeValueChangedNotificationXml(coreData.getMountpoint(), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue(), notification.getAttributeName(), notification.getNewValue()); + + microwaveModelListener.onAttributeValueChangedNotification(notificationXml); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev181010.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev181010.java new file mode 100644 index 000000000..627b64e6d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperMicrowaveModelRev181010.java @@ -0,0 +1,606 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; + + + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.NetworkElementCoreData; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType1211p; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ONFLayerProtocolName; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.UniversalId; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceDiversityCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AttributeValueChangedNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ContainerCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ContainerHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MicrowaveModelListener; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwAirInterfaceDiversityPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwAirInterfaceDiversityPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwAirInterfacePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwAirInterfacePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwEthernetContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwEthernetContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwHybridMwStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwHybridMwStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwPureEthernetStructurePac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwPureEthernetStructurePacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwTdmContainerPac; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.MwTdmContainerPacKey; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ObjectCreationNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ObjectDeletionNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ProblemNotification; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.StructureCurrentProblemTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.air._interface.diversity.pac.AirInterfaceDiversityCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.air._interface.pac.AirInterfaceConfiguration; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.air._interface.pac.AirInterfaceCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.air._interface.pac.AirInterfaceHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.ethernet.container.pac.EthernetContainerCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.ethernet.container.pac.EthernetContainerHistoricalPerformances; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.hybrid.mw.structure.pac.HybridMwStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.pure.ethernet.structure.pac.PureEthernetStructureCurrentProblems; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.mw.tdm.container.pac.TdmContainerCurrentProblems; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.NotificationListener; +import org.opendaylight.yangtools.yang.common.QName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class WrapperMicrowaveModelRev181010 implements OnfMicrowaveModel, MicrowaveModelListener { + + private static final Logger LOG = LoggerFactory.getLogger(WrapperMicrowaveModelRev181010.class); + + public static final QName QNAME = MwAirInterfacePac.QNAME; + + + private NetworkElementCoreData coreData; + + private OnfMicrowaveModelNotification microwaveModelListener; + private final TransactionUtils genericTransactionUtils; + + /*----------------------------------------------------------------------------- + * Setter/Getter + */ + + /** + * @param acessor + */ + public WrapperMicrowaveModelRev181010(INetconfAcessor acessor) { + genericTransactionUtils = acessor.getTransactionUtils(); + } + + @Override + public void setCoreData(NetworkElementCoreData coreData) { + this.coreData = coreData; + } + + public NetworkElementCoreData getCoreData() { + return coreData; + } + + @Override + public void setOnfMicrowaveModelListener(OnfMicrowaveModelNotification microwaveModelListener) { + this.microwaveModelListener = microwaveModelListener; + } + + @SuppressWarnings("unchecked") + @Override + public <T extends NotificationListener> T getNotificationListener() { + return (T) this; + } + + /*----------------------------------------------------------------------------- + * Interfacefunctions + */ + + @Override + public void readTheFaultsOfMicrowaveModel(ONFLayerProtocolName lpName, Class<?> lpClass, UniversalId uuid, + List<ProblemNotificationXml> resultList) { + + switch (lpName) { + case MWAirInterface: + readTheFaultsOfMwAirInterfacePac(uuid, resultList); + break; + + case EthernetContainer12: + readTheFaultsOfMwEthernetContainerPac(uuid, resultList); + break; + + case TDMContainer: + readTheFaultsOfMwTdmContainerPac(uuid, resultList); + break; + + case Structure: + if (lpClass == MwHybridMwStructurePac.class) { + readTheFaultsOfMwHybridMwStructurePac(uuid, resultList); + + } else if (lpClass == MwAirInterfaceDiversityPac.class) { + readTheFaultsOfMwAirInterfaceDiversityPac(uuid, resultList); + + } else if (lpClass == MwPureEthernetStructurePac.class) { + readTheFaultsOfMwPureEthernetStructurePac(uuid, resultList); + + } else { + LOG.warn("Unassigned lp model {} class {}", lpName, lpClass); + } + break; + case Ethernet: + // No alarms supported + break; + case EthernetContainer10: + default: + LOG.warn("Unassigned or not expected lp in model {}", lpName); + } + } + + @Override + public List<? extends OtnHistoryDataG> readTheHistoricalPerformanceData(ONFLayerProtocolName lpName, Lp lp) { + switch (lpName) { + case MWAirInterface: + return readTheHistoricalPerformanceDataOfMwAirInterfacePac(lp); + + case EthernetContainer12: + return readTheHistoricalPerformanceDataOfEthernetContainer(lp); + + case EthernetContainer10: + case EthernetPhysical: + case Ethernet: + case TDMContainer: + case Structure: + case Unknown: + LOG.debug("Do not read HistoricalPM data for {} {}", lpName, lp.getUuid().getValue()); + break; + } + return new ArrayList<>(); + } + + @Override + public Class<?> getClassForLtpExtension(QName qName) { + Class<?> res = null; + if (qName.equals(MwAirInterfacePac.QNAME)) { + res = MwAirInterfacePac.class; + } else if (qName.equals(MwAirInterfaceDiversityPac.QNAME)) { + res = MwAirInterfaceDiversityPac.class; + } else if (qName.equals(MwPureEthernetStructurePac.QNAME)) { + res = MwPureEthernetStructurePac.class; + } else if (qName.equals(MwHybridMwStructurePac.QNAME)) { + res = MwHybridMwStructurePac.class; + } else if (qName.equals(MwEthernetContainerPac.QNAME)) { + res = MwEthernetContainerPac.class; + } else if (qName.equals(MwTdmContainerPac.QNAME)) { + res = MwTdmContainerPac.class; + } + LOG.info("Found QName {} mapped to {}", String.valueOf(qName), String.valueOf(res)); + return res; + } + + /*----------------------------------------------------------------------------- + * Reading problems for specific interface pacs + */ + + /** + * Read problems of specific interfaces + * + * @param uuId Universal Id String of the interface + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfacePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfacePac> clazzPac = MwAirInterfacePac.class; + // final Class<MwAirInterfacePacKey> clazzPacKey = MwAirInterfacePacKey.class; + // final Class<AirInterfaceCurrentProblems> clazzProblems = + // AirInterfaceCurrentProblems.class; + // final Class<AirInterfaceCurrentProblemTypeG> clazzProblem = + // AirInterfaceCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceCurrentProblems> mwAirInterfaceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(interfacePacUuid)) + .child(AirInterfaceCurrentProblems.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceIID); + + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemList", interfacePacUuid); + } else { + for (AirInterfaceCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwEthernetContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwEthernetContainerPac> clazzPac = MwEthernetContainerPac.class; + // final Class<MwEthernetContainerPacKey> clazzPacKey = + // MwEthernetContainerPacKey.class; + // final Class<EthernetContainerCurrentProblems> clazzProblems = + // EthernetContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<EthernetContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(interfacePacUuid)) + .child(EthernetContainerCurrentProblems.class).build(); + + EthernetContainerCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no EthernetContainerCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (ContainerCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwAirInterfaceDiversityPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwAirInterfaceDiversityPac> clazzPac = MwAirInterfaceDiversityPac.class; + // final Class<MwAirInterfaceDiversityPacKey> clazzPacKey = + // MwAirInterfaceDiversityPacKey.class; + final Class<AirInterfaceDiversityCurrentProblems> clazzProblems = AirInterfaceDiversityCurrentProblems.class; + // final Class<AirInterfaceDiversityCurrentProblemTypeG> clazzProblem = + // AirInterfaceDiversityCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<AirInterfaceDiversityCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwAirInterfaceDiversityPacKey(interfacePacUuid)).child(clazzProblems).build(); + + AirInterfaceDiversityCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no AirInterfaceDiversityCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemList", interfacePacUuid); + } else { + for (AirInterfaceDiversityCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwPureEthernetStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwPureEthernetStructurePac> clazzPac = MwPureEthernetStructurePac.class; + // final Class<MwPureEthernetStructurePacKey> clazzPacKey = + // MwPureEthernetStructurePacKey.class; + final Class<PureEthernetStructureCurrentProblems> clazzProblems = PureEthernetStructureCurrentProblems.class; + // final Class<StructureCurrentProblemTypeG> clazzProblem = + // StructureCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<PureEthernetStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwPureEthernetStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + PureEthernetStructureCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no PureEthernetStructureCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + */ + private List<ProblemNotificationXml> readTheFaultsOfMwHybridMwStructurePac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwHybridMwStructurePac> clazzPac = MwHybridMwStructurePac.class; + // final Class<MwHybridMwStructurePacKey> clazzPacKey = + // MwHybridMwStructurePacKey.class; + final Class<HybridMwStructureCurrentProblems> clazzProblems = HybridMwStructureCurrentProblems.class; + // final Class<HybridMwStructureCurrentProblemsG> clazzProblem = + // HybridMwStructureCurrentProblemsG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + InstanceIdentifier<HybridMwStructureCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, new MwHybridMwStructurePacKey(interfacePacUuid)).child(clazzProblems).build(); + + HybridMwStructureCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no HybridMwStructureCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + for (StructureCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + return resultList; + } + + /** + * Read problems of specific interfaces. TODO Goal for future implementation + * without usage of explicit new. Key is generated by newInstance() function + * here to verify this approach. + * + * @param uuId Universal index of Interfacepac + * @return number of alarms + * @throws SecurityException + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private List<ProblemNotificationXml> readTheFaultsOfMwTdmContainerPac(UniversalId interfacePacUuid, + List<ProblemNotificationXml> resultList) { + + final Class<MwTdmContainerPac> clazzPac = MwTdmContainerPac.class; + final Class<MwTdmContainerPacKey> clazzPacKey = MwTdmContainerPacKey.class; + final Class<TdmContainerCurrentProblems> clazzProblems = TdmContainerCurrentProblems.class; + // final Class<ContainerCurrentProblemTypeG> clazzProblem = + // ContainerCurrentProblemTypeG.class; + + LOG.info("DBRead Get problems for class {} from mountpoint {} for uuid {}", clazzPac.getSimpleName(), + coreData.getMountpoint(), interfacePacUuid.getValue()); + + try { + // -- Specific part 1 + Constructor<MwTdmContainerPacKey> cons = clazzPacKey.getConstructor(UniversalId.class); // Avoid new() + InstanceIdentifier<TdmContainerCurrentProblems> mwEthInterfaceIID = InstanceIdentifier + .builder(clazzPac, cons.newInstance(interfacePacUuid)).child(clazzProblems).build(); + + // -- Specific part 2 + TdmContainerCurrentProblems problems = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwEthInterfaceIID); + if (problems == null) { + LOG.debug("DBRead Id {} no TdmContainerCurrentProblems", interfacePacUuid); + } else if (problems.getCurrentProblemList() == null) { + LOG.debug("DBRead Id {} empty CurrentProblemsList", interfacePacUuid); + } else { + // -- Specific part 3 + for (ContainerCurrentProblemTypeG problem : problems.getCurrentProblemList()) { + resultList.add(new ProblemNotificationXml(coreData.getMountpoint(), interfacePacUuid.getValue(), + problem.getProblemName(), InternalSeverity.valueOf(problem.getProblemSeverity()), + problem.getSequenceNumber(), + InternalDateAndTime.valueOf(problem.getTimeStamp()))); + } + } + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOG.warn("Could not reade instance of MwTdmContainerPacKey: ", e); + } + return resultList; + } + + /*----------------------------------------------------------------------------- + * Performance related data + */ + + /** + * PM MwAirInterfacePac + * + * @param lp + * @return + */ + private List<ExtendedAirInterfaceHistoricalPerformanceType1211p> readTheHistoricalPerformanceDataOfMwAirInterfacePac( + Lp lp) { + + String uuId = lp.getUuid().getValue(); + + List<ExtendedAirInterfaceHistoricalPerformanceType1211p> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} MWAirInterfacePac: {}", coreData.getMountpoint(), uuId); + // ---- + UniversalId mwAirInterfacePacuuId = new UniversalId(uuId); + // Step 2.1: construct data and the relative iid + InstanceIdentifier<AirInterfaceConfiguration> mwAirInterfaceConfigurationIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceConfiguration.class).build(); + AirInterfaceConfiguration airConfiguration = genericTransactionUtils.readData(coreData.getDataBroker(), + LogicalDatastoreType.OPERATIONAL, mwAirInterfaceConfigurationIID); + + if (airConfiguration == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceConfiguration", mwAirInterfacePacuuId); + + } else { + // Step 2.2: construct data and the relative iid + InstanceIdentifier<AirInterfaceHistoricalPerformances> mwAirInterfaceHistoricalPerformanceIID = InstanceIdentifier + .builder(MwAirInterfacePac.class, new MwAirInterfacePacKey(mwAirInterfacePacuuId)) + .child(AirInterfaceHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + AirInterfaceHistoricalPerformances airHistoricalPerformanceData = genericTransactionUtils.readData( + coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, mwAirInterfaceHistoricalPerformanceIID); + + if (airHistoricalPerformanceData == null) { + LOG.debug("DBRead MWAirInterfacePac Id {} no AirInterfaceHistoricalPerformances", + mwAirInterfacePacuuId); + } else { + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.air._interface.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.air._interface.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = airHistoricalPerformanceData + .getHistoricalPerformanceDataList(); + LOG.debug("DBRead MWAirInterfacePac Id {} Records intermediate: {}", mwAirInterfacePacuuId, + airHistPMList.size()); + if (airHistPMList != null) { + for (AirInterfaceHistoricalPerformanceTypeG pmRecord : airHistoricalPerformanceData + .getHistoricalPerformanceDataList()) { + resultList.add(new ExtendedAirInterfaceHistoricalPerformanceType1211p(pmRecord, airConfiguration)); + } + } + } + } + LOG.debug("DBRead MWAirInterfacePac Id {} Records result: {}", mwAirInterfacePacuuId, resultList.size()); + return resultList; + } + + private List<ContainerHistoricalPerformanceTypeG> readTheHistoricalPerformanceDataOfEthernetContainer(Lp lp) { + + final String myName = "MWEthernetContainerPac"; + String uuId = lp.getUuid().getValue(); + + List<ContainerHistoricalPerformanceTypeG> resultList = new ArrayList<>(); + LOG.debug("DBRead Get {} : {}", coreData.getMountpoint(), myName, uuId); + // ---- + UniversalId ethContainerPacuuId = new UniversalId(uuId); + // Step 2.2: construct data and the relative iid + InstanceIdentifier<EthernetContainerHistoricalPerformances> ethContainerIID = InstanceIdentifier + .builder(MwEthernetContainerPac.class, new MwEthernetContainerPacKey(ethContainerPacuuId)) + .child(EthernetContainerHistoricalPerformances.class).build(); + + // Step 2.3: read to the config data store + EthernetContainerHistoricalPerformances ethContainerHistoricalPerformanceData = genericTransactionUtils + .readData(coreData.getDataBroker(), LogicalDatastoreType.OPERATIONAL, ethContainerIID); + + if (ethContainerHistoricalPerformanceData == null) { + LOG.debug("DBRead {} Id {} no HistoricalPerformances", myName, ethContainerPacuuId); + } else { + // import + // org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170320.ethernet.container.historical.performances.g.HistoricalPerformanceDataList + List<org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ethernet.container.historical.performances.g.HistoricalPerformanceDataList> airHistPMList = ethContainerHistoricalPerformanceData + .getHistoricalPerformanceDataList(); + LOG.debug("DBRead {} Id {} Records intermediate: {}", myName, ethContainerPacuuId, airHistPMList.size()); + if (airHistPMList != null) { + for (ContainerHistoricalPerformanceTypeG pmRecord : airHistPMList) { + resultList.add(pmRecord); + } + } + } + LOG.debug("DBRead {} Id {} Records result: {}", myName, ethContainerPacuuId, resultList.size()); + return resultList; + } + + @Override + public void onObjectCreationNotification(ObjectCreationNotification notification) { + LOG.debug("Got event of type :: {}", ObjectCreationNotification.class.getSimpleName()); + + ObjectCreationNotificationXml notificationXml = new ObjectCreationNotificationXml(coreData.getMountpoint(), + notification.getCounter(), + InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue()); + microwaveModelListener.onObjectCreationNotification(notificationXml); + } + + @Override + public void onObjectDeletionNotification(ObjectDeletionNotification notification) { + LOG.debug("Got event of type :: {}", ObjectDeletionNotification.class.getSimpleName()); + + ObjectDeletionNotificationXml notificationXml = new ObjectDeletionNotificationXml(coreData.getMountpoint(), + notification.getCounter(), + InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue() + ); + microwaveModelListener.onObjectDeletionNotification(notificationXml); + } + + @Override + public void onProblemNotification(ProblemNotification notification) { + + LOG.debug("Got event of type :: {}", ProblemNotification.class.getSimpleName()); + + ProblemNotificationXml notificationXml = new ProblemNotificationXml(coreData.getMountpoint(), notification.getObjectIdRef().getValue(), + notification.getProblem(), InternalSeverity.valueOf(notification.getSeverity()), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp())); + + microwaveModelListener.onProblemNotification(notificationXml); + } + + @Override + public void onAttributeValueChangedNotification(AttributeValueChangedNotification notification) { + LOG.debug("Got event of type :: {}", AttributeValueChangedNotification.class.getSimpleName()); + + AttributeValueChangedNotificationXml notificationXml = new AttributeValueChangedNotificationXml(coreData.getMountpoint(), + notification.getCounter(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue(), notification.getAttributeName(), notification.getNewValue()); + + microwaveModelListener.onAttributeValueChangedNotification(notificationXml); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperPTPModelRev170208.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperPTPModelRev170208.java new file mode 100644 index 000000000..172db1198 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/base/onfcore/wrapperc/WrapperPTPModelRev170208.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc; +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ + +import java.util.List; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.Capabilities; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ptp.dataset.rev170208.InstanceList; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ptp.dataset.rev170208.InstanceListKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ptp.dataset.rev170208.instance.list.PortDsList; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ptp.dataset.rev170208.port.ds.entry.PortIdentity; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Reading PTP specific information from networkelement and creating log-trace output. + * + * @author herbert + */ +public class WrapperPTPModelRev170208 { + + private static final Logger LOG = LoggerFactory.getLogger(WrapperPTPModelRev170208.class); + + protected static final InstanceIdentifier<InstanceList> PTPINSTANCES_IID = InstanceIdentifier + .builder(InstanceList.class, new InstanceListKey(1)).build(); + + /** + * Query synchronization information out of NE + */ + + public static void initSynchronizationExtension(INetconfAcessor acessor) { + + String mountPointNodeName = acessor.getNodeId().getValue(); + Capabilities capabilities = acessor.getCapabilites(); + try { + if (!capabilities.isSupportingNamespaceAndRevision(InstanceList.QNAME)) { + LOG.debug("Mountpoint {} does not support PTP", mountPointNodeName); + } else { + StringBuffer sb = new StringBuffer(); + sb.append("NE "); + sb.append(mountPointNodeName); + sb.append(" does support synchronisation.\n"); + InstanceList ptpInstance = readPTPClockInstances(acessor); + if (ptpInstance != null) { + List<PortDsList> dsList = ptpInstance.getPortDsList(); + if (dsList != null) { + int t = 0; + for (PortDsList portDs : dsList) { + PortIdentity portId = portDs.getPortIdentity(); + if (portId != null) { + sb.append("Port["); + sb.append(portId.getPortNumber()); + sb.append("]{ ClockId: "); + sb.append(portId.getClockIdentity()); + sb.append(", Portstate: "); + sb.append(portDs.getPortState()); + sb.append("}, "); + } else { + sb.append("Incomplete port #" + t + ", "); + } + t++; + } + } else { + sb.append("dsList contains null"); + } + } else { + sb.append("ptpInstance equals null"); + } + LOG.trace(sb.toString()); + } + } catch (Exception e) { + LOG.info("Inconsistent synchronisation structure: " + e.getMessage()); + } + } + + @Nullable + private static InstanceList readPTPClockInstances(INetconfAcessor acessor) { + return acessor.getTransactionUtils().readData(acessor.getDataBroker(), LogicalDatastoreType.OPERATIONAL, + PTPINSTANCES_IID); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderImpl.java new file mode 100644 index 000000000..88854dbd1 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderImpl.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.common.HtAssert; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.ProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.NetconfEventListenerHandler12; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.MaintenanceService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DcaeForwarderImpl implements DcaeForwarderInternal, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfEventListenerHandler12.class); + + private final @Nullable ProviderClient aotsmClient; + private final ProviderClient dcaeProvider; + private final MaintenanceService maintenanceService; + + public DcaeForwarderImpl(@Nullable ProviderClient aotsmClient, @Nullable ProviderClient dcaeProvider, + @NonNull MaintenanceService maintenanceService) { + super(); + + HtAssert.nonnull(maintenanceService); + this.aotsmClient = aotsmClient; + this.dcaeProvider = dcaeProvider; + this.maintenanceService = maintenanceService; + } + + @Override + @SuppressWarnings("null") + public void sendProblemNotificationUsingMaintenanceFilter(String nodeId, ProblemNotificationXml notificationXml) { + if (!this.maintenanceService.isONFObjectInMaintenance(nodeId, notificationXml.getObjectId(), + notificationXml.getProblem())) { + if (dcaeProvider != null) { + this.dcaeProvider.sendProblemNotification(nodeId, notificationXml); + } + if (this.aotsmClient != null) { + this.aotsmClient.sendProblemNotification(nodeId, notificationXml); + } + } else { + LOG.debug("Notification will not be sent to external services. Device " + nodeId + + " is in maintenance mode"); + } + } + + @Override + public void sendProblemNotification(String nodeId, ProblemNotificationXml notificationXml) { + //to prevent push alarms on reconnect + //=> only pushed alarms are forwared to dcae + //dcaeProvider.sendProblemNotification(nodeName, notificationXml); + if(aotsmClient!=null) { + aotsmClient.sendProblemNotification(nodeId, notificationXml); + } + + } + + @Override + public void close() throws Exception { + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderInternal.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderInternal.java new file mode 100644 index 000000000..68f1ac369 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeForwarderInternal.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DcaeForwarder; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; + +/** + * @author herbert + * + */ +public interface DcaeForwarderInternal extends DcaeForwarder { + + /** + * @param oWNKEYNAME + * @param notificationXml + */ + void sendProblemNotificationUsingMaintenanceFilter(String oWNKEYNAME, ProblemNotificationXml notificationXml); + + /** + * @param nodeName + * @param notificationXml + */ + void sendProblemNotification(String nodeName, ProblemNotificationXml notificationXml); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeMessages.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeMessages.java new file mode 100644 index 000000000..e82e8e965 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeMessages.java @@ -0,0 +1,348 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + ecompProvider.sendProblemNotification(ownKeyName, notificationXml); + * ECOMP Messages are generated an send to destination + * + * @author herbert + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Optional; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.InventoryProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.legacy.InventoryInformation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DcaeMessages { + + private static final Logger LOG = LoggerFactory.getLogger(DcaeSenderImpl.class); + + private static final String DCAE_NORMAL = "NORMAL"; + private static final String DCAE_MINOR = "MINOR"; + private static final String DCAE_WARNING = "WARNING"; + private static final String DCAE_CRITICAL = "CRITICAL"; + private static final String DCAE_MAJOR = "MAJOR"; + + private static final String eventNamePrefix = "fault_Microwave_Radio_Alarms"; + private static final String eventType = "Microwave_Radio_Alarms"; + private static final String eventSourceType = "Microwave_Radio"; + + private static final String charset = "UTF-8"; + + private static final HostnameVerifier allHostsValid = (hostname, session) -> true; + + private static final String CONTENT_TYPE_APPJSON = "application/json"; + + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + //Configurable parameters + private final DcaeSender dcaeSender; + private final int heartbeatIntervallSeconds; + private final String entityName; + private final DeviceManagerImpl deviceManager; + + //Variables + private int heartbeatsequence = 0; + + public DcaeMessages(DcaeSender ecompSender, String entityName, Integer heartbeatIntervallSeconds, DeviceManagerImpl deviceManager) { + this.dcaeSender = ecompSender; + this.entityName = entityName; + this.deviceManager = deviceManager; + this.heartbeatIntervallSeconds = heartbeatIntervallSeconds; + } + + /** + * Create a heartbeat message. + * @return Result string with answer from server + */ + public String postHeartBeat() { + String epochTimeMicrosecondsString = getEpochTimeMicroseconds(); + String body = assembleHeartbeatFromTemplate(null, + epochTimeMicrosecondsString, + heartbeatsequence++, + NETCONFTIME_CONVERTER.getTimeStampAsNetconfString()).toString(); + return dcaeSender.sendDcaePost( body); + } + + /** + * ONF 1.2 Problem Notification + * @param mountPointName self-explaining + * @param notification Notification input + * @return String with answer + */ + + public String postNotification(String mountPointName, ProblemNotificationXml notification) { + + String problemName = notification.getProblem(); + String sequence = notification.getCounter(); + String objId = notification.getObjectId(); + String severity = convert( notification.getSeverity()); + String timeStamp = convert( notification.getTimeStamp() ); + + String body = assembleEventNotificationFromTemplate(null, + timeStamp, sequence, + mountPointName, objId, problemName, severity, notification.getTimeStamp() ).toString(); + + return dcaeSender.sendDcaePost( body); + } + + /** + * Setup a connection to URL with authorisation header + * @param url e.g. "https://plan.fritz.box:9092/ux/#" or " + * @param basicAuth authorisation header like "Basic SGVyYmVydDpIZXJiZXJ0" + * @param insertContentHeader + * @return Null in case of error or the URLConnection + * @throws IOException + * @throws MalformedURLException + */ + static @Nullable HttpURLConnection openConnection( URL url, String basicAuth, boolean insertContentHeader, @Nullable SSLContext sc) throws MalformedURLException, IOException { + + //Prepare the connection + HttpURLConnection newHttpConnection = null; + { + URLConnection newConnection = url.openConnection(); + if (newConnection instanceof HttpURLConnection) { + LOG.debug("Setup connection to {} ", url.toString()); + + newHttpConnection = (HttpURLConnection)newConnection; + + newHttpConnection.setDoOutput(true); // Triggers POST. + newHttpConnection.setRequestProperty("Accept-Charset", charset); + if (basicAuth != null) { + newHttpConnection.setRequestProperty("Authorization", basicAuth); + } + if (insertContentHeader) { + newHttpConnection.setRequestProperty("Content-Type", CONTENT_TYPE_APPJSON); + } + + if (newHttpConnection instanceof HttpsURLConnection) { + LOG.debug("SSL connection setup with trust all."); + HttpsURLConnection newHttpsConnection = (HttpsURLConnection)newHttpConnection; + if (sc != null) { + newHttpsConnection.setSSLSocketFactory(sc.getSocketFactory()); + } else { + LOG.warn("No SSL Contect available"); + } + newHttpsConnection.setHostnameVerifier(allHostsValid); + } + } else { + LOG.warn("URL not a HTTP protocol: {}", url); + } + } + return newHttpConnection; + } + + /* ----------------- + * Private function for message creation and with templates + */ + + /** + * Get actual microseconds + * @return String + */ + private String getEpochTimeMicroseconds() { + long microseconds = System.nanoTime() / 1000; + return String.valueOf(microseconds); + } + + /** + * Assemble heartbeat message + * @param sb StringBuffer to be used or null to allocate + * @param epochTimeMicrosecondsString Text with time stamp + * @param sequence integer sequence number + * @param eventTimeValueNetconfFormatString like this: 2018-05-14T05:32:17.292Z + * @return StringBuffer with result + */ + private StringBuffer assembleHeartbeatFromTemplate( + StringBuffer sb, + String epochTimeMicrosecondsString, + int sequence, + String eventTimeValueNetconfFormatString) { + + if (sb == null) { + sb = new StringBuffer(); + } + sb.append("{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"heartbeat\",\n" + + " \"eventId\": \"testpattern-ab305d54-85b4-a31b-7db2-fb6b9e546015\",\n" + + " \"eventName\": \"heartbeat_Controller\",\n" + + " \"eventType\": \"Controller\",\n" + + " \"priority\": \"Low\",\n" + + " \"reportingEntityId\": \"\",\n" + + " \"reportingEntityName\": \""+entityName+"\",\n" + + " \"sequence\": "+String.valueOf(sequence)+",\n" + + " \"sourceId\": \"\",\n" + + " \"sourceName\": \""+entityName+"\",\n" + + " \"startEpochMicrosec\": "+epochTimeMicrosecondsString+",\n" + + " \"lastEpochMicrosec\": "+epochTimeMicrosecondsString+",\n" + + " \"version\": 3.0\n" + + " },\n" + + " \"heartbeatFields\": {\n" + + " \"additionalFields\": [\n" + + " {\n" + + " \"name\": \"eventTime\",\n" + + " \"value\": \""+eventTimeValueNetconfFormatString+"\"\n" + + " }\n" + + " ],\n" + + " \"heartbeatFieldsVersion\": 1.0,\n" + + " \"heartbeatInterval\": "+heartbeatIntervallSeconds+"\n" + + " }\n" + + " }\n" + + "}\n" + ); + + return sb; + } + + /** + * Assemble notification message + * @param sb StringBuffer to be used or null to allocate + * @param epochTimeMicrosecondsString Text with time stamp + * @param sequence integer sequence number + * @param mountpointName + * @param objId + * @param problemName + * @param severity + * @return StringBuffer with result + */ + + private StringBuffer assembleEventNotificationFromTemplate(StringBuffer sb, + String epochTimeMicrosecondsString, String sequence, + String mountpointName, String objId, String problemName, String severity, String eventTimeValueNetconfFormatString + ) { + + if (sb == null) { + sb = new StringBuffer(); + } + + NetworkElement optionalNe = deviceManager != null ? deviceManager.getNeByMountpoint(mountpointName) : null; + InventoryInformation neInventory = InventoryInformation.getDefault(); + if (optionalNe != null) { + Optional<InventoryProvider> inventoryProvider = optionalNe.getService(InventoryProvider.class); + if (inventoryProvider.isPresent()) { + neInventory = inventoryProvider.get().getInventoryInformation(); + } + } + + sb.append("{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"fault\",\n" + + " \"eventId\": \""+mountpointName+"_"+objId+"_"+problemName+"\",\n" + + " \"eventName\": \""+eventNamePrefix+"_"+problemName+"\",\n" + + " \"eventType\": \""+eventType+"\",\n" + + " \"sequence\": "+sequence+",\n" + + " \"priority\": \"High\",\n" + + " \"reportingEntityId\": \"\",\n" + + " \"reportingEntityName\": \""+entityName+"\",\n" + + " \"sourceId\": \"\",\n" + + " \"sourceName\": \""+mountpointName+"\",\n" + + " \"startEpochMicrosec\": "+epochTimeMicrosecondsString+",\n" + + " \"lastEpochMicrosec\": "+epochTimeMicrosecondsString+",\n" + + " \"version\": 3.0\n" + + " },\n" + + " \"faultFields\": {\n" + + " \"alarmAdditionalInformation\": [\n" + + " {\n" + + " \"name\": \"eventTime\",\n" + + " \"value\": \""+eventTimeValueNetconfFormatString+"\"\n" + + " },\n" + + " {\n" + + " \"name\": \"equipType\",\n" + + " \"value\": \""+neInventory.getType()+"\"\n" + + " },\n" + + " {\n" + + " \"name\": \"vendor\",\n" + + " \"value\": \""+neInventory.getVendor()+"\"\n" + + " },\n" + + " {\n" + + " \"name\": \"model\",\n" + + " \"value\": \""+neInventory.getModel()+"\"\n" + + " }\n" + + " ],\n" + + " \"faultFieldsVersion\":2.0,\n" + + " \"eventSourceType\": \""+eventSourceType+"\",\n" + + " \"alarmCondition\": \""+problemName+"\",\n" + + " \"alarmInterfaceA\": \""+objId+"\",\n" + + " \"specificProblem\": \""+problemName+"\",\n" + + " \"eventSeverity\": \""+severity+"\",\n" + + " \"vfStatus\": \"Active\"\n" + + " }\n" + + " }\n" + + "}\n" + ); + + return sb; + } + + /* ----------------- + * Convert internal type formats into the Ecomp format + */ + + private String convert(InternalSeverity severity ) { + switch( severity ) { + case NonAlarmed: + break; + case Warning: + return DCAE_WARNING; + case Minor: + return DCAE_MINOR; + case Major: + return DCAE_MAJOR; + case Critical: + return DCAE_CRITICAL; + } + return DCAE_NORMAL; + } + + + /** + * Time has to be converted into milliseconds + * @param timeAsString time as string + * @return as string + */ + private String convert(String timeAsString) { + + long microseconds = -1; + try { + microseconds = NETCONFTIME_CONVERTER.getTimeStampFromNetconfAsMilliseconds(timeAsString) * 1000; + } catch (IllegalArgumentException e) { + LOG.info("Can not convert timeAsString", e); + } + return String.valueOf(microseconds); + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderClient.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderClient.java new file mode 100644 index 000000000..6993a14e9 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderClient.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.config.DcaeConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.ProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class DcaeProviderClient implements AutoCloseable, ProviderClient { + + private static final Logger LOG = LoggerFactory.getLogger(DcaeProviderClient.class); + + private final ConfigurationFileRepresentation htConfig; + private final IConfigChangedListener configChangedListener; + + private final Object lock = new Object(); + private DcaeProviderWorker worker; + private DcaeConfig config; + + public DcaeProviderClient(ConfigurationFileRepresentation cfg, String entityName, DeviceManagerImpl deviceManager) { + LOG.info("Create"); + this.htConfig=cfg; + this.config = new DcaeConfig(cfg); + worker = new DcaeProviderWorker(config, entityName, deviceManager); + this.configChangedListener = () -> { + LOG.info("Configuration change. Worker exchanged"); + synchronized(lock) { + worker.close(); + worker = new DcaeProviderWorker(this.config, entityName, deviceManager); + } + }; + this.htConfig.registerConfigChangedListener(configChangedListener ); + + } + + @Override + public void sendProblemNotification(String mountPointName, ProblemNotificationXml notification) { + synchronized(lock) { + worker.sendProblemNotification(mountPointName, notification); + } + } + + @Override + public void sendProblemNotification(String mountPointName, ProblemNotificationXml notification, boolean neDeviceAlarm) { + sendProblemNotification(mountPointName, notification); + } + + @Override + public void close() { + this.htConfig.unregisterConfigChangedListener(configChangedListener); + synchronized(lock) { + worker.close(); + } + } + + /* --------------------------------------------------------- + * Private + */ + +} + + + diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderTask.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderTask.java new file mode 100644 index 000000000..2a169db01 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderTask.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * Event provider to ECOMP for heartbeat message + * + * @author herbert + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class DcaeProviderTask implements Runnable { + + private static final Logger LOG = LoggerFactory.getLogger(DcaeProviderTask.class); + + private int t = 0; + private final DcaeMessages dcaeMessages; + + DcaeProviderTask(DcaeMessages dcaeMessages) { + LOG.info("Create eventprovider task"); + this.dcaeMessages = dcaeMessages; + } + + private void sendHeartbeat() { + dcaeMessages.postHeartBeat(); + } + + @Override + public void run() { + LOG.debug("DCAE provider heartbeat tick start {}", t++); + sendHeartbeat(); + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderWorker.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderWorker.java new file mode 100644 index 000000000..6293843e8 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeProviderWorker.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.config.DcaeConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class DcaeProviderWorker implements AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(DcaeProviderWorker.class); + + private static final int MIN_HEARTBEAT_TIME_SECONDS = 30; + + private final ScheduledExecutorService scheduler; + private final DcaeSenderImpl dcaepClient; + private final DcaeMessages dcaeMessages; + private final ScheduledFuture<?> taskReference; + + public DcaeProviderWorker(DcaeConfig configuration, String entityName, DeviceManagerImpl deviceManager) { + + //Start services + LOG.info("Configuration: "+configuration); + int heartbeatSeconds = configuration.getTimerPeriodSeconds(); + if ( heartbeatSeconds < MIN_HEARTBEAT_TIME_SECONDS ) { + heartbeatSeconds = MIN_HEARTBEAT_TIME_SECONDS; + LOG.info("Adjust heartbeat intervall to minimum of { } seconds.",heartbeatSeconds); + } + + dcaepClient = new DcaeSenderImpl(configuration.getEventReveicerUrl(), configuration.getUserCredentials()); + dcaeMessages = new DcaeMessages(dcaepClient, entityName, heartbeatSeconds, deviceManager); + + //Activate task + LOG.info("Create Fault manager client Task"); + this.scheduler = Executors.newSingleThreadScheduledExecutor(); + Runnable task = new DcaeProviderTask(dcaeMessages); + + LOG.info("Fault task created with "+heartbeatSeconds+" Seconds"); + this.taskReference = this.scheduler.scheduleAtFixedRate(task, 0, heartbeatSeconds, TimeUnit.SECONDS); + LOG.info("Fault task scheduled"); + } + + public void sendProblemNotification(String mountPointName, ProblemNotificationXml notification) { + LOG.debug("Notification answer: {}", dcaeMessages.postNotification(mountPointName, notification)); + } + + @Override + public void close() { + this.taskReference.cancel(false); + try { + this.scheduler.shutdown(); + this.scheduler.awaitTermination(5, TimeUnit.SECONDS); + } catch (InterruptedException | SecurityException e) { + LOG.debug("Schedler shutdown interrupted with exception: ",e); + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + } + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSender.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSender.java new file mode 100644 index 000000000..5ebc37d51 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSender.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +/** + * @author herbert + * + */ +public interface DcaeSender { + + public String sendDcaePost(String body); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSenderImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSenderImpl.java new file mode 100644 index 000000000..22277a0db --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/DcaeSenderImpl.java @@ -0,0 +1,236 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * Client for ECOMP notification server + * + * Reference: @link + * http://stackoverflow.com/questions/13022717/java-and-https-url-connection-without-downloading-certificate + * + * @author herbert + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.spec.InvalidKeySpecException; +import java.util.Base64; +import javax.net.ssl.SSLContext; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPClientFromDevicemanager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DcaeSenderImpl implements DcaeSender { + + private static final Logger LOG = LoggerFactory.getLogger(DcaeSenderImpl.class); + private static final String EMPTY = ""; + private static final String charset = "UTF-8"; + + private final String urlString; + private final String basicAuth; + + private SSLContext sc = null; + private URL url = null; + private HttpURLConnection connection = null; + + public DcaeSenderImpl(String url, String userCredentials) { + + LOG.info("DcaeSenderImpl setup start with {} {}", url, userCredentials); + + this.urlString = url; + this.basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes())); + + if (urlString != null && !urlString.equals("off")) { + try { + this.url = new URL(url); + sc = BaseHTTPClientFromDevicemanager.setupSsl(true); + } catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException + | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) { + LOG.warn("SSL setup failed: {}", e.getMessage()); + } + } + LOG.info("DcaeSenderImpl setup ends"); + } + + /** + * Send message to ECOMP Server + * + * @param body for POST message + */ + @Override + public String sendDcaePost(String body) { + + if (url != null) { + try { + connection = DcaeMessages.openConnection(url, basicAuth, true, sc); + if (connection != null) { + return processPost(connection, body); + } else { + LOG.warn("No SSL context available"); + } + } catch (IOException e) { + LOG.warn("Dcae post failed {}", e.getMessage()); + } + } + return EMPTY; + } + + /** + * Connect to Server and expect answer. + * + * @return with answer body + */ + public String testConnectServer() { + + if (url != null) { + try { + connection = DcaeMessages.openConnection(url, null, false, sc); + if (connection != null) { + return receiveInitialAnswer(connection); + } + } catch (IOException e) { + LOG.warn("Dcae post failed {}", e.getMessage()); + } + } + return EMPTY; + } + + /** + * Show status in readable form for testing + * + * @return String with result + */ + public String getStatusAsString() { + StringBuffer sb = new StringBuffer(); + + sb.append("URL: " + url.getPath() + " " + url.getPort() + " Host: " + url.getHost()); + sb.append("\n"); + if (connection != null) { + sb.append("Connection setup: "); + sb.append(connection.getClass().getName()); + sb.append(" "); + } else { + sb.append("Connection setup: No connection (server problem or switched off)"); + } + return sb.toString(); + + } + + + /*------------------------------------------------------------------------------ + * Private functions + */ + + + /** + * Send Post and wait for answer + * + * @param connection + * @param body + * @return + * @throws IOException + */ + private static String processPost(HttpURLConnection connection, String body) throws IOException { + + LOG.debug("Post message: {}", connection.getURL().toString()); + if (LOG.isTraceEnabled()) { + LOG.trace("Body: {} ", body); + } + + // Send the message to destination + try (OutputStream output = connection.getOutputStream()) { + output.write(body.getBytes(charset)); + } + + // Receive answer + InputStream response = null; + BufferedReader rd = null; + StringBuilder result = new StringBuilder(); + + try { + int responseCode = connection.getResponseCode(); + LOG.debug("Response code: {}", String.valueOf(responseCode)); + + if (responseCode >= 200 && responseCode < 300) { + response = connection.getInputStream(); + } else { + response = connection.getErrorStream(); + if (response == null) { + response = connection.getInputStream(); + } + } + if (response != null) { + rd = new BufferedReader(new InputStreamReader(response)); + String line; + while ((line = rd.readLine()) != null) { + result.append(line); + } + } + } catch (IOException e) { + LOG.debug("No response received: {}", e.getMessage()); + } finally { + if (response != null) { + response.close(); + } + if (rd != null) { + rd.close(); + } + } + + LOG.trace("Result: {} ", result); + return result.toString(); + } + + /** + * Read initial answer from Server after connect + * + * @param connection that was opened + * @return String with answer message + * @throws IOException + */ + private static String receiveInitialAnswer(URLConnection iConnection) throws IOException { + + + final StringBuffer response = new StringBuffer(); + + if (iConnection != null) { + + final Reader reader = new InputStreamReader(iConnection.getInputStream()); + final BufferedReader br = new BufferedReader(reader); + String line = ""; + while ((line = br.readLine()) != null) { + response.append(line); + response.append("\n"); + } + br.close(); + } + + return response.toString(); + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/config/DcaeConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/config/DcaeConfig.java new file mode 100644 index 000000000..2e4d73acb --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/dcaeconnector/impl/config/DcaeConfig.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.config; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; + +public class DcaeConfig implements Configuration { + + private static final String SECTION_MARKER_DCAE = "dcae"; + + private static final String PROPERTY_KEY_EVENTRECEIVERURL = "dcaeUrl"; + private static final String PROPERTY_KEY_USERCREDENTIALS = "dcaeUserCredentials"; + private static final String PROPERTY_KEY_TIMERPERIOD = "dcaeHeartbeatPeriodSeconds"; + + private static final String DEFAULT_VALUE_EVENTRECEIVERURL = "off"; + private static final String DEFAULT_VALUE_USERCREDENTIALS = "admin:admin"; + private static final long DEFAULT_VALUE_TIMERPERIOD = 120; + + private final ConfigurationFileRepresentation configuration; + + public DcaeConfig(ConfigurationFileRepresentation configuration) { + this.configuration = configuration; + this.configuration.addSection(SECTION_MARKER_DCAE); + defaults(); + } + + /* *********************** + * Getter + */ + + public String getEventReveicerUrl() { + return configuration.getProperty(SECTION_MARKER_DCAE, PROPERTY_KEY_EVENTRECEIVERURL); + } + + public String getUserCredentials() { + return configuration.getProperty(SECTION_MARKER_DCAE, PROPERTY_KEY_USERCREDENTIALS); + } + + public Integer getTimerPeriodSeconds() { + long res = configuration.getPropertyLong(SECTION_MARKER_DCAE, PROPERTY_KEY_TIMERPERIOD).orElse(DEFAULT_VALUE_TIMERPERIOD); + return (int)res; + } + + + @Override + public String getSectionName() { + return SECTION_MARKER_DCAE; + } + + @Override + public void defaults() { + this.configuration.setPropertyIfNotAvailable(SECTION_MARKER_DCAE, PROPERTY_KEY_EVENTRECEIVERURL, DEFAULT_VALUE_EVENTRECEIVERURL); + this.configuration.setPropertyIfNotAvailable(SECTION_MARKER_DCAE, PROPERTY_KEY_USERCREDENTIALS, DEFAULT_VALUE_USERCREDENTIALS); + this.configuration.setPropertyIfNotAvailable(SECTION_MARKER_DCAE, PROPERTY_KEY_TIMERPERIOD, DEFAULT_VALUE_TIMERPERIOD); + } + + @Override + public String toString() { + return "DcaeConfig [getEventReveicerUrl()=" + getEventReveicerUrl() + ", getUserCredentials()=" + + getUserCredentials() + ", getTimerPeriodSeconds()=" + getTimerPeriodSeconds() + ", getSectionName()=" + + getSectionName() + "]"; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/Checker.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/Checker.java new file mode 100644 index 000000000..1091c41eb --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/Checker.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * (c) highstreet technologies GmbH + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Steps to Monitor the connection to a network element during state connected + */ +abstract class Checker { + + @SuppressWarnings("unused") + private static final Logger LOG = LoggerFactory.getLogger(Checker.class); + + /** + * Check action. + * @return true if reachable, false if not + */ + abstract boolean isReachableOnce(); + + /** + * Procedure to check the connection of one mountpoint + * @return true if reachable, false if not + */ + boolean isConnected() { + return isReachableOnce(); + } +} + diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitor.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitor.java new file mode 100644 index 000000000..f0a477b84 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitor.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; + +public interface DeviceMonitor extends AutoCloseable { + + /** + * Referesh database by raising all alarms again. + */ + void refreshAlarmsInDb(); + + /** + * removeMountpointIndication deregisters a mountpoint for registration services + * @param mountPointNodeName to deregister + */ + void removeMountpointIndication(String mountPointNodeName); + + /** + * Notify of device state change to "disconnected" + * Mount point supervision + * @param mountPointNodeName to deregister + */ + void deviceDisconnectIndication(String mountPointNodeName); + + /** + * Notify of device state changes to "connected" + * @param mountPointNodeName name of mount point + * @param ne to monitor + */ + void deviceConnectMasterIndication(String mountPointNodeName, DeviceMonitoredNe ne); + + /** + * Notify of device state changes to "connected" + * @param mountPointNodeName name of mount point + * @param ne to monitor + */ + void deviceConnectMasterIndication(String mountPointNodeName, NetworkElement ne); + + /** + * Notify of device state changes to "connected" for slave nodes + * @param mountPointNodeName name of mount point + */ + void deviceConnectSlaveIndication(String mountPointNodeName); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorEmptyImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorEmptyImpl.java new file mode 100644 index 000000000..4a8eba09e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorEmptyImpl.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; + +public class DeviceMonitorEmptyImpl implements DeviceMonitor { + + @Override + public void refreshAlarmsInDb() { + } + + @Override + public void removeMountpointIndication(String mountPointNodeName) { + } + + @Override + public void deviceConnectMasterIndication(String mountPointNodeName, DeviceMonitoredNe ne) { + } + + @Override + public void deviceDisconnectIndication(String mountPointNodeName) { + } + + @Override + public void deviceConnectSlaveIndication(String mountPointNodeName) { + } + + @Override + public void close() throws Exception { + } + + @Override + public void deviceConnectMasterIndication(String mountPointNodeName, NetworkElement ne) { + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorImpl.java new file mode 100644 index 000000000..fd2b141df --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorImpl.java @@ -0,0 +1,264 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * (c) 2017 highstreet technologies GmbH + */ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import java.util.Enumeration; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.config.DmConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Implementation of concept "Active monitoring" of a device.<br> + * <br> + * For each existing mountpoint a task runs with 120s cycle time. Every 120 seconds the check actions are performed. + * The request is handled by the NETCONF layer with a (default)configured time-out of 60 seconds.<br> + * Generated alarms, by the object/node "SDN-Controller" are (enum DeviceMonitorProblems):<br> + * - notConnected(InternalSeverity.Warning)<br> + * - noConnectionMediator(InternalSeverity.Minor)<br> + * - noConnectionNe(InternalSeverity.Critical)<br> + * <br> + * 1. Mountpoint does not exist<br> + * If the mountpoint does not exists there are no related current alarms in the database.<br> + * <br> + * 2. Created mountpoint with state "Connecting" or "UnableToConnect"<br> + * If the Mountpoint is created and connection status is "Connecting" or "UnableToConnect".<br> + * - After about 2..4 Minutes ... raise alarm "notConnected" with severity warning<br> + * <br> + * 3. Created mountpoint with state "Connection"<br> + * There are two monitor activities.<br> + * 3a. Check of Mediator connection by requesting (typical) cached data.<br> + * - After about 60 seconds raise alarm: connection-loss-mediator with severity minor<br> + * - Request from Mediator: network-element<br> + * <br> + * 3b. Check connection to NEby requesting (typical) non-cached data.<br> + * - Only if AirInterface available. The first one is used.<br> + * - Requested are the currentAlarms<br> + * - After about 60 seconds raise alarm: connection-loss-network-element with severity critical<br> + * <br> + * @author herbert + */ + +public class DeviceMonitorImpl implements DeviceMonitor, IConfigChangedListener { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceMonitorImpl.class); + + private final ConcurrentHashMap<String, DeviceMonitorTask> queue; + private final ScheduledExecutorService scheduler; + private final ODLEventListenerHandler odlEventListener; + @SuppressWarnings("unused") + private final DataBroker dataBroker; //Future usage + private final DmConfig dmConfig; + private final DeviceMonitoredNe dummyNe; + + /*------------------------------------------------------------- + * Construction/ destruction of service + */ + + /** + * Basic implementation of devicemonitoring + * @param odlEventListener as destination for problems + */ + public DeviceMonitorImpl(DataBroker dataBroker, ODLEventListenerHandler odlEventListener, ConfigurationFileRepresentation htconfig) { + LOG.info("Construct {}", this.getClass().getSimpleName()); + + this.odlEventListener = odlEventListener; + this.dataBroker = dataBroker; + this.dummyNe = getDummyNe(); + + htconfig.registerConfigChangedListener(this); + this.dmConfig = new DmConfig(htconfig); + setDmConfig(dmConfig); + + this.queue = new ConcurrentHashMap<>(); + this.scheduler = Executors.newScheduledThreadPool(10); + } + + /** + * Stop the service. Stop all running monitoring tasks. + */ + @Override + synchronized public void close() { + LOG.info("Close {}", this.getClass().getSimpleName()); + + Enumeration<String> e = queue.keys(); + while (e.hasMoreElements()) { + deviceDisconnectIndication(e.nextElement()); + } + + scheduler.shutdown(); + } + + @Override + public void onConfigChanged() { + setDmConfig(dmConfig); + } + + private void setDmConfig(DmConfig dmConfig) { + for (DeviceMonitorProblems problem : DeviceMonitorProblems.values()) { + problem.setSeverity(dmConfig.getSeverity(problem)); + } + } + + /*------------------------------------------------------------- + * Start/ stop/ update service for Mountpoint + */ + + /** + * Notify of device state changes to "connected" for slave nodes + * @param mountPointNodeName name of mount point + */ + @Override + synchronized public void deviceConnectSlaveIndication(String mountPointNodeName) { + deviceConnectMasterIndication(mountPointNodeName, (DeviceMonitoredNe)null); + } + + @Override + public void deviceConnectMasterIndication(String mountPointNodeName, NetworkElement networkElement) { + Optional<DeviceMonitoredNe> monitoredNe = networkElement.getService(DeviceMonitoredNe.class); + deviceConnectMasterIndication(mountPointNodeName, monitoredNe.isPresent() ? monitoredNe.get() : dummyNe); + } + + /** + * Notify of device state changes to "connected" + * @param mountPointNodeName name of mount point + * @param ne to monitor + */ + @Override + synchronized public void deviceConnectMasterIndication(String mountPointNodeName, DeviceMonitoredNe ne) { + + LOG.debug("ne changes to connected state {}",mountPointNodeName); + createMonitoringTask(mountPointNodeName); + if (queue.containsKey(mountPointNodeName)) { + DeviceMonitorTask task = queue.get(mountPointNodeName); + task.deviceConnectIndication(ne); + } else { + LOG.warn("Monitoring task not in queue: {} {} {}", mountPointNodeName, mountPointNodeName.hashCode(), queue.size()); + } + } + + /** + * Notify of device state change to "disconnected" + * Mount point supervision + * @param mountPointNodeName to deregister + */ + @Override + synchronized public void deviceDisconnectIndication(String mountPointNodeName) { + + LOG.debug("State changes to not connected state {}",mountPointNodeName); + createMonitoringTask(mountPointNodeName); + if (queue.containsKey(mountPointNodeName)) { + DeviceMonitorTask task = queue.get(mountPointNodeName); + task.deviceDisconnectIndication(); + } else { + LOG.warn("Monitoring task not in queue: {} {} {}", mountPointNodeName, mountPointNodeName.hashCode(), queue.size()); + } + } + + /** + * removeMountpointIndication deregisters a mountpoint for registration services + * @param mountPointNodeName to deregister + */ + @Override + synchronized public void removeMountpointIndication(String mountPointNodeName) { + + if (queue.containsKey(mountPointNodeName)) { + DeviceMonitorTask task = queue.get(mountPointNodeName); + //Remove from here + queue.remove(mountPointNodeName); + //Clear all problems + task.removeMountpointIndication(); + LOG.debug("Task stopped: {}", mountPointNodeName); + } else { + LOG.warn("Task not in queue: {}", mountPointNodeName); + } + } + + /** + * Referesh database by raising all alarms again. + */ + @Override + public void refreshAlarmsInDb() { + synchronized(queue) { + for (DeviceMonitorTask task : queue.values()) { + task.refreshAlarms(); + } + } + } + + /*------------------------------------------------------------- + * Private functions + */ + + /** + * createMountpoint registers a new mountpoint monitoring service + * @param mountPointNodeName name of mountpoint + */ + synchronized private DeviceMonitorTask createMonitoringTask(String mountPointNodeName) { + + DeviceMonitorTask task; + LOG.debug("Register for monitoring {} {}",mountPointNodeName, mountPointNodeName.hashCode()); + + if (queue.containsKey(mountPointNodeName)) { + LOG.info("Monitoring task exists"); + task = queue.get(mountPointNodeName); + } else { + LOG.info("Do start of DeviceMonitor task"); + //Runnable task = new PerformanceManagerTask(queue, databaseService); + task = new DeviceMonitorTask(mountPointNodeName, this.odlEventListener); + queue.put(mountPointNodeName, task); + task.start(scheduler); + } + return task; + } + + + private static DeviceMonitoredNe getDummyNe() { + return new DeviceMonitoredNe() { + + @Override + public void prepareCheck() { + // Do nothing + } + + @Override + public boolean checkIfConnectionToMediatorIsOk() { + return true; + } + + @Override + public boolean checkIfConnectionToNeIsOk() { + return true; + } + }; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorProblems.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorProblems.java new file mode 100644 index 000000000..1282a41f8 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorProblems.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * Problems generated by DeviceMonitor + * + * @author herbert + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public enum DeviceMonitorProblems { + + /** + * Mountpoint is not connected via NETCONF with NE/Mediator = ssh connection + */ + connectionLossOAM(InternalSeverity.Major), + + /** + * Mountpoint is connected via Netconf to Mediator, but mediator is not responding. + * Connection state to NE is unknown. + */ + connectionLossMediator(InternalSeverity.Major), + + /** Mountpoint is connected via Netconf to Mediator. + * This connection is OK, but mediator <-> NE Connection is not OK + */ + connectionLossNeOAM(InternalSeverity.Major); + + private static final Logger LOG = LoggerFactory.getLogger(DeviceMonitorProblems.class); + private InternalSeverity severity; + + DeviceMonitorProblems(@Nullable InternalSeverity severity) { + if (severity != null) { + this.severity = severity; + } + } + + public InternalSeverity getSeverity() { + return severity; + } + + public void setSeverity(InternalSeverity severity) { + LOG.info("Change severity for {} from {} to {}", name(), this.severity, severity); + this.severity=severity; + } + +} + diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorTask.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorTask.java new file mode 100644 index 000000000..d26f4ac7f --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/DeviceMonitorTask.java @@ -0,0 +1,320 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * @author herbert + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DeviceMonitorTask implements Runnable { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceMonitorTask.class); + private static final String LOGMARKER = "DMTick"; + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + private final String mountPointName; + private final ODLEventListenerHandler odlEventListener; + private final Checker checkConnectionToMediator; + private final Checker checkConnectionToNe; + + private int tickCounter; //Added for each tick. Not relevant for internal status + + private ScheduledFuture<?> taskHandle; + private final Object lockNe = new Object(); //USe top lock access to member ne + private @Nullable DeviceMonitoredNe ne; //Indication if in status connect or disconnect + private @NonNull Boolean mountpointConnectingStateSupervision; //Indication of mountpoint supervision + + private final Object lockDisconnectSupervisionTickout = new Object(); + private Integer disconnectSupervisionTickout; //Tickcounter of task ticks for "not connected indication" + private Set<DeviceMonitorProblems> currentProblems; //List with actual problems. Synchronized by itself + + /*------------------------------------------------------------ + * Construction + */ + + /** + * Setup monitoring task + * @param mountPointName to monitor + * @param odlEventListener to forward problems to + */ + public DeviceMonitorTask(String mountPointName, ODLEventListenerHandler odlEventListener) { + LOG.debug("Init task {}", DeviceMonitorTask.class.getSimpleName()); + + //Setup finals + this.mountPointName = mountPointName; + this.odlEventListener = odlEventListener; + this.checkConnectionToMediator = new Checker() { + @Override + boolean isReachableOnce() { + synchronized(lockNe) { + //mountpoint state "Connected" + //If for any reason the mountpoint is Connected, but Notconf messages are not received + return ne == null ? true : ne.checkIfConnectionToMediatorIsOk(); + } + } + }; + this.checkConnectionToNe = new Checker() { + @Override + boolean isReachableOnce() { + synchronized(lockNe) { + //mountpoint state "Connected" + //If netconf mediator (netconf application software for NE) has connection loss to managed device. + //The networkelement object is available, but there is no interfacepack available. + return ne == null ? true : ne.checkIfConnectionToNeIsOk(); + } + } + }; + + //Setup parameters + this.taskHandle = null; + this.tickCounter = 0; + this.ne = null; + this.mountpointConnectingStateSupervision = false; + this.currentProblems = Collections.synchronizedSet(EnumSet.noneOf(DeviceMonitorProblems.class)); + this.disconnectSupervisionTickout = 0; + + int removed = odlEventListener.removeAllCurrentProblemsOfNode(mountPointName); + LOG.debug("{} Init task removed fault entries {}", LOGMARKER, removed); + + } + + /** + * Start for each object an own instance of the thread. + * @param scheduler for all the threads. + */ + public void start(ScheduledExecutorService scheduler) { + LOG.info("{} {} DeviceMonitor task to create", LOGMARKER, tickCounter); + if (taskHandle == null) { + startDisconnectSupervision(); + taskHandle = scheduler.scheduleAtFixedRate(this, 0, 120, TimeUnit.SECONDS); + LOG.info("DeviceMonitor task scheduled"); + } else { + LOG.error("{} {} Task already running.", LOGMARKER, tickCounter); + } + } + + /** + * Call after NE change state to connected. + * Mountpoint exists. Status is Connecting. + * @param neParam that connected + */ + + public void deviceConnectIndication(DeviceMonitoredNe neParam) { + LOG.info("{} {} Connect {} and stop.", LOGMARKER, tickCounter, mountPointName); + clear(DeviceMonitorProblems.connectionLossOAM); + synchronized(lockNe) { + this.ne = neParam; + this.mountpointConnectingStateSupervision = false; + } + stopDisconnectSupervision(); + } + + /** + * If ne is disconnected do the related actions. + * - Mountpoint exists. Status is Connecting or UnableToConnect + */ + + public void deviceDisconnectIndication() { + LOG.info("{} {} Disconnect {} and start.", LOGMARKER, tickCounter, mountPointName); + clear(DeviceMonitorProblems.connectionLossOAM); + synchronized(lockNe) { + this.ne = null; + this.mountpointConnectingStateSupervision = true; + } + startDisconnectSupervision(); + } + + /** + * Do all actions to clean up the log if mountpoint has been deleted. + * - Mountpoint removed + * Prepare cancellation of the task and cancel task + */ + + public void removeMountpointIndication() { + for (DeviceMonitorProblems problem : DeviceMonitorProblems.values()) { + clear(problem); + } + //Cancel the task + if (this.taskHandle != null) { + this.taskHandle.cancel(false); + LOG.info("{} {} DeviceMonitor task canceled for {}", LOGMARKER, tickCounter, mountPointName); + } else { + LOG.error("{} {} Task already stopped", LOGMARKER, tickCounter); + } + } + + /** + * Referesh Alarms + */ + public void refreshAlarms() { + LOG.debug("{} Start refresh of all problems",LOGMARKER); + synchronized(currentProblems) { + for (DeviceMonitorProblems problem : currentProblems) { + LOG.debug("{} Refresh problem {} Raised-status {}",LOGMARKER, problem.name(), currentProblems.contains(problem)); + odlEventListener.onProblemNotification(mountPointName, problem.name(), problem.getSeverity()); + } + } + LOG.debug("{} Finish refresh of all problems",LOGMARKER); + } + + /*------------------------------------------------------------ + * Functions to clear/raise alarm + */ + + /** + * Raise a problem, but only once + * @param problem + */ + private void raise(DeviceMonitorProblems problem) { + LOG.debug("{} Raise problem {} Raised-status {}",LOGMARKER, problem.name(), currentProblems.contains(problem)); + synchronized(currentProblems) { + if (! currentProblems.contains(problem)) { + currentProblems.add(problem); + odlEventListener.onProblemNotification(mountPointName, problem.name(), problem.getSeverity()); + } + } + } + + /** + * Raise a problem, but only once + * @param problem + */ + private void clear(DeviceMonitorProblems problem) { + LOG.debug("{} Clear problem {} Raised-status {}",LOGMARKER, problem.name(), currentProblems.contains(problem)); + synchronized(currentProblems) { + if (currentProblems.contains(problem)) { + currentProblems.remove(problem); + odlEventListener.onProblemNotification(mountPointName, problem.name(), InternalSeverity.NonAlarmed); + } + } + } + + /** + * Process problem notification cascade + * @param isReachable + * @param problem + */ + private void clearRaiseIfConnected(Checker checker, DeviceMonitorProblems problem) { + LOG.debug("{} check start {} problem {} Raised-status {}",LOGMARKER, tickCounter, problem.name(), currentProblems.contains(problem)); + if (checker.isConnected()) { + clear(problem); + } else { + raise(problem); + } + LOG.debug("{} check end {} problem {} Raised-status {}",LOGMARKER, tickCounter, problem.name(), currentProblems.contains(problem)); + } + + /*------------------------------------------------------------ + * Functions to start/stop + */ + + private void startDisconnectSupervision() { + synchronized(lockDisconnectSupervisionTickout) { + this.disconnectSupervisionTickout = 2; + } + } + + private void stopDisconnectSupervision() { + synchronized(lockDisconnectSupervisionTickout) { + this.disconnectSupervisionTickout = 0; + } + } + + private boolean processDisconnectSupervisionAndCheckExceeded() { + synchronized(lockDisconnectSupervisionTickout) { + if (disconnectSupervisionTickout == 0) { + return true; + } else if (disconnectSupervisionTickout > 0) { + disconnectSupervisionTickout--; + } + return false; + } + } + + /*------------------------------------------------------------ + * TASK + */ + + /** + * Task to monitor connectivity to Network Elements. + * Connectivity problems lead to alarm indication. + */ + @Override + public void run() { + + try { + LOG.debug("{} UTCTime {} START mountpoint {} tick {} connecting supervision {} tickout {}", + LOGMARKER, + NETCONFTIME_CONVERTER.getTimeStamp(), + mountPointName, + tickCounter, + mountpointConnectingStateSupervision, + disconnectSupervisionTickout); + + if (mountpointConnectingStateSupervision) { + LOG.debug("{} {} Mountpoint supervision {}", LOGMARKER, tickCounter, mountPointName); + if (processDisconnectSupervisionAndCheckExceeded()) { + raise(DeviceMonitorProblems.connectionLossOAM); + } + + } else { + synchronized (lockNe) { + if (ne != null) { + //checks during "Connected" + clear(DeviceMonitorProblems.connectionLossOAM); //Always cleared never raised + LOG.debug("{} {} Prepare check", LOGMARKER, tickCounter); + ne.prepareCheck(); // Prepare ne check + // Mediator check + LOG.debug("{} {} Mediator check", LOGMARKER, tickCounter); + clearRaiseIfConnected(checkConnectionToMediator, DeviceMonitorProblems.connectionLossMediator); + + // NE check + LOG.debug("{} {} Ne check", LOGMARKER, tickCounter); + clearRaiseIfConnected(checkConnectionToNe, DeviceMonitorProblems.connectionLossNeOAM); + } else { + //Monitor switch off. + LOG.debug("{} {} Monitor switch off state", LOGMARKER, tickCounter); + clear(DeviceMonitorProblems.connectionLossOAM); //Always cleared never raised + clear(DeviceMonitorProblems.connectionLossMediator); //Always cleared never raised + clear(DeviceMonitorProblems.connectionLossNeOAM); //Always cleared never raised + } + } + } + } catch (Exception e) { + //Prevent stopping the task + LOG.warn("{} {} During DeviceMontoring task",LOGMARKER, tickCounter, e); + } + LOG.debug("{} {} END", LOGMARKER, tickCounter++); + + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/config/DmConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/config/DmConfig.java new file mode 100644 index 000000000..215d8272d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/devicemonitor/impl/config/DmConfig.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.config; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitorProblems; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; + +/** + * Configuration of devicemonitor, section [devicemonitor] + * SeverityConnectionlossNeOAM=minor + * SeverityConnectionlossOAM=major + * SeverityConnectionlossMediator=critical + */ +public class DmConfig implements Configuration { + + private static final String SECTION_MARKER_TA = "devicemonitor"; + + private static final String PROPERTY_KEY_PREFIX_Severity = "Severity"; + + private final ConfigurationFileRepresentation configuration; + + public DmConfig(ConfigurationFileRepresentation configuration) { + this.configuration = configuration; + this.configuration.addSection(SECTION_MARKER_TA); + defaults(); + } + + public InternalSeverity getSeverity(DeviceMonitorProblems problem) { + String severityString = configuration.getProperty(SECTION_MARKER_TA, getPropertyName(problem)); + InternalSeverity result = InternalSeverity.valueOfString(severityString); + return result != null ? result : InternalSeverity.Major; + } + + @Override + public String getSectionName() { + return SECTION_MARKER_TA; + } + + @Override + public void defaults() { + for (DeviceMonitorProblems problem : DeviceMonitorProblems.values()) { + configuration.setPropertyIfNotAvailable(SECTION_MARKER_TA, getPropertyName(problem), problem.getSeverity().name()); + } + } + + private String getPropertyName(DeviceMonitorProblems problem) { + return PROPERTY_KEY_PREFIX_Severity+problem.name(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ConnectionStatusHousekeepingService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ConnectionStatusHousekeepingService.java new file mode 100644 index 000000000..d42537650 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ConnectionStatusHousekeepingService.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping; + +import com.google.common.util.concurrent.FluentFuture; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.eclipse.jdt.annotation.NonNull; +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.InternalConnectionStatus; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService; +import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionLogStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionEntity; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ConnectionStatusHousekeepingService implements ClusterSingletonService,AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(ConnectionStatusHousekeepingService.class); + + private static final long INTERVAL_SECONDS = 30; + private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID = InstanceIdentifier + .create(NetworkTopology.class) + .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); + private static final ServiceGroupIdentifier IDENT = ServiceGroupIdentifier.create("ConnectionStatusHousekeepingService"); + + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3); + private final DataBroker dataBroker; + private final DataProvider dataProvider; + private boolean isMaster; + private Future<?> taskReference; + + private final Runnable runner = () -> doClean(); + + public ConnectionStatusHousekeepingService(DataBroker dataBroker, DataProvider dataProvider) { + this.dataBroker = dataBroker; + this.dataProvider = dataProvider; + this.start(); + } + + public void start() { + if (taskReference != null) { + taskReference.cancel(false); + } + if(!isMaster) { + LOG.info("do not start. not the master node"); + return; + } + LOG.info("starting scheduler with interval {}", INTERVAL_SECONDS); + this.taskReference = this.scheduler.scheduleAtFixedRate(runner, INTERVAL_SECONDS, INTERVAL_SECONDS, + TimeUnit.SECONDS); + } + + private void doClean() { + LOG.debug("start housekeeping"); + // get all devices from networkelement-connection index + try { + List<NetworkElementConnectionEntity> list = this.dataProvider.getNetworkElementConnections(); + + ConnectionLogStatus dbStatus; + ConnectionLogStatus mdsalStatus; + String nodeId; + if (list == null || list.size() <= 0) { + LOG.trace("no items in list."); + return; + } + for (NetworkElementConnectionEntity item : list) { + + // compare with MD-SAL + nodeId = item.getNodeId(); + LOG.trace("check status of {}", nodeId); + dbStatus = item.getStatus(); + mdsalStatus = this.getMDSalConnectionStatus(nodeId); + if (mdsalStatus == null) { + LOG.trace("unable to get connection status. jump over"); + continue; + } + // if different then update db + if (dbStatus != mdsalStatus) { + LOG.trace("status is inconsistent db={}, mdsal={}. updating db", dbStatus, mdsalStatus); + if(!item.isIsRequired() && mdsalStatus==ConnectionLogStatus.Disconnected) { + this.dataProvider.removeNetworkConnection(nodeId); + } + else { + this.dataProvider.updateNetworkConnectionDeviceType( + new NetworkElementConnectionBuilder().setStatus(mdsalStatus).build(), nodeId); + } + } else { + LOG.trace("no difference"); + } + + } + } catch (Exception e) { + LOG.warn("problem executing housekeeping task: {}", e); + } + LOG.debug("finish housekeeping"); + } + + private ConnectionLogStatus getMDSalConnectionStatus(String nodeId) { + + @SuppressWarnings("null") + @NonNull InstanceIdentifier<Node> instanceIdentifier = NETCONF_TOPO_IID.child(Node.class, + new NodeKey(new NodeId(nodeId))); + FluentFuture<Optional<Node>> optionalNode = this.dataBroker.newReadOnlyTransaction() + .read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier); + try { + Node node = optionalNode.get(5, TimeUnit.SECONDS).get(); + LOG.debug("node is {}", node); + NetconfNode nNode = node.augmentation(NetconfNode.class); + LOG.debug("nnode is {}", nNode); + if (nNode != null) { + return InternalConnectionStatus.statusFromNodeStatus(nNode.getConnectionStatus()); + } + } catch (NoSuchElementException e) { + return ConnectionLogStatus.Disconnected; + } catch (ExecutionException | InterruptedException | TimeoutException e) { + LOG.warn("unable to get node info: {}", e); + } + + return null; + } + + @Override + public void close() throws Exception { + if (taskReference != null) { + taskReference.cancel(false); + } + this.scheduler.shutdown(); + } + + @SuppressWarnings("null") + @Override + public @NonNull ServiceGroupIdentifier getIdentifier() { + return IDENT; + } + + @Override + public void instantiateServiceInstance() { + LOG.info("We take Leadership"); + this.isMaster=true; + this.start(); + } + + @Override + public ListenableFuture<? extends Object> closeServiceInstance() { + LOG.info("We lost Leadership"); + this.isMaster=false; + this.start(); + return Futures.immediateFuture(null); + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementHouskeepingService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementHouskeepingService.java new file mode 100644 index 000000000..b9d09afac --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementHouskeepingService.java @@ -0,0 +1,168 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitor; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.MountPointService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResyncNetworkElementHouskeepingService implements ResyncNetworkElementsListener { + + private static final Logger LOG = LoggerFactory.getLogger(ResyncNetworkElementHouskeepingService.class); + + private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID = + InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, + new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); + + // Services to use + private final MountPointService mountPointService; + private final ODLEventListenerHandler odlEventListenerHandler; + private final DataProvider databaseClientEvents; + private @Nullable final DeviceMonitor deviceMonitor; + private final DeviceManagerImpl deviceManager; + + /** Thread is started to du the clean up action **/ + private Thread threadDoClearCurrentFaultByNodename; + /** Indicate number of refresh activities for log **/ + private int refreshCounter = 0; + + /** + * @param deviceManager to provide devices information + * @param mountPointService service + * @param odlEventListenerHandler handler for events + * @param databaseClientEvents database to clean + * @param deviceMonitor devicemonitor + */ + public ResyncNetworkElementHouskeepingService( + DeviceManagerImpl deviceManager, + MountPointService mountPointService, ODLEventListenerHandler odlEventListenerHandler, + DataProvider databaseClientEvents, DeviceMonitor deviceMonitor) { + super(); + this.deviceManager = deviceManager; + this.mountPointService = mountPointService; + this.odlEventListenerHandler = odlEventListenerHandler; + this.databaseClientEvents = databaseClientEvents; + this.deviceMonitor = deviceMonitor; + } + + /** + * Async RPC Interface implementation + */ + @Override + public @NonNull List<String> doClearCurrentFaultByNodename(@Nullable List<String> nodeNamesInput) + throws IllegalStateException { + + if (this.databaseClientEvents == null) { + throw new IllegalStateException("dbEvents service not instantiated"); + } + + if (threadDoClearCurrentFaultByNodename != null && threadDoClearCurrentFaultByNodename.isAlive()) { + throw new IllegalStateException("A clear task is already active"); + } else { + + // Create list of mountpoints if input is empty, using the content in ES + if (nodeNamesInput == null || nodeNamesInput.size() <= 0) { + nodeNamesInput = this.databaseClientEvents.getAllNodesWithCurrentAlarms(); + } + + // Filter all mountpoints from input that were found and are known to this Cluster-node instance of + // DeviceManager + final List<String> nodeNamesHandled = new ArrayList<>(); + for (String mountpointName : nodeNamesInput) { + LOG.info("Work with mountpoint {}", mountpointName); + + if (odlEventListenerHandler != null && mountpointName.equals(odlEventListenerHandler.getOwnKeyName())) { + + // SDN Controller related alarms + // -- can not be recreated on all nodes in connected state + // -- would result in a DCAE/AAI Notification + // Conclusion for 1810 Delivery ... not covered by RPC function (See issue #43) + LOG.info("Ignore SDN Controller related alarms for {}", mountpointName); + // this.databaseClientEvents.clearFaultsCurrentOfNode(mountpointName); + // nodeNamesHandled.add(mountpointName); + + } else { + + if (mountPointService != null) { + InstanceIdentifier<Node> instanceIdentifier = + NETCONF_TOPO_IID.child(Node.class, new NodeKey(new NodeId(mountpointName))); + Optional<MountPoint> optionalMountPoint = mountPointService.getMountPoint(instanceIdentifier); + + if (!optionalMountPoint.isPresent()) { + LOG.info("Remove Alarms for unknown mountpoint {}", mountpointName); + this.databaseClientEvents.clearFaultsCurrentOfNode(mountpointName); + nodeNamesHandled.add(mountpointName); + } else { + if (deviceManager.getNeByMountpoint(mountpointName) != null) { + LOG.info("At node known mountpoint {}", mountpointName); + nodeNamesHandled.add(mountpointName); + } else { + LOG.info("At node unknown mountpoint {}", mountpointName); + } + } + } + } + } + + // Force a sync + deviceMonitor.refreshAlarmsInDb(); + + threadDoClearCurrentFaultByNodename = new Thread(() -> { + refreshCounter++; + LOG.info("Start refresh mountpoint task {}", refreshCounter); + // for(String nodeName:nodeNamesOutput) { + for (String nodeName : nodeNamesHandled) { + NetworkElement ne = deviceManager.getNeByMountpoint(nodeName); + if (ne != null) { + LOG.info("Refresh mountpoint {}", nodeName); + ne.warmstart(); + } else { + LOG.info("Unhandled mountpoint {}", nodeName); + } + } + LOG.info("End refresh mountpoint task {}", refreshCounter); + }); + threadDoClearCurrentFaultByNodename.start(); + return nodeNamesHandled; + } + }; + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementsListener.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementsListener.java new file mode 100644 index 000000000..751d48cda --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/housekeeping/ResyncNetworkElementsListener.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping; + +import java.util.List; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; + + +public interface ResyncNetworkElementsListener +{ + /** + * Handle API Request and clean up current alarms according to the list of mountpoint id's/devices + * Implement RPC function "clear-current-fault-by-nodename" + * @return List with + * @throws IllegalStateException Illegal state exception + */ + public @NonNull List<String> doClearCurrentFaultByNodename(@Nullable List<String> nodeNamesInput) throws IllegalStateException; + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerApiServiceImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerApiServiceImpl.java new file mode 100644 index 000000000..9a2b81cbb --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerApiServiceImpl.java @@ -0,0 +1,239 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import java.util.List; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping.ResyncNetworkElementsListener; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.MaintenanceRPCServiceAPI; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl.MaintenanceServiceImpl; +import org.opendaylight.mdsal.binding.api.RpcProviderService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ClearCurrentFaultByNodenameInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ClearCurrentFaultByNodenameOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ClearCurrentFaultByNodenameOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.DevicemanagerService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetRequiredNetworkElementKeysInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetRequiredNetworkElementKeysOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetRequiredNetworkElementKeysOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushAttributeChangeNotificationInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushAttributeChangeNotificationOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushFaultNotificationInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushFaultNotificationOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeOutputBuilder; +import org.opendaylight.yangtools.concepts.ObjectRegistration; +import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.util.concurrent.ListenableFuture; + +public class DeviceManagerApiServiceImpl implements DevicemanagerService, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(DevicemanagerService.class); + + private final ObjectRegistration<DevicemanagerService> rpcReg; + private @Nullable + final MaintenanceRPCServiceAPI maintenanceService; + private @Nullable + final PushNotifications pushNotificationsListener; + private @Nullable + final ResyncNetworkElementsListener resyncCallbackListener; + + DeviceManagerApiServiceImpl(final RpcProviderService rpcProviderRegistry, + MaintenanceServiceImpl maintenanceService, ResyncNetworkElementsListener listener, + PushNotifications pushNotificationsListener) { + this.maintenanceService = maintenanceService; + this.pushNotificationsListener = pushNotificationsListener; + this.resyncCallbackListener = listener; + + // Register ourselves as the REST API RPC implementation + LOG.info("Register RPC Service "+DevicemanagerService.class.getSimpleName()); + this.rpcReg = rpcProviderRegistry.registerRpcImplementation(DevicemanagerService.class, this); + } + + @Override + public void close() throws Exception { + LOG.info("Close RPC Service"); + if (rpcReg != null) { + rpcReg.close(); + } + } + + /*------------------------------- + * Interfaces for MaintenanceService + */ + + @Override + public ListenableFuture<RpcResult<GetRequiredNetworkElementKeysOutput>> getRequiredNetworkElementKeys( + GetRequiredNetworkElementKeysInput input) { + return getRequiredNetworkElementKeys(); + } + + // For casablanca version no input was generated. + public ListenableFuture<RpcResult<GetRequiredNetworkElementKeysOutput>> getRequiredNetworkElementKeys() { + + LOG.info("RPC Request: getRequiredNetworkElementKeys"); + RpcResultBuilder<GetRequiredNetworkElementKeysOutput> result; + try { + GetRequiredNetworkElementKeysOutputBuilder outputBuilder = maintenanceService.getRequiredNetworkElementKeys(); + result = RpcResultBuilder.success(outputBuilder); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + } + + @Override + public ListenableFuture<RpcResult<ShowRequiredNetworkElementOutput>> showRequiredNetworkElement( + ShowRequiredNetworkElementInput input) { + + LOG.info("RPC Request: showRequiredNetworkElement input: {}", input.getMountpointName()); + RpcResultBuilder<ShowRequiredNetworkElementOutput> result; + + try { + ShowRequiredNetworkElementOutputBuilder outputBuilder = maintenanceService.showRequiredNetworkElement(input); + result = RpcResultBuilder.success(outputBuilder); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + } + + @Override + public ListenableFuture<RpcResult<SetMaintenanceModeOutput>> setMaintenanceMode(SetMaintenanceModeInput input) { + + LOG.info("RPC Request: setMaintenanceMode input: {}", input.getNodeId()); + RpcResultBuilder<SetMaintenanceModeOutput> result; + + try { + SetMaintenanceModeOutputBuilder outputBuilder = maintenanceService.setMaintenanceMode(input); + result = RpcResultBuilder.success(outputBuilder); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + + } + + + + @Override + public ListenableFuture<RpcResult<GetMaintenanceModeOutput>> getMaintenanceMode(GetMaintenanceModeInput input) { + + LOG.info("RPC Request: getMaintenanceMode input: {}", input.getMountpointName()); + RpcResultBuilder<GetMaintenanceModeOutput> result; + + try { + GetMaintenanceModeOutputBuilder outputBuilder = maintenanceService.getMaintenanceMode(input); + result = RpcResultBuilder.success(outputBuilder); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + + } + + @Override + public ListenableFuture<RpcResult<TestMaintenanceModeOutput>> testMaintenanceMode(TestMaintenanceModeInput input) { + LOG.info("RPC Request: getMaintenanceMode input: {}", input.getMountpointName()); + RpcResultBuilder<TestMaintenanceModeOutput> result; + + try { + TestMaintenanceModeOutputBuilder outputBuilder = maintenanceService.testMaintenanceMode(input); + result = RpcResultBuilder.success(outputBuilder); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + + } + + + @Override + public ListenableFuture<RpcResult<ClearCurrentFaultByNodenameOutput>> clearCurrentFaultByNodename( + ClearCurrentFaultByNodenameInput input) { + LOG.info("RPC Request: clearNetworkElementAlarms input: {}", input.getNodenames()); + RpcResultBuilder<ClearCurrentFaultByNodenameOutput> result; + try { + if(this.resyncCallbackListener!=null) { + List<String> nodeNames= this.resyncCallbackListener.doClearCurrentFaultByNodename(input.getNodenames()); + ClearCurrentFaultByNodenameOutputBuilder outputBuilder = new ClearCurrentFaultByNodenameOutputBuilder(); + outputBuilder.setNodenames(nodeNames); + result = RpcResultBuilder.success(outputBuilder); + } else { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Startup running" ); + } + } catch(Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + } + + @Override + public ListenableFuture<RpcResult<PushFaultNotificationOutput>> pushFaultNotification( + PushFaultNotificationInput input) { + LOG.info("RPC Received fault notification {}", input); + RpcResultBuilder<PushFaultNotificationOutput> result; + try { + pushNotificationsListener.pushFaultNotification(input); + result = RpcResultBuilder.success(); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + } + + @Override + public ListenableFuture<RpcResult<PushAttributeChangeNotificationOutput>> pushAttributeChangeNotification( + PushAttributeChangeNotificationInput input) { + LOG.info("RPC Received change notification {}", input); + RpcResultBuilder<PushAttributeChangeNotificationOutput> result; + try { + pushNotificationsListener.pushAttributeChangeNotification(input); + result = RpcResultBuilder.success(); + } catch (Exception e) { + result = RpcResultBuilder.failed(); + result.withError(ErrorType.APPLICATION, "Exception", e); + } + return result.buildFuture(); + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerImpl.java new file mode 100644 index 000000000..d2f489646 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerImpl.java @@ -0,0 +1,829 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.database.config.EsConfig; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.IEntityDataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerServiceProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceMonitoredNe; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.FactoryRegistration; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetconfNetworkElementService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.NetworkElementFactory; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.UnkownDevicemanagerServiceException; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.AaiProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.archiveservice.ArchiveCleanService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementFactory; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitor; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.devicemonitor.impl.DeviceMonitorImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping.ConnectionStatusHousekeepingService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.housekeeping.ResyncNetworkElementHouskeepingService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka.AkkaConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo.GeoConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.RpcPushNotificationsHandler; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.listener.NetconfChangeListener; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.GenericTransactionUtils; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientDummyImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientImpl2; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl.MaintenanceServiceImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.PerformanceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.service.MicrowaveHistoricalPerformanceWriterService; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.INetconfAcessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfAccessor; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateService; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.MountPointService; +import org.opendaylight.mdsal.binding.api.NotificationPublishService; +import org.opendaylight.mdsal.binding.api.RpcProviderService; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus.ConnectionStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.ClusteredConnectionStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketmanagerService; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Devicemanager + * - Handles startup and closedown of network element handlers for netconf session + * - Provide common services for network element specific components + */ +public class DeviceManagerImpl implements NetconfNetworkElementService, DeviceManagerServiceProvider, NetconfNodeService, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class); + private static final String APPLICATION_NAME = "DeviceManager"; + private static final String MYDBKEYNAMEBASE = "SDN-Controller"; + private static final String CONFIGURATIONFILE = "etc/devicemanager.properties"; + public static final long DATABASE_TIMEOUT_MS = 120*1000L; + + + // http://sendateodl:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf + private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID = + InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, + new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); + @SuppressWarnings("unused") + private static final String STARTUPLOG_FILENAME = "etc/devicemanager.startup.log"; + // private static final String STARTUPLOG_FILENAME2 = "data/cache/devicemanager.startup.log"; + + // MDSAL Services + private DataBroker dataBroker; + private MountPointService mountPointService; + private RpcProviderService rpcProviderRegistry; + @SuppressWarnings("unused") + private NotificationPublishService notificationPublishService; + private ClusterSingletonServiceProvider clusterSingletonServiceProvider; + private WebsocketmanagerService websocketmanagerService; + private IEntityDataProvider iEntityDataProvider; + + // Devicemanager common services for network element handler + private @Nullable WebSocketServiceClientInternal webSocketService; + private ODLEventListenerHandler odlEventListenerHandler; + private NetconfChangeListener netconfChangeListener; + private DeviceManagerApiServiceImpl rpcApiService; + private PerformanceManagerImpl performanceManager; + private DcaeProviderClient dcaeProviderClient; + private AaiProviderClient aaiProviderClient; + private DcaeForwarderInternal aotsDcaeForwarder; + private DeviceMonitor deviceMonitor; + private MaintenanceServiceImpl maintenanceService; + private DevicemanagerNotificationDelayService notificationDelayService; + private ResyncNetworkElementHouskeepingService resyncNetworkElementHouskeepingService; + private ArchiveCleanService archiveCleanService; + private ConnectionStatusHousekeepingService housekeepingService; + private NetconfNodeStateService netconfNodeStateService; + private DataProvider dataProvider; + private HtDatabaseClient htDatabaseClient; + // Handler + private RpcPushNotificationsHandler rpcPushNotificationsHandler; + private DeviceManagerNetconfConnectHandler forTest; + private final TransactionUtils transactionUtils; + // Attributes + private final Object networkelementLock; + private final ConcurrentHashMap<String, NetworkElement> networkElementRepresentations; + private final List<MyNetworkElementFactory<? extends NetworkElementFactory>> factoryList; + private AkkaConfig akkaConfig; + private ClusterSingletonServiceRegistration cssRegistration; + private ClusterSingletonServiceRegistration cssRegistration2; + private Boolean devicemanagerInitializationOk; + + // Blueprint 1 + public DeviceManagerImpl() { + LOG.info("Creating provider for {}", APPLICATION_NAME); + this.devicemanagerInitializationOk = false; + this.factoryList = new CopyOnWriteArrayList<>(); + this.networkelementLock = new Object(); + this.networkElementRepresentations = new ConcurrentHashMap<>(); + this.transactionUtils = new GenericTransactionUtils(); + + this.dataBroker = null; + this.mountPointService = null; + this.rpcProviderRegistry = null; + this.notificationPublishService = null; + this.clusterSingletonServiceProvider = null; + this.websocketmanagerService = null; + this.iEntityDataProvider = null; + + this.webSocketService = null; + } + + public void setDataBroker(DataBroker dataBroker) { + this.dataBroker = dataBroker; + } + + public void setRpcProviderRegistry(RpcProviderService rpcProviderRegistry) { + this.rpcProviderRegistry = rpcProviderRegistry; + } + + public void setNotificationPublishService(NotificationPublishService notificationPublishService) { + this.notificationPublishService = notificationPublishService; + } + + public void setMountPointService(MountPointService mountPointService) { + this.mountPointService = mountPointService; + } + public void setClusterSingletonService(ClusterSingletonServiceProvider clusterSingletonService) { + this.clusterSingletonServiceProvider = clusterSingletonService; + } + public void setNetconfNodeStateService(NetconfNodeStateService netconfNodeStateService) { + this.netconfNodeStateService = netconfNodeStateService; + } + public void setWebsocketmanagerService(WebsocketmanagerService websocketmanagerService) { + this.websocketmanagerService = websocketmanagerService; + } + public void setEntityDataProvider(IEntityDataProvider iEntityDataProvider) { + this.iEntityDataProvider = iEntityDataProvider; + } + + public void init() throws Exception { + + LOG.info("Session Initiated start {}", APPLICATION_NAME); + this.iEntityDataProvider.setReadyStatus(false); + + // Register network element factories and related init functions + registerMyNetworkElementFactory(new ONFCoreNetworkElementFactory(), (a,b,c) -> initONFCoremodel(a,b,(ONFCoreNetworkElementRepresentation)c)); + //registerMyNetworkElementFactory(new ORanNetworkElementFactory(), (a,b,c) -> initORan(a,b,(ONFCoreNetworkElementRepresentation)c)); + //registerMyNetworkElementFactory(new NtsNetworkElementFactory(), (a,b,c) -> initNts(a,b,(ONFCoreNetworkElementRepresentation)c)); + //registerMyNetworkElementFactory(new GRanNetworkElementFactory(), (a,b,c) -> initGRan(a,b,(ONFCoreNetworkElementRepresentation)c)); + + this.dataProvider = iEntityDataProvider.getDataProvider(); // Get configuration + + ConfigurationFileRepresentation config = new ConfigurationFileRepresentation(CONFIGURATIONFILE); + + this.akkaConfig = loadClusterConfiguration(); + this.notificationDelayService = new DevicemanagerNotificationDelayService(config); + + EsConfig dbConfig = new EsConfig(config); + LOG.debug("esConfig=" + dbConfig.toString()); + // Start database + // TODO Remove this database client + this.htDatabaseClient = new HtDatabaseClient(dbConfig.getHosts()); + this.htDatabaseClient.waitForYellowStatus(DATABASE_TIMEOUT_MS); + + // start service for device maintenance service + this.maintenanceService = new MaintenanceServiceImpl(htDatabaseClient); + + // Websockets + try { + this.webSocketService = new WebSocketServiceClientImpl2(websocketmanagerService); + } catch (Exception e) { + LOG.error("Can not start websocket service. Loading mock class.", e); + this.webSocketService = new WebSocketServiceClientDummyImpl(); + } + // DCAE + this.dcaeProviderClient = new DcaeProviderClient(config, dbConfig.getCluster(), this); + + this.aaiProviderClient = new AaiProviderClient(config, this); + // EM + String myDbKeyNameExtended = MYDBKEYNAMEBASE + "-" + dbConfig.getCluster(); + + this.aotsDcaeForwarder = new DcaeForwarderImpl(null, dcaeProviderClient, maintenanceService); + this.rpcPushNotificationsHandler = new RpcPushNotificationsHandler(webSocketService, + dataProvider, aotsDcaeForwarder); + this.odlEventListenerHandler = new ODLEventListenerHandler(myDbKeyNameExtended, webSocketService, + dataProvider, aotsDcaeForwarder); + this.archiveCleanService = new ArchiveCleanService(config, dataProvider); + this.housekeepingService = new ConnectionStatusHousekeepingService(this.dataBroker, + dataProvider); + this.cssRegistration = this.clusterSingletonServiceProvider + .registerClusterSingletonService(this.archiveCleanService); + this.cssRegistration2 = this.clusterSingletonServiceProvider + .registerClusterSingletonService(this.housekeepingService); + // PM + this.performanceManager = new PerformanceManagerImpl(60, new MicrowaveHistoricalPerformanceWriterService(htDatabaseClient), config); + + // DM + // DeviceMonitor has to be available before netconfSubscriptionManager is + // configured + LOG.debug("start DeviceMonitor Service"); + this.deviceMonitor = new DeviceMonitorImpl(dataBroker, odlEventListenerHandler, config); + + // ResyncNetworkElementHouskeepingService + this.resyncNetworkElementHouskeepingService = new ResyncNetworkElementHouskeepingService( + this, mountPointService, odlEventListenerHandler, + dataProvider, deviceMonitor); + + // RPC Service for specific services + // Start RPC Service + LOG.debug("start rpc service"); + this.rpcApiService = new DeviceManagerApiServiceImpl(rpcProviderRegistry, maintenanceService, + resyncNetworkElementHouskeepingService, rpcPushNotificationsHandler); + + // netconfSubscriptionManager should be the last one because this is a callback + // service + LOG.debug("start NetconfSubscriptionManager Service"); + // this.netconfSubscriptionManager = new + // NetconfSubscriptionManagerOfDeviceManager(this, dataBroker); + // this.netconfSubscriptionManager.register(); + this.netconfChangeListener = new NetconfChangeListener(this, dataBroker); + this.netconfChangeListener.register(); + + this.forTest = new DeviceManagerNetconfConnectHandler(netconfNodeStateService); + + writeToEventLog(APPLICATION_NAME, "startup", "done"); + this.devicemanagerInitializationOk = true; + + LOG.info("Session Initiated end. Initialization done {}", devicemanagerInitializationOk); + this.iEntityDataProvider.setReadyStatus(true); + + } + + @Override + public void close() { + LOG.info("DeviceManagerImpl closing ..."); + close(performanceManager); + close(dcaeProviderClient); + close(aaiProviderClient); + close(deviceMonitor); + close(htDatabaseClient); + close(netconfChangeListener); + close(maintenanceService); + close(rpcApiService); + close(notificationDelayService); + close(archiveCleanService); + close(housekeepingService); + close(forTest); + close(cssRegistration, cssRegistration2); + LOG.info("DeviceManagerImpl closing done"); + } + + @Override + public @NonNull <L extends NetworkElementFactory> FactoryRegistration<L> registerNetworkElementFactory(@NonNull L factory) { + LOG.info("Factory registration {}", factory.getClass().getName()); + MyNetworkElementFactory<L> myFactory = new MyNetworkElementFactory<>(factory, (a,b,c) -> initDefault(a,b,c)); + factoryList.add(myFactory); + return new FactoryRegistration<L>() { + + @Override + public @NonNull L getInstance() { + return myFactory.getFactory(); + } + + @Override + public void close() { + factoryList.remove(myFactory); + } + + }; + } + + private <L extends NetworkElementFactory> void registerMyNetworkElementFactory(@NonNull L factory, + Register<String, MountPoint, NetworkElement> init) { + factoryList.add(new MyNetworkElementFactory<>(factory, init)); + } + + + @Override + public @NonNull DataProvider getDataProvider() { + return this.dataProvider; + } + + /** + * Used to close all Services, that should support AutoCloseable Pattern + * @param toClose + */ + private void close(AutoCloseable... toCloseList) { + for (AutoCloseable element : toCloseList) { + if (element != null) { + try { + element.close(); + } catch (Exception e) { + LOG.warn("Problem during close {}", e); + } + } + } + } + + /*------------------------------------------------------------------------------------------- + * Functions for interface DeviceManagerService + */ + + /** + * For each mounted device a mountpoint is created and this listener is called. + * Mountpoint was created or existing. Managed device is now fully connected to node/mountpoint. + * @param action provide action + * @param nNodeId id of the mountpoint + * @param nNode mountpoint contents + */ + public void startListenerOnNodeForConnectedState(Action action, NodeId nNodeId, NetconfNode nNode) { + + String mountPointNodeName = nNodeId.getValue(); + LOG.info("Starting Event listener on Netconf for mountpoint {} Action {}", mountPointNodeName, action); + + boolean preConditionMissing = false; + if (mountPointService == null) { + preConditionMissing = true; + LOG.warn("No mountservice available."); + } + if (!devicemanagerInitializationOk) { + preConditionMissing = true; + LOG.warn("Devicemanager initialization still pending."); + } + if (preConditionMissing) { + return; + } + + if (!isNetconfNodeMaster(nNode)) { + // Change Devicemonitor-status to connected ... for non master mountpoints. + deviceMonitor.deviceConnectSlaveIndication(mountPointNodeName); + } else { + + InstanceIdentifier<Node> instanceIdentifier = NETCONF_TOPO_IID.child(Node.class, + new NodeKey(nNodeId)); + + Optional<MountPoint> optionalMountPoint = waitForMountpoint(instanceIdentifier, mountPointNodeName); + + + if (!optionalMountPoint.isPresent()) { + LOG.warn("Event listener timeout while waiting for mount point for Netconf device :: Name : {} ", + mountPointNodeName); + } else { + // Mountpoint is present for sure + MountPoint mountPoint = optionalMountPoint.get(); + // BindingDOMDataBrokerAdapter.BUILDER_FACTORY; + LOG.info("Mountpoint with id: {} class {} toString {}", mountPoint.getIdentifier(), + mountPoint.getClass().getName(), mountPoint); + + Optional<DataBroker> optionalNetconfNodeDatabroker = mountPoint.getService(DataBroker.class); + if (!optionalNetconfNodeDatabroker.isPresent()) { + LOG.info("Slave mountpoint {} without databroker", mountPointNodeName); + } else { + + // It is master for mountpoint and all data are available. + // Make sure that specific mountPointNodeName is handled only once. + // be aware that startListenerOnNodeForConnectedState could be called multiple + // times for same mountPointNodeName. + // networkElementRepresentations contains handled NEs at master node. + + synchronized (networkelementLock) { + if (networkElementRepresentations.containsKey(mountPointNodeName)) { + LOG.warn("Mountpoint {} already registered. Leave startup procedure.", mountPointNodeName); + return; + } + } + // update db with connect status + sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode); + + DataBroker netconfNodeDataBroker = optionalNetconfNodeDatabroker.get(); + LOG.info("Master mountpoint {}", mountPointNodeName); + INetconfAcessor acessor = new NetconfAccessor(nNodeId, nNode, netconfNodeDataBroker, mountPoint, transactionUtils); + + for (MyNetworkElementFactory<? extends NetworkElementFactory> f : factoryList) { + Optional<NetworkElement> optionalNe = f.getFactory().create(acessor, this); + if (optionalNe.isPresent()) { + f.getInit().register(mountPointNodeName, mountPoint, optionalNe.get()); + break; //Use the first provided + } + } + } + } + } + } + + @SuppressWarnings("unchecked") + @Override + public @NonNull <L extends DeviceManagerService> L getService(Class<L> serviceInterface) throws UnkownDevicemanagerServiceException { + if (serviceInterface.isInstance(webSocketService)) { + return (L) this.webSocketService; + } else if (serviceInterface.isInstance(aotsDcaeForwarder)) { + return (L) this.aotsDcaeForwarder; + } else if (serviceInterface.isInstance(notificationDelayService)) { + return (L) notificationDelayService; + } + throw new UnkownDevicemanagerServiceException("Unknown service ",serviceInterface); + } + + // Deviceinitialization + + @FunctionalInterface + interface Register<X, Y, Z> { + public void register(X mountPointNodeName, Y mountPoint, Z ne); + } + + private class MyNetworkElementFactory<L extends NetworkElementFactory> { + + private final Register<String, MountPoint, NetworkElement> init; + private final @NonNull L factory; + + @SuppressWarnings("null") + public MyNetworkElementFactory(@NonNull L factory, Register<String, MountPoint, NetworkElement> init) { + super(); + if (init == null || factory == null) { + throw new IllegalArgumentException("Null not allowed here."); + } + this.init = init; + this.factory = factory; + } + public Register<String, MountPoint, NetworkElement> getInit() { + return init; + } + public @NonNull L getFactory() { + return factory; + } + } + + /** + * Execute register command, for network element + * @param mountPointNodeName of new network element + * @param mountPoint of new network element + * @param inNe that needs to register + */ + private void initDefault(String mountPointNodeName, MountPoint mountPoint, NetworkElement inNe) { + // sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode); + + // TODO + putToNetworkElementRepresentations(mountPointNodeName, inNe); + deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, inNe); + + inNe.register(); + } + + private void initONFCoremodel(String mountPointNodeName, MountPoint mountPoint, + ONFCoreNetworkElementRepresentation ne) { + putToNetworkElementRepresentations(mountPointNodeName, ne); + // create automatic empty maintenance entry into db before reading and listening + // for problems + maintenanceService.createIfNotExists(mountPointNodeName); + + // Setup microwaveEventListener for notification service + // MicrowaveEventListener microwaveEventListener = new + // MicrowaveEventListener(mountPointNodeName, websocketmanagerService, + // xmlMapper, databaseClientEvents); + + ne.doRegisterEventListener(mountPoint); + + // Register netconf stream + NetconfNotification.registerNotificationStream(mountPointNodeName, mountPoint, "NETCONF"); + + // -- Read data from NE + ne.initialReadFromNetworkElement(); + + if (aaiProviderClient != null) { + aaiProviderClient.onDeviceRegistered(mountPointNodeName); + } + // -- Register NE to performance manager + if (performanceManager != null) { + performanceManager.registration(mountPointNodeName, ne); + } + + deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, (DeviceMonitoredNe)ne); + + LOG.info("Starting Event listener finished. Added Netconf device {}", mountPointNodeName); + } + + private void initORan(String mountPointNodeName, MountPoint mountPoint, ONFCoreNetworkElementRepresentation neORan) { + // sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode); + putToNetworkElementRepresentations(mountPointNodeName, neORan); + + maintenanceService.createIfNotExists(mountPointNodeName); + + deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, (DeviceMonitoredNe)neORan); + + // -- Read data from NE + neORan.initialReadFromNetworkElement(); + neORan.doRegisterEventListener(mountPoint); + NetconfNotification.registerNotificationStream(mountPointNodeName, mountPoint, "NETCONF"); + } + + private void initNts(String mountPointNodeName, MountPoint mountPoint, ONFCoreNetworkElementRepresentation neNts) { + // sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode); + putToNetworkElementRepresentations(mountPointNodeName, neNts); + deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, (DeviceMonitoredNe)neNts); + + // -- Read data from NE + neNts.initialReadFromNetworkElement(); + } + private void initGRan(String mountPointNodeName, MountPoint mountPoint, ONFCoreNetworkElementRepresentation neGRan) { + // sendUpdateNotification(mountPointNodeName, nNode.getConnectionStatus(), nNode); + putToNetworkElementRepresentations(mountPointNodeName, neGRan); + deviceMonitor.deviceConnectMasterIndication(mountPointNodeName, (DeviceMonitoredNe)neGRan); + + // -- Read data from NE + neGRan.initialReadFromNetworkElement(); + } + /** + * @param instanceIdentifier + * @param mountPointNodeName + * @return + */ + private Optional<MountPoint> waitForMountpoint(InstanceIdentifier<Node> instanceIdentifier, + String mountPointNodeName) { + Optional<MountPoint> optionalMountPoint = null; + int timeout = 10000; + while (!(optionalMountPoint = mountPointService.getMountPoint(instanceIdentifier)).isPresent() + && timeout > 0) { + LOG.info("Event listener waiting for mount point for Netconf device :: Name : {}", mountPointNodeName); + sleepMs(1000); + timeout -= 1000; + } + return optionalMountPoint; + } + + private void putToNetworkElementRepresentations(String mountPointNodeName, NetworkElement ne) { + NetworkElement result; + synchronized (networkelementLock) { + result = networkElementRepresentations.put(mountPointNodeName, ne); + } + if (result != null) { + LOG.warn("NE list was not empty as expected, but contained {} ", result.getNodeId()); + } else { + odlEventListenerHandler.connectIndication(mountPointNodeName, ne.getDeviceType()); + } + } + + /** + * Mountpoint created or existing. Managed device is actually disconnected from node/ mountpoint. + * Origin state: Connecting, Connected + * Target state: are UnableToConnect or Connecting + * @param action create or update + * @param nNodeId id of the mountpoint + * @param nNode mountpoint contents + */ + public void enterNonConnectedState(Action action, NodeId nNodeId, NetconfNode nNode) { + String mountPointNodeName = nNodeId.getValue(); + ConnectionStatus csts = nNode.getConnectionStatus(); + if (isNetconfNodeMaster(nNode)) { + sendUpdateNotification(mountPointNodeName, csts,nNode); + } + + // Handling if mountpoint exist. connected -> connecting/UnableToConnect + stopListenerOnNodeForConnectedState(mountPointNodeName); + + deviceMonitor.deviceDisconnectIndication(mountPointNodeName); + + } + + /** + * Mountpoint removed indication. + * @param nNodeId id of the mountpoint + */ + public void removeMountpointState(NodeId nNodeId) { + String mountPointNodeName = nNodeId.getValue(); + LOG.info("mountpointNodeRemoved {}", nNodeId.getValue()); + + stopListenerOnNodeForConnectedState(mountPointNodeName); + deviceMonitor.removeMountpointIndication(mountPointNodeName); + if (odlEventListenerHandler != null) { + odlEventListenerHandler.deRegistration(mountPointNodeName); + } + } + + /** + * Do all tasks necessary to move from mountpoint state connected -> connecting + * @param mountPointNodeName provided + * @param ne representing the device connected to mountpoint + */ + private void stopListenerOnNodeForConnectedState( String mountPointNodeName) { + NetworkElement ne = networkElementRepresentations.remove(mountPointNodeName); + if (ne != null) { + this.maintenanceService.deleteIfNotRequired(mountPointNodeName); + ne.deregister(); + if (performanceManager != null) { + performanceManager.deRegistration(mountPointNodeName); + } + if (aaiProviderClient != null) { + aaiProviderClient.onDeviceUnregistered(mountPointNodeName); + } + } + } + + private void sendUpdateNotification(String mountPointNodeName, ConnectionStatus csts, NetconfNode nNode) { + LOG.info("update ConnectedState for device :: Name : {} ConnectionStatus {}", mountPointNodeName, csts); + if (odlEventListenerHandler != null) { + odlEventListenerHandler.updateRegistration(mountPointNodeName, ConnectionStatus.class.getSimpleName(), + csts != null ? csts.getName() : "null", nNode); + } + } + + /** + * Handle netconf/mountpoint changes + */ + @Override + public void netconfNodeChangeHandler(Action action, NodeId nodeId, NetconfNode nNode) { + + @Nullable ConnectionStatus csts = nNode.getConnectionStatus(); + @Nullable ClusteredConnectionStatus ccsts = nNode.getClusteredConnectionStatus(); + String nodeIdString = nodeId.getValue(); + + LOG.debug("NETCONF Node processing with id {} action {} status {} cluster status {}", nodeId, + action, csts, ccsts); + + boolean isCluster = akkaConfig == null && akkaConfig.isCluster(); + if (isCluster && ccsts == null) { + LOG.debug("NETCONF Node {} {} does not provide cluster status. Stop execution.", nodeIdString, action); + } else { + switch (action) { + case REMOVE: + removeMountpointState(nodeId); // Stop Monitor + break; + case CREATE: + if (odlEventListenerHandler != null) { + odlEventListenerHandler.registration(nodeIdString,nNode); + } + createOrUpdateMountpointState(action, csts, nodeId, nNode); + break; + case UPDATE: + createOrUpdateMountpointState(action, csts, nodeId, nNode); + break; + } + } + } + + private void createOrUpdateMountpointState(Action action, @Nullable ConnectionStatus csts, NodeId nodeId, NetconfNode nNode) { + if (csts != null) { + switch (csts) { + case Connected: { + startListenerOnNodeForConnectedState(action, nodeId, nNode); + break; + } + case UnableToConnect: + case Connecting: { + enterNonConnectedState(action, nodeId, nNode); + break; + } + } + } else { + LOG.debug("NETCONF Node handled with null status for action", action); + } + } + + /*------------------------------------------------------------------------------------------- + * Functions + */ + + public ArchiveCleanService getArchiveCleanService() { + return this.archiveCleanService; + } + + public DataProvider getDatabaseClientEvents() { + return dataProvider; + } + + @Override + public DeviceManagerServiceProvider getServiceProvider() { + return this; + } + + /** + * Indication if init() of devicemanager successfully done. + * @return true if init() was sucessfull. False if not done or not successfull. + */ + public boolean isDevicemanagerInitializationOk() { + return this.devicemanagerInitializationOk; + } + + /** + * Get NE object. Used by DCAE Service + * @param mountpoint mount point name + * @return null or NE specific data + */ + public @Nullable NetworkElement getNeByMountpoint(String mountpoint) { + + return networkElementRepresentations.get(mountpoint); + + } + + @Override + public void writeToEventLog(String objectId, String msg, String value) { + this.odlEventListenerHandler.writeEventLog(objectId, msg, value); + } + + /*--------------------------------------------------------------------- + * Private funtions + */ + + + /* -- LOG related functions -- */ + + + private boolean isInClusterMode() { + return this.akkaConfig == null ? false : this.akkaConfig.isCluster(); + } + + private String getClusterNetconfNodeName() { + return this.akkaConfig == null ? "" : this.akkaConfig.getClusterConfig().getClusterSeedNodeName("abc"); + } + + private boolean isNetconfNodeMaster(NetconfNode nNode) { + if (isInClusterMode()) { + LOG.debug("check if me is responsible for node"); + String masterNodeName = null; + ClusteredConnectionStatus ccst = nNode.getClusteredConnectionStatus(); + if (ccst != null) { + masterNodeName = ccst.getNetconfMasterNode(); + } + if (masterNodeName == null) { + masterNodeName = "null"; + } + + String myNodeName = getClusterNetconfNodeName(); + LOG.debug("sdnMasterNode=" + masterNodeName + " and sdnMyNode=" + myNodeName); + if (!masterNodeName.equals(myNodeName)) { + LOG.debug("netconf change but me is not master for this node"); + return false; + } + } + return true; + } + + private static AkkaConfig loadClusterConfiguration() { + AkkaConfig akkaConfigRes; + try { + akkaConfigRes = AkkaConfig.load(); + LOG.debug("akka.conf loaded: " + akkaConfigRes.toString()); + } catch (Exception e1) { + akkaConfigRes = null; + LOG.warn("problem loading akka.conf: " + e1.getMessage()); + } + @SuppressWarnings("unused") + GeoConfig geoConfig = null; + if (akkaConfigRes != null && akkaConfigRes.isCluster()) { + LOG.info("cluster mode detected"); + if (GeoConfig.fileExists()) { + try { + LOG.debug("try to load geoconfig"); + geoConfig = GeoConfig.load(); + } catch (Exception err) { + LOG.warn("problem loading geoconfig: " + err.getMessage()); + } + } else { + LOG.debug("no geoconfig file found"); + } + } else { + LOG.info("single node mode detected"); + } + return akkaConfigRes; + } + + private void sleepMs(int milliseconds) { + try { + Thread.sleep(milliseconds); + } catch (InterruptedException e) { + LOG.debug("Interrupted sleep"); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerNetconfConnectHandler.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerNetconfConnectHandler.java new file mode 100644 index 000000000..2c164d826 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DeviceManagerNetconfConnectHandler.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeConnectListener; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateService; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DeviceManagerNetconfConnectHandler implements NetconfNodeConnectListener { + + private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerNetconfConnectHandler.class); + + private ListenerRegistration<DeviceManagerNetconfConnectHandler> registerNetconfNodeConnectListener; + + public DeviceManagerNetconfConnectHandler(@Nullable NetconfNodeStateService netconfNodeStateService) { + if (netconfNodeStateService == null) { + registerNetconfNodeConnectListener = new ListenerRegistration<DeviceManagerNetconfConnectHandler>() { + @Override + public void close() { + } + @Override + public @NonNull DeviceManagerNetconfConnectHandler getInstance() { + return DeviceManagerNetconfConnectHandler.this; + } + }; + } else { + this.registerNetconfNodeConnectListener = netconfNodeStateService.registerNetconfNodeConnectListener(this); + } + } + + @Override + public void onEnterConnected(NodeId nNodeId, NetconfNode netconfNode, DataBroker netconfNodeDataBroker) { + LOG.info("onEnterConnected {}", nNodeId); + //o-ran-interfaces .. spec for RAN Devices to be used as fingerprint + } + + @Override + public void onLeaveConnected(NodeId nNodeId) { + LOG.info("onLeaveConnected {}", nNodeId); + } + + @Override + public void close() throws Exception { + registerNetconfNodeConnectListener.close(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DevicemanagerNotificationDelayService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DevicemanagerNotificationDelayService.java new file mode 100644 index 000000000..25f55046b --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/DevicemanagerNotificationDelayService.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayService; + +/** + * Devicemanager service + */ +public class DevicemanagerNotificationDelayService extends NotificationDelayService<ProblemNotificationXml> implements DeviceManagerService { + + public DevicemanagerNotificationDelayService(ConfigurationFileRepresentation htconfig) { + super(htconfig); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/LinkIdentifyingObject.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/LinkIdentifyingObject.java new file mode 100644 index 000000000..8c9ca564f --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/LinkIdentifyingObject.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +public interface LinkIdentifyingObject { + + public String getSignalId(); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNodeService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNodeService.java new file mode 100644 index 000000000..5ce8a0d69 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNodeService.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; + +public interface NetconfNodeService { + + public enum Action { + CREATE, + REMOVE, + UPDATE + } + + /** + * MountpointChangeHandler, called to indicate change to DeviceManager + * @param action provided + * @param csts provided + * @param nodeId provided + * @param nnode provided + */ + void netconfNodeChangeHandler(Action action, NodeId nodeId, NetconfNode nnode); +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNotification.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNotification.java new file mode 100644 index 000000000..ac4b8565e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/NetconfNotification.java @@ -0,0 +1,69 @@ +/** + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import java.util.Optional; +import javax.annotation.Nonnull; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInputBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.NotificationsService; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NetconfNotification { + + private static final Logger log = LoggerFactory.getLogger(DeviceManagerImpl.class); + + /** + * Do the stream creation for the device. + * @param nodeId node-id of device + * @param mountpoint information + * @param streamName to register + */ + public static void registerNotificationStream(String nodeId, MountPoint mountpoint, String streamName) { + + final Optional<RpcConsumerRegistry> optionalRpcConsumerService = + mountpoint.getService(RpcConsumerRegistry.class); + if (optionalRpcConsumerService.isPresent()) { + final RpcConsumerRegistry rpcConsumerRegitry = optionalRpcConsumerService.get(); + @Nonnull + final NotificationsService rpcService = rpcConsumerRegitry.getRpcService(NotificationsService.class); + + final CreateSubscriptionInputBuilder createSubscriptionInputBuilder = new CreateSubscriptionInputBuilder(); + createSubscriptionInputBuilder.setStream(new StreamNameType(streamName)); + log.info("Event listener triggering notification stream {} for node {}", streamName, nodeId); + try { + CreateSubscriptionInput createSubscriptionInput = createSubscriptionInputBuilder.build(); + if (createSubscriptionInput == null) { + log.warn("createSubscriptionInput is null for mountpoint {}", nodeId); + } else { + rpcService.createSubscription(createSubscriptionInput); + } + } catch (NullPointerException e) { + log.warn("createSubscription failed"); + } + } else { + log.warn("No RpcConsumerRegistry avaialble."); + } + + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/ProviderClient.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/ProviderClient.java new file mode 100644 index 000000000..922b8a0e0 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/ProviderClient.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; + +public interface ProviderClient extends AutoCloseable { + + /** + * Send out problem notification, that was created by a device/ or NE + * @param mountPointName related + * @param notification xml description + */ + public void sendProblemNotification(String mountPointName, ProblemNotificationXml notification); + + /** + * Send out problem notification + * @param mountPointName related + * @param notification xml description + * @param neDeviceAlarm true indicates an NE originated alarm, false an sdncontroller generated alarm + */ + public void sendProblemNotification(String mountPointName, ProblemNotificationXml notification, boolean neDeviceAlarm); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/PushNotifications.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/PushNotifications.java new file mode 100644 index 000000000..2acefc166 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/PushNotifications.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl; + +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushAttributeChangeNotificationInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushFaultNotificationInput; + +public interface PushNotifications { + + void pushAttributeChangeNotification(PushAttributeChangeNotificationInput input); + + void pushFaultNotification(PushFaultNotificationInput input); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/AkkaConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/AkkaConfig.java new file mode 100644 index 000000000..7e54881ed --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/AkkaConfig.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka; + +import java.io.File; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; + +public class AkkaConfig { + + @SuppressWarnings("unused") + private static final Logger LOG = LoggerFactory.getLogger(AkkaConfig.class); + + private static final String DEFAULT_FILENAME = "configuration/initial/akka.conf"; + private final String filename; + private ClusterConfig cluserConfig; + + public ClusterConfig getClusterConfig() { + return this.cluserConfig; + } + + private AkkaConfig(String filename) { + this.filename = filename; + } + + public AkkaConfig() { + this(null); + } + + @Override + public String toString() { + return "AkkaConfig [filename=" + filename + ", cluserConfig=" + cluserConfig + "]"; + } + + private void loadFromFile() throws Exception { + Config cfg = ConfigFactory.parseFile(new File(this.filename)); + this.cluserConfig = new ClusterConfig(cfg.getConfig("odl-cluster-data").getConfig("akka").getConfig("cluster")); + } + + public boolean isCluster() { + return this.cluserConfig != null ? this.cluserConfig.isCluster() : false; + } + + public boolean isClusterAndFirstNode() { + return isSingleNode() || isCluster() && getClusterConfig().getRoleMemberIndex() == 1; + } + + public static AkkaConfig load() throws Exception { + return load(DEFAULT_FILENAME); + } + + public static AkkaConfig load(String filename) throws Exception { + AkkaConfig cfg = new AkkaConfig(filename); + cfg.loadFromFile(); + return cfg; + } + + public boolean isSingleNode() { + return !this.isCluster(); + } + public static AkkaConfig parse(String content) throws Exception { + Config cfg = ConfigFactory.parseString(content); + AkkaConfig c = new AkkaConfig(); + c.cluserConfig=new ClusterConfig(cfg.getConfig("odl-cluster-data").getConfig("akka").getConfig("cluster")); + return c; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterConfig.java new file mode 100644 index 000000000..c6c8c1533 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterConfig.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo.ClusterRoleInfo; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo.ClusterRoleInfoCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.typesafe.config.Config; + +public class ClusterConfig { + + private static final Logger LOG = LoggerFactory.getLogger(ClusterConfig.class); + + private final List<ClusterNodeInfo> seedNodes; + private final ClusterRoleInfoCollection roles; + private ClusterNodeInfo ismeInfo; + + public static ClusterConfig defaultSingleNodeConfig() + { + ClusterConfig cfg=new ClusterConfig(); + cfg.ismeInfo=ClusterNodeInfo.defaultSingleNodeInfo(); + cfg.seedNodes.add(cfg.ismeInfo); + cfg.roles.add(ClusterRoleInfo.defaultSingleNodeRole()); + return cfg; + } + public ClusterConfig() + { + this.seedNodes = new ArrayList<>(); + this.roles = new ClusterRoleInfoCollection(); + + } + public ClusterConfig(Config o) throws Exception { + { + this.seedNodes = new ArrayList<>(); + this.roles = new ClusterRoleInfoCollection(); + List<String> a = o.getStringList("seed-nodes"); + for (int i = 0; i < a.size(); i++) { + ClusterNodeInfo info = new ClusterNodeInfo(a.get(i)); + this.seedNodes.add(info); + } + a = o.getStringList("roles"); + for (int i = 0; i < a.size(); i++) { + ClusterRoleInfo s = new ClusterRoleInfo(a.get(i)); + this.roles.add(s); + } + int idx = this.roles.get(0).getIndex() - 1; + if (idx >= 0 && idx < this.seedNodes.size()) { + this.ismeInfo = this.seedNodes.get(idx); + } else { + this.ismeInfo = null; + } + } + + } + + public boolean isCluster() { + return this.seedNodes != null ? this.seedNodes.size() > 1 : false; + } + + public boolean isMe(ClusterNodeInfo i) { + return this.ismeInfo != null ? this.ismeInfo.equals(i) : false; + } + + public List<ClusterNodeInfo> getSeedNodes() { + return this.seedNodes; + } + + public String getHostName(String defaultValue) { + if (getRoleMemberIndex() > 0 && getRoleMemberIndex() <= seedNodes.size()) { + return this.seedNodes.get(getRoleMemberIndex()-1).getRemoteAddress(); + } else { + LOG.warn("Seednode not available for roleMemberIndex {}. Using default {}",getRoleMember(), defaultValue); + return defaultValue; + } + } + + public String getDBClusterName(String defaultValue) { + String r = null; + if (this.seedNodes != null && this.seedNodes.size() > 0) { + r = String.format("cluster-%s.%d", this.seedNodes.get(0).getRemoteAddress(), this.seedNodes.get(0).getPort()); + } + if (r == null || r.isEmpty()) { + r = defaultValue; + } + return r; + } + public String getClusterSeedNodeName() { + return this.getClusterSeedNodeName(""); + } + public String getClusterSeedNodeName(String defaultValue) { + int idx=this.getRoleMemberIndex()-1; + String r=null; + if(this.seedNodes!=null && idx>=0 && this.seedNodes.size()>0 && this.seedNodes.size()>idx) + { + r=this.seedNodes.get(idx).getSeedNodeName(); + } + if (r == null || r.isEmpty()) { + r = defaultValue; + } + return r; + } + public int getRoleMemberIndex() { + + ClusterRoleInfo role=this.roles.get("member"); + return role!=null?role.getIndex():0; + } + public ClusterRoleInfo getRoleMember() { + return this.roles.get("member"); + } + + @Override + public String toString() { + return "ClusterConfig [seedNodes=" + seedNodes + ", roles=" + roles + ", ismeInfo=" + ismeInfo + "]"; + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterNodeInfo.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterNodeInfo.java new file mode 100644 index 000000000..7bc015fed --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlAkka/ClusterNodeInfo.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClusterNodeInfo { + private final String protocol; + private final String clusterName; + private final String remoteAdr; + private final int port; + private final String seedNodeName; + + public static ClusterNodeInfo defaultSingleNodeInfo() { + return new ClusterNodeInfo("akka.tcp","opendaylight-cluster-data","127.0.0.1",2550); + } + + public ClusterNodeInfo(String s) throws Exception { + final String regex = "([a-z.]*):\\/\\/([a-zA-Z0-9-]*)@([a-zA-Z0-9.-]*):([0-9]*)"; + final Pattern pattern = Pattern.compile(regex); + final Matcher matcher = pattern.matcher(s); + if (!matcher.find()) { + throw new Exception("invalid seedNode format"); + } + this.seedNodeName = matcher.group(); + this.protocol = matcher.group(1); + this.clusterName = matcher.group(2); + this.remoteAdr = matcher.group(3); + this.port = Integer.parseInt(matcher.group(4)); + } + + public ClusterNodeInfo(String protocol, String clustername, String remoteadr, int port) { + this.protocol=protocol; + this.clusterName=clustername; + this.remoteAdr=remoteadr; + this.port=port; + this.seedNodeName=this.protocol+"://"+this.clusterName+"@"+this.remoteAdr+":"+this.port; + } + + public String getProtocol() { + return protocol; + } + + public String getClusterName() { + return clusterName; + } + + public String getRemoteAddress() { + return remoteAdr; + } + public String getSeedNodeName() { + return seedNodeName; + } + + public int getPort() { + return port; + } + + @Override + public String toString() { + return "ClusterNodeInfo [protocol=" + protocol + ", clusterName=" + clusterName + ", remoteAdr=" + remoteAdr + + ", port=" + port + ", seedNodeName=" + seedNodeName + "]"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfo.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfo.java new file mode 100644 index 000000000..9a9793b89 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfo.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClusterRoleInfo { + private final String Role; + private final int Index; + + public ClusterRoleInfo(String s) throws Exception { + final String regex = "([a-zA-Z]*)-([0-9]*)"; + final Pattern pattern = Pattern.compile(regex); + final Matcher matcher = pattern.matcher(s); + if (!matcher.find()) { + throw new Exception("unexpected role format:"+s); + } + this.Role = matcher.group(1); + this.Index = Integer.parseInt(matcher.group(2)); + } + + private ClusterRoleInfo(String role, int idx) { + this.Role=role; + this.Index=idx; + } + + public static ClusterRoleInfo defaultSingleNodeRole() { + return new ClusterRoleInfo("member",1); + } + + public String getRole() { + return Role; + } + public int getIndex() { + return Index; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Index; + result = prime * result + (Role == null ? 0 : Role.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; + } + ClusterRoleInfo other = (ClusterRoleInfo) obj; + if (Index != other.Index) { + return false; + } + if (Role == null) { + if (other.Role != null) { + return false; + } + } else if (!Role.equals(other.Role)) { + return false; + } + return true; + } + @Override + public String toString() { + return "ClusterRoleInfo [Role=" + Role + ", Index=" + Index + "]"; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfoCollection.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfoCollection.java new file mode 100644 index 000000000..089bf33f2 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/ClusterRoleInfoCollection.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo; + +import java.util.ArrayList; + +public class ClusterRoleInfoCollection extends ArrayList<ClusterRoleInfo> { + private static final long serialVersionUID = 1L; + + public ClusterRoleInfo get(String role) { + for (ClusterRoleInfo info : this) { + if (info.getRole().equals(role)) { + return info; + } + } + return null; + } + + public boolean contains(ClusterRoleInfo info) { + if (info == null) { + return false; + } + for (ClusterRoleInfo i : this) { + if (i.equals(info)) { + return true; + } + } + return false; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/GeoConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/GeoConfig.java new file mode 100644 index 000000000..25e7fe265 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/conf/odlGeo/GeoConfig.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; + +public class GeoConfig { + + private static final String DEFAULT_FILENAME = "configuration/initial/geo.conf"; + private static final String LUMINA_ROOTNODENAME = "lumina-geo-cluster"; + private final String filename; + private final String rootNodename; + private ClusterRoleInfoCollection primaryRoles; + private ClusterRoleInfoCollection secondayRoles; + private RolesTable rolesTable; + + private GeoConfig() { + this(null); + } + + private GeoConfig(String filename) { + this(filename, LUMINA_ROOTNODENAME); + } + + private GeoConfig(String filename, String rootNodeName) { + this.filename = filename; + this.rootNodename = rootNodeName; + } + + public static boolean fileExists() { + File f = new File(DEFAULT_FILENAME); + return f.exists(); + } + + public static GeoConfig load() throws Exception { + return load(DEFAULT_FILENAME); + } + + public static GeoConfig load(String filename) throws Exception { + GeoConfig cfg = new GeoConfig(filename); + cfg._load(); + return cfg; + } + + private void _load() throws Exception { + this._load(ConfigFactory.parseFile(new File(this.filename))); + } + + private void _load(Config cfg) throws Exception { + this.primaryRoles = new ClusterRoleInfoCollection(); + List<String> a = cfg.getConfig(this.rootNodename).getStringList("primary_roles"); + + for (int i = 0; i < a.size(); i++) { + ClusterRoleInfo s = new ClusterRoleInfo(a.get(i)); + this.primaryRoles.add(s); + } + this.secondayRoles = new ClusterRoleInfoCollection(); + a = cfg.getConfig(this.rootNodename).getStringList("secondary_roles"); + for (int i = 0; i < a.size(); i++) { + ClusterRoleInfo s = new ClusterRoleInfo(a.get(i)); + this.secondayRoles.add(s); + } + this.checkDuplicateRoleEntries(); + this.rolesTable = new RolesTable(cfg.getConfig(this.rootNodename).getConfigList("ip_roles_table")); + } + + private void checkDuplicateRoleEntries() throws Exception { + ClusterRoleInfoCollection duplicateEntries = new ClusterRoleInfoCollection(); + for (ClusterRoleInfo primaryRole : this.primaryRoles) { + if (this.secondayRoles.contains(primaryRole)) { + duplicateEntries.add(primaryRole); + } + } + if (duplicateEntries.size() > 0) { + throw new Exception("duplicate entries found: " + duplicateEntries.toString()); + } + + } + + public static GeoConfig parse(String content) throws Exception { + GeoConfig cfg = new GeoConfig(); + cfg._load(ConfigFactory.parseString(content)); + return cfg; + } + + public ClusterRoleInfoCollection getPrimaryRoles() { + return this.primaryRoles; + } + + public ClusterRoleInfoCollection getSecondaryRoles() { + return this.secondayRoles; + } + + public boolean isPrimary(ClusterRoleInfo roleMember) { + return !this.isSecondary(roleMember); + } + + private boolean isSecondary(ClusterRoleInfo roleMember) { + if (roleMember == null) { + return false; + } + for (ClusterRoleInfo info : this.secondayRoles) { + if (info.equals(roleMember)) { + return true; + } + } + return false; + } + + @Override + public String toString() { + return "GeoConfig [filename=" + filename + ", rootNodename=" + rootNodename + ", primaryRoles=" + primaryRoles + + ", secondayRoles=" + secondayRoles + ", rolesTable=" + rolesTable + "]"; + } + + public static class RolesTableEntry { + private final ClusterRoleInfo role; + private final String ip; + + public RolesTableEntry(Config c) throws Exception { + this.role = new ClusterRoleInfo(c.getString("role")); + this.ip = c.getString("ip"); + } + + @Override + public String toString() { + return "RolesTableEntry [role=" + role + ", ip=" + ip + "]"; + } + } + public static class RolesTable extends ArrayList<RolesTableEntry> { + private static final long serialVersionUID = -9146218864237487506L; + + public RolesTable(List<? extends Config> configList) throws Exception { + for (Config c : configList) { + this.add(new RolesTableEntry(c)); + } + } + + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/FaultEntityManager.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/FaultEntityManager.java new file mode 100644 index 000000000..5b7057b81 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/FaultEntityManager.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Fault; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultcurrentEntity; + +public class FaultEntityManager { + + private static final Pattern pattern = Pattern.compile(".*\\[layerProtocol=(.*)\\]"); + + /** + * The leading indication for notification or events that are not in the + * currentProblem data of the ONF Coremodel + */ + private static final String NOCURRENTPROBLEMINDICATION = "#"; + + /** + * Specific problems are not moving into current problem list + * @param problemName to be verified + * @return true if problem is current + */ + public static boolean isManagedAsCurrentProblem(String problemName) { + return ! problemName.startsWith(NOCURRENTPROBLEMINDICATION); + } + + public static boolean isManagedAsCurrentProblem(Fault problem) { + return isManagedAsCurrentProblem(problem.getProblem()); + } + + /** + * Specific problems are not moving into current problem list + * @param fault to be verified + * @return true if cleared indication + */ + public static boolean isNoAlarmIndication(Fault fault) { + InternalSeverity severity = InternalSeverity.valueOf(fault.getSeverity()); + return severity.isNoAlarmIndication(); + } + + /** + * Create a specific ES id for the current log. + * @return a string with the generated ES Id + */ + public static String genSpecificEsId(String nodeName, String objectId, String problemName) { + + String uuId; + + Matcher matcher = pattern.matcher(objectId); + if (matcher.matches() && matcher.groupCount() == 1) { + uuId = matcher.group(1); + } else { + uuId = objectId; + } + + StringBuffer strBuf = new StringBuffer(); + strBuf.append(nodeName); + strBuf.append("/"); + strBuf.append(uuId); + strBuf.append("/"); + strBuf.append(problemName); + return strBuf.toString(); + } + + /** + * Create Es id + * @param fault used to create uuid for faultcurrent + * @return String with Id + */ + public static String genSpecificEsId(FaultcurrentEntity fault) { + return genSpecificEsId(fault.getNodeId(), fault.getObjectId(), fault.getProblem()); + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtDataBaseReaderAndWriter.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtDataBaseReaderAndWriter.java new file mode 100644 index 000000000..919156b20 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtDataBaseReaderAndWriter.java @@ -0,0 +1,258 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database; + +import java.util.Collection; +import java.util.List; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.common.database.DatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.common.database.IsEsObject; +import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; +import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Generic class to write lists of model classes to the database. + * + */ +public class HtDataBaseReaderAndWriter<T extends IsEsObject> { + + private static final Logger log = LoggerFactory.getLogger(HtDataBaseReaderAndWriter.class); + + + private final DatabaseClient db; + private final String dataTypeName; + private final HtMapper<T> mapper; + + /** + * Class specific access to database + * @param db ES database descriptor + * @param dataTypeName datatype name + * @param clazz class of datatype + */ + public HtDataBaseReaderAndWriter(DatabaseClient db, String dataTypeName, Class<? extends T> clazz) { + + this.db = db; + this.dataTypeName = dataTypeName; + this.mapper = new HtMapper<>( clazz ); + + } + public boolean isExistsIndex() { + return this.db.isExistsIndex(this.dataTypeName); + } + /** + * @return dataTypeName + */ + public String getDataTypeName() { + return this.dataTypeName; + } + /** + * Remove Object from database + * @param object Object with content + * @return true if remove is done + */ + public boolean doRemove( T object) { + + return db.doRemove(dataTypeName, object ); + + } + + /** + * Remove all data that match the filter + * @param query to specify data to be deleted + * @return number of removed objects + */ + public int doRemoveByQuery(QueryBuilder query) { + + int idx = 0; //Idx for getAll + int iterateLength = 100; //Step width for iterate + + List<SearchHit> hits; + do { + hits = db.doReadByQueryJsonData( dataTypeName, query).getHits(); + log.debug("Found: {} elements: {} Failures: {}",dataTypeName,hits.size(), mapper.getMappingFailures()); + + T object; + idx += hits.size(); + for (SearchHit hit : hits) { + + object = mapper.getObjectFromJson( hit.getSourceAsString() ); + + log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures()); + if (object != null) { + object.setEsId( hit.getId() ); + doRemove(object); + } else { + log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString()); + } + } + } while (hits.size() == iterateLength); //Do it until end indicated, because less hits than iterateLength allows. + + return idx; + } + + /** + * Do the mapping for test purpose + * @param object object for test purpose + * @return json String + */ + public String getJson( T object ) { + String json = mapper.objectToJson(object); + return json; + } + + /** + * Write one object into Database + * @param object Object with content + * @return This object for chained call pattern. + */ + public T doWrite( T object) { + + String json = mapper.objectToJson(object); + return doWrite(object, json); + + } + + /** + * Write one object into Database + * @param object Object with content + * @param json string + * @return This object for chained call pattern. + */ + public T doWrite( T object, String json) { + + log.debug("doWrite {} {}",object.getClass().getSimpleName(), object.getEsId()); + + if (json != null) { + String esId = db.doWriteJsonString(dataTypeName, object, json); + object.setEsId(esId); + log.debug("doWrite done for {} {}",object.getClass().getSimpleName(), object.getEsId()); + return esId == null ? null : object; + } else { + log.warn("Can not map object and write to database. {} {}",object.getClass().getSimpleName(), object); + return null; + } + + } + + + /** + * Write a list of Objects to the database. + * @param list Object list with content + * @return This object for chained call pattern. + */ + public HtDataBaseReaderAndWriter<T> doWrite( Collection<T> list) { + + int writeError = 0; + log.debug("Write to ES database {} Class: {} {} elements",dataTypeName, mapper.getClazz().getSimpleName(), list.size()); + + if (list != null && !list.isEmpty()) { + for( T s : list ) { + if ( doWrite(s) == null ) { + if ( ++writeError > 5 ) { + log.warn("Leave because of to >5 write errors"); + break; + } + } + } + } + + return this; + } + + /** + * Read one object via the object class specific ID + * @param object Object refrenced by idString + * @return The Object if found or null + */ + public @Nullable T doRead( IsEsObject object ) { + T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, object) ); + if (res != null) { + res.setEsId(object.getEsId()); + } + return res; + } + + /** + * Read one object via the object class specific ID + * @param objectEsId Object refrence + * @return The Object if found or null + */ + public @Nullable T doRead( String objectEsId ) { + T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, objectEsId ) ); + if (res != null) { + res.setEsId(objectEsId); + } + return res; + } + /** + * Get all elements of related type + * @return all Elements + */ + public SearchResult<T> doReadAll() { + return doReadAll(null); + } + + /** + * Read all existing objects of a type + * @param query for the elements + * @return the list of all objects + */ + + public SearchResult<T> doReadAll(QueryBuilder query) { + + SearchResult<T> res = new SearchResult<>(); + int idx = 0; //Idx for getAll + int iterateLength = 100; //Step width for iterate + + SearchResult<SearchHit> result; + List<SearchHit> hits; + do { + if(query!=null) { + log.debug("read data in {} with query {}",dataTypeName,query.toJSON()); + result=db.doReadByQueryJsonData( dataTypeName, query); + } + else { + result = db.doReadAllJsonData( dataTypeName); + } + hits=result.getHits(); + log.debug("Read: {} elements: {} Failures: {}",dataTypeName,hits.size(), mapper.getMappingFailures()); + + T object; + idx += result.getHits().size(); + for (SearchHit hit : hits) { + +// object = mapper.getObjectFromJson( hit.getSourceRef() ); + object = mapper.getObjectFromJson( hit.getSourceAsString() ); + + log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures()); + if (object != null) { + object.setEsId( hit.getId() ); + res.add( object ); + } else { + log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString()); + } + } + } while (hits.size() == iterateLength); //Do it until end indicated, because less hits than iterateLength allows. + res.setTotal(idx); + return res; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtMapper.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtMapper.java new file mode 100644 index 000000000..dc2e4d768 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/HtMapper.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import java.io.IOException; +import org.eclipse.jdt.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Herbert + * + */ +public class HtMapper<T> { + + private static final Logger log = LoggerFactory.getLogger(HtMapper.class); + + private final Class<? extends T> clazz; + + private final JsonMapperBase objectMapperRead; + private final JsonMapperBase objectMapperWrite; + + private int mappingFailures; + + public HtMapper(Class<? extends T> clazz) { + + this.mappingFailures = 0; + this.clazz = clazz; + + this.objectMapperRead = new JsonMapperBase(); + this.objectMapperWrite = this.objectMapperRead; + } + + public Class<? extends T> getClazz() { + return clazz; + } + + public int getMappingFailures() { + return mappingFailures; + } + + public String objectToJson(T object) { + return objectMapperWrite.objectToJson(object); + } + + /** + * Do the mapping from Json to class Block further mapping if there is are to + * many failures + * + * @param json String with Objects JSON representation + * @return The Object + */ + public @Nullable T getObjectFromJson(byte[] json) { + + if (json == null) { + return null; + } else if (mappingFailures < 10) { + try { + T object = objectMapperRead.readValue(json, clazz); + return object; + } catch (JsonParseException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (JsonMappingException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (IOException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (Exception e) { + mappingFailures++; + log.warn(e.toString()); + } + } + log.warn("Problems parsing : {} {}", clazz, json); + return null; + } + + /** + * Do the mapping from Json to class Block further mapping if there is are to + * many failures + * + * @param json String with Objects JSON representation + * @return The Object + */ + public @Nullable T getObjectFromJson(String json) { + + if (json == null) { + return null; + } else if (mappingFailures < 10) { + try { + T object = objectMapperRead.readValue(json, clazz); + return object; + } catch (JsonParseException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (JsonMappingException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (IOException e) { + mappingFailures++; + log.warn(e.toString()); + } catch (Exception e) { + mappingFailures++; + log.warn(e.toString()); + } + } + log.warn("Problems parsing : {} {}", clazz, json); + return null; + } + + public void setSerializationInclusion(Include incl) { + this.objectMapperRead.setSerializationInclusion(incl); + + } + public void resetSerializationInclusion() { + this.objectMapperRead.setSerializationInclusion(Include.USE_DEFAULTS); + + + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/JsonMapperBase.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/JsonMapperBase.java new file mode 100644 index 000000000..848004b39 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/database/JsonMapperBase.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonGenerator.Feature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +/** + * This class is used to define default for JSON Serialization and Deserialization for the project at a single place + */ +public class JsonMapperBase extends ObjectMapper { + + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(JsonMapperBase.class); + + public JsonMapperBase() { + + setVisibility(PropertyAccessor.ALL, Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + + // Deserialization + configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); + + // Serialization + configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + getFactory().configure(Feature.ESCAPE_NON_ASCII, true); + } + + public JsonMapperBase(int t) { + + switch(t) { + case 0: + break; + case 1: + setVisibility(PropertyAccessor.ALL, Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, Visibility.DEFAULT); + break; + case 2: + setVisibility(PropertyAccessor.ALL, Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, Visibility.PROTECTED_AND_PUBLIC); + break; + case 3: + setVisibility(PropertyAccessor.ALL, Visibility.NONE); + setVisibility(PropertyAccessor.GETTER, Visibility.ANY); + setVisibility(PropertyAccessor.IS_GETTER, Visibility.ANY); + break; + default: + setVisibility(PropertyAccessor.ALL, Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + break; + + } + + // Deserialization + configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); + + // Serialization + configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + getFactory().configure(Feature.ESCAPE_NON_ASCII, true); + } + + + + public String objectToJson( Object object ) { + String res = null; + + try { + + res = writeValueAsString(object); + + } catch (JsonGenerationException e) { + LOG.debug(e.toString()); + } catch (JsonMappingException e) { + LOG.debug(e.toString()); + } catch (IOException e) { + LOG.debug(e.toString()); + } catch (Exception e) { + LOG.debug(e.toString()); + } + + return res; + } + + public String objectListToJson( List<? extends Object> objectList ) { + String res = null; + + try { + + StringWriter stringEmp = new StringWriter(); + writeValue(stringEmp, objectList); + res = stringEmp.toString(); + stringEmp.close(); + + } catch (JsonGenerationException e) { + LOG.debug(e.toString()); + } catch (JsonMappingException e) { + LOG.debug(e.toString()); + } catch (IOException e) { + LOG.debug(e.toString()); + } catch (Exception e) { + LOG.debug(e.toString()); + } + + return res; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/NetconfEventListenerHandler12.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/NetconfEventListenerHandler12.java new file mode 100644 index 000000000..e0560cb1e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/NetconfEventListenerHandler12.java @@ -0,0 +1,174 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler; + +import java.util.List; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElement12Equipment; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementCallback; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.wrapperc.OnfMicrowaveModelNotification; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayFilter; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationDelayedListener; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Important: Websocket notification must be the last action. + * At the beginning intended to handle notifications of type <code>OnfMicrowaveModelNotification</code>. + * Today an abstract class for processing notifications independent of model. + * + * @author herbert + */ +public class NetconfEventListenerHandler12 implements OnfMicrowaveModelNotification, NotificationDelayedListener<ProblemNotificationXml> { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfEventListenerHandler12.class); + + private final String nodeName; + private final WebSocketServiceClientInternal webSocketService; + //private final WebsocketmanagerService websocketmanagerService; + //private final XmlMapper xmlMapper; + private final DataProvider databaseService; + private final DcaeForwarderInternal dcaeForwarder; + + private final NotificationDelayFilter<ProblemNotificationXml> delayFilter; + private final ONFCoreNetworkElementCallback ne; + + public NetconfEventListenerHandler12(String nodeName, WebSocketServiceClientInternal webSocketService, + DataProvider databaseService, DcaeForwarderInternal aotsDcaeForwarder, + NotificationDelayService<ProblemNotificationXml> notificationDelayService, + ONFCoreNetworkElementCallback ne) { + super(); + this.nodeName = nodeName; + //this.websocketmanagerService = websocketmanagerService; + //this.xmlMapper = xmlMapper; + this.webSocketService = webSocketService; + this.databaseService = databaseService; + this.dcaeForwarder = aotsDcaeForwarder; + this.delayFilter=notificationDelayService.getInstance(nodeName, this);//12(nodeName,this); + this.ne = ne; + } + + + @Override + public void onAttributeValueChangedNotification(AttributeValueChangedNotificationXml notificationXml) { + + ne.notificationFromNeListener(notificationXml); + + databaseService.writeEventLog(notificationXml.getEventlogEntity()); + webSocketService.sendViaWebsockets(nodeName, notificationXml); + } + + + @Override + public void onObjectCreationNotification(ObjectCreationNotificationXml notificationXml) { + + databaseService.writeEventLog(notificationXml.getEventlogEntity()); + webSocketService.sendViaWebsockets(nodeName, notificationXml); + + } + + @Override + public void onObjectDeletionNotification(ObjectDeletionNotificationXml notificationXml) { + + databaseService.writeEventLog(notificationXml.getEventlogEntity()); + webSocketService.sendViaWebsockets(nodeName, notificationXml); + } + + @Override + public void onProblemNotification(ProblemNotificationXml notificationXml) { + + databaseService.writeFaultLog(notificationXml.getFaultlog(SourceType.Netconf)); + databaseService.updateFaultCurrent(notificationXml.getFaultcurrent()); + + // ToggleAlarmFilter functionality + if (delayFilter.processNotification(notificationXml.getSeverity() == InternalSeverity.NonAlarmed, notificationXml.getProblem(), notificationXml)) + { + dcaeForwarder.sendProblemNotificationUsingMaintenanceFilter(this.nodeName, notificationXml); + // end of ToggleAlarmFilter + } + + this.webSocketService.sendViaWebsockets(nodeName, notificationXml); + + } + + @Override + public void onNotificationDelay(ProblemNotificationXml notificationXml) { + + LOG.debug("Got delayed event of type :: {}", ProblemNotificationXml.class.getSimpleName()); + dcaeForwarder.sendProblemNotificationUsingMaintenanceFilter(this.nodeName, notificationXml); + + } + private void initCurrentProblem(ProblemNotificationXml notificationXml) { + databaseService.updateFaultCurrent(notificationXml.getFaultcurrent()); + dcaeForwarder.sendProblemNotification(this.nodeName, notificationXml); + } + + /** + * Called to initialize with the current status and notify the clients + * @param notificationXmlList List with problems + */ + public void initCurrentProblemStatus(List<ProblemNotificationXml> notificationXmlList) { + + for (ProblemNotificationXml notificationXml : notificationXmlList) { + initCurrentProblem(notificationXml); + } + + } + + /** + * Called on exit to remove everything from the current list. + * @return Number of deleted objects + */ + public int removeAllCurrentProblemsOfNode() { + int deleted = databaseService.clearFaultsCurrentOfNode(nodeName); + return deleted; + } + + /** + * Called on exit to remove for one Object-Pac from the current list. + * @param objectId uuid of the interface-pac or equipment-pac + * @return Number of deleted objects + */ + public int removeObjectsCurrentProblemsOfNode(String objectId) { + int deleted = databaseService.clearFaultsCurrentOfNodeWithObjectId(nodeName, objectId); + return deleted; + } + + /** + * Write equipment data to database + * @param equipment to write + */ + public void writeEquipment(ONFCoreNetworkElement12Equipment equipment) { +// List<ExtendedEquipment> equipmentList = equipment.getEquipmentList(); +// for (ExtendedEquipment card : equipmentList) { +// databaseService.writeInventory(card.getCreateInventoryInput()); +// } + equipment.getEquipmentList().forEach(card -> databaseService.writeInventory(card.getCreateInventoryInput()) ); + + } + + } diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/ODLEventListenerHandler.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/ODLEventListenerHandler.java new file mode 100644 index 000000000..36ac7dca0 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/ODLEventListenerHandler.java @@ -0,0 +1,231 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler; + +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementBase; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectDeletionNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementDeviceType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Responsible class for documenting changes in the ODL itself. The occurence of such an event is + * documented in the database and to clients. Specific example here is the registration or + * deregistration of a netconf device. This service has an own eventcounter to apply to the ONF + * Coremodel netconf behaviour. + * + * Important: Websocket notification must be the last action. + * + * @author herbert + */ + +public class ODLEventListenerHandler { + + private static final Logger LOG = LoggerFactory.getLogger(ODLEventListenerHandler.class); + + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + private final String ownKeyName; + private final WebSocketServiceClientInternal webSocketService; + private final DataProvider databaseService; + private final DcaeForwarderInternal aotsDcaeForwarder; + + private int eventNumber; + + /*--------------------------------------------------------------- + * Construct + */ + + /** + * Create a Service to document events to clients and within a database + * + * @param ownKeyName The name of this service, that is used in the database as identification key. + * @param webSocketService service to direct messages to clients + * @param databaseService service to write to the database + * @param dcaeForwarder to deliver problems to external service + */ + public ODLEventListenerHandler(String ownKeyName, WebSocketServiceClientInternal webSocketService, + DataProvider databaseService, DcaeForwarderInternal dcaeForwarder) { + super(); + + this.ownKeyName = ownKeyName; + this.webSocketService = webSocketService; + + this.databaseService = databaseService; + this.aotsDcaeForwarder = dcaeForwarder; + + this.eventNumber = 0; + + } + + /*--------------------------------------------------------------- + * Handling of ODL Controller events + */ + + /** + * A registration of a mountpoint occured, that is in connect state + * @param registrationName of device (mountpoint name) + * @param nNode with mountpoint data + */ + public void registration(String registrationName, NetconfNode nNode) { + + ObjectCreationNotificationXml cNotificationXml = + new ObjectCreationNotificationXml(ownKeyName, popEvntNumber(), + InternalDateAndTime.valueOf(NETCONFTIME_CONVERTER.getTimeStamp()), registrationName); + NetworkElementConnectionEntity e = ONFCoreNetworkElementBase.getNetworkConnection(registrationName, nNode); + LOG.debug("registration networkelement-connection for {} with status {}", registrationName, e.getStatus()); + + // Write first to prevent missing entries + databaseService.updateNetworkConnection22(e, registrationName); + databaseService.writeConnectionLog(cNotificationXml.getConnectionlogEntity()); + webSocketService.sendViaWebsockets(registrationName, cNotificationXml); + } + + /** + * After registration + * @param mountpointNodeName uuid that is nodeId or mountpointId + * @param deviceType according to assessement + */ + public void connectIndication(String mountpointNodeName, NetworkElementDeviceType deviceType) { + // Write first to prevent missing entries + LOG.debug("updating networkelement-connection devicetype for {} with {}",mountpointNodeName, deviceType); + NetworkElementConnectionEntity e = ONFCoreNetworkElementBase.getNetworkConnectionDeviceTpe(deviceType); + databaseService.updateNetworkConnectionDeviceType(e, mountpointNodeName); + + } + + + /** + * A deregistration of a mountpoint occured. + * + * @param registrationName Name of the event that is used as key in the database. + */ + + public void deRegistration(String registrationName) { + + ObjectDeletionNotificationXml dNotificationXml = + new ObjectDeletionNotificationXml(ownKeyName, popEvntNumber(), + InternalDateAndTime.valueOf(NETCONFTIME_CONVERTER.getTimeStamp()), registrationName); + + // Write first to prevent missing entries + databaseService.removeNetworkConnection(registrationName); + databaseService.writeConnectionLog(dNotificationXml.getConnectionlogEntity()); + webSocketService.sendViaWebsockets(registrationName, dNotificationXml); + + } + + /** + * Mountpoint state changed .. from connected -> connecting or unable-to-connect or vis-e-versa. + * + * @param registrationName Name of the event that is used as key in the database. + */ + public void updateRegistration(String registrationName, String attribute, String attributeNewValue, NetconfNode nNode) { + AttributeValueChangedNotificationXml notificationXml = new AttributeValueChangedNotificationXml(ownKeyName, + popEvntNumber(), InternalDateAndTime.valueOf(NETCONFTIME_CONVERTER.getTimeStamp()), + registrationName, attribute, attributeNewValue); + NetworkElementConnectionEntity e = ONFCoreNetworkElementBase.getNetworkConnection(registrationName, nNode); + LOG.debug("updating networkelement-connection for {} with status {}", registrationName, e.getStatus()); + + databaseService.updateNetworkConnection22(e, registrationName); + databaseService.writeConnectionLog(notificationXml.getConnectionlogEntity()); + webSocketService.sendViaWebsockets(registrationName, notificationXml); + } + + /** + * At a mountpoint a problem situation is indicated + * + * @param registrationName indicating object within SDN controller, normally the mountpointName + * @param problemName that changed + * @param problemSeverity of the problem according to NETCONF/YANG + */ + + public void onProblemNotification(String registrationName, String problemName, InternalSeverity problemSeverity) { + LOG.debug("Got event of {} {} {}", registrationName, problemName, problemSeverity); + // notification + + ProblemNotificationXml notificationXml = + new ProblemNotificationXml(ownKeyName, registrationName, problemName, problemSeverity, + // popEvntNumberAsString(), InternalDateAndTime.TESTPATTERN ); + popEvntNumber(), InternalDateAndTime.valueOf(NETCONFTIME_CONVERTER.getTimeStamp())); + + databaseService.writeFaultLog(notificationXml.getFaultlog(SourceType.Controller)); + databaseService.updateFaultCurrent(notificationXml.getFaultcurrent()); + + aotsDcaeForwarder.sendProblemNotificationUsingMaintenanceFilter(ownKeyName, notificationXml); + + webSocketService.sendViaWebsockets(registrationName, notificationXml); + } + + public void writeEventLog(String objectId, String msg, String value) { + + LOG.debug("Got startComplete"); + EventlogBuilder eventlogBuilder = new EventlogBuilder(); + eventlogBuilder.setNodeId(ownKeyName).setTimestamp(new DateAndTime(NETCONFTIME_CONVERTER.getTimeStamp())) + .setObjectId(objectId).setAttributeName(msg).setNewValue(value).setCounter(popEvntNumber()) + .setSourceType(SourceType.Controller); + databaseService.writeEventLog(eventlogBuilder.build()); + + } + + /*--------------------------------------------- + * Handling of ODL Controller events + */ + + /** + * Called on exit to remove everything for a node from the current list. + * + * @param nodeName to remove all problems for + * @return Number of deleted objects + */ + public int removeAllCurrentProblemsOfNode(String nodeName) { + return databaseService.clearFaultsCurrentOfNodeWithObjectId(ownKeyName, nodeName); + } + + /*--------------------------------------------------------------- + * Get/Set + */ + + /** + * @return the ownKeyName + */ + public String getOwnKeyName() { + return ownKeyName; + } + + /*--------------------------------------------------------------- + * Private + */ + private Integer popEvntNumber() { + return eventNumber++; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/RpcPushNotificationsHandler.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/RpcPushNotificationsHandler.java new file mode 100644 index 000000000..ff559f859 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/handler/RpcPushNotificationsHandler.java @@ -0,0 +1,90 @@ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler; +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ + +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeForwarderInternal; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.PushNotifications; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.AttributeValueChangedNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.WebSocketServiceClientInternal; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultcurrentBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultcurrentEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushAttributeChangeNotificationInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.PushFaultNotificationInput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RpcPushNotificationsHandler implements PushNotifications { + + private static final Logger LOG = LoggerFactory.getLogger(RpcPushNotificationsHandler.class); + + private static String OWNKEYNAME = "VES"; + private final WebSocketServiceClientInternal webSocketService; + private final DataProvider databaseService; + private final DcaeForwarderInternal aotsDcaeForwarder; + + public RpcPushNotificationsHandler(WebSocketServiceClientInternal webSocketService, DataProvider databaseService, + DcaeForwarderInternal aotsDcaeForwarder) { + super(); + this.webSocketService = webSocketService; + this.databaseService = databaseService; + this.aotsDcaeForwarder = aotsDcaeForwarder; + } + + @Override + public void pushAttributeChangeNotification(PushAttributeChangeNotificationInput input) { + + LOG.debug("Got attribute change event {}", input); + + EventlogBuilder enventlogBuilder = new EventlogBuilder(); + enventlogBuilder.setSourceType(SourceType.Ves); + enventlogBuilder.fieldsFrom(input); + EventlogEntity eventlogEntity = enventlogBuilder.build(); + databaseService.writeEventLog(eventlogEntity); + webSocketService.sendViaWebsockets(OWNKEYNAME, new AttributeValueChangedNotificationXml(eventlogEntity)); + + } + + @Override + public void pushFaultNotification(PushFaultNotificationInput input) { + + LOG.debug("Got fault event {}", input); + + FaultlogBuilder faultlogBuilder = new FaultlogBuilder(); + faultlogBuilder.setSourceType(SourceType.Ves); + faultlogBuilder.fieldsFrom(input); + FaultlogEntity faultlogEntity = faultlogBuilder.build(); + databaseService.writeFaultLog(faultlogEntity); + + FaultcurrentBuilder faultcurrentBuilder = new FaultcurrentBuilder(); + faultcurrentBuilder.fieldsFrom(input); + FaultcurrentEntity faultcurrentEntity = faultcurrentBuilder.build(); + databaseService.updateFaultCurrent(faultcurrentEntity); + + ProblemNotificationXml notificationXml = new ProblemNotificationXml(faultlogEntity); + aotsDcaeForwarder.sendProblemNotificationUsingMaintenanceFilter(OWNKEYNAME, notificationXml); + webSocketService.sendViaWebsockets(OWNKEYNAME, notificationXml); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/listener/NetconfChangeListener.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/listener/NetconfChangeListener.java new file mode 100644 index 000000000..2334bd181 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/listener/NetconfChangeListener.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.listener; + +import java.util.Collection; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.NetconfNodeService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.NetconfNodeService.Action; +import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.DataObjectModification; +import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType; +import org.opendaylight.mdsal.binding.api.DataTreeIdentifier; +import org.opendaylight.mdsal.binding.api.DataTreeModification; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// 07.09.18 Switched to DataTreeChangeListener from ClusteredDataTreeChangeListener -> DM Service is +// running at all nodes +// This is not correct +public class NetconfChangeListener implements ClusteredDataTreeChangeListener<Node>, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfChangeListener.class); + + private static final InstanceIdentifier<Node> NETCONF_NODE_TOPO_IID = + InstanceIdentifier.create(NetworkTopology.class) + .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))) + .child(Node.class); + // Name of ODL controller NETCONF instance + private static final NodeId CONTROLLER = new NodeId("controller-config"); + + private final NetconfNodeService deviceManagerService; + private final DataBroker dataBroker; + private ListenerRegistration<NetconfChangeListener> dlcReg; + + public NetconfChangeListener(NetconfNodeService deviceManagerService, DataBroker dataBroker) { + this.deviceManagerService = deviceManagerService; + this.dataBroker = dataBroker; + } + + public void register() { + DataTreeIdentifier<Node> treeId = DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NETCONF_NODE_TOPO_IID); + + dlcReg = dataBroker.registerDataTreeChangeListener(treeId, this); + } + + @Override + public void close() { + if (dlcReg != null) { + dlcReg.close(); + } + } + /** + * Listener function to select the right node from DataObjectModification + */ + @Override + public void onDataTreeChanged(Collection<DataTreeModification<Node>> changes) { + LOG.debug("OnDataChange, TreeChange, changes:{}", changes.size()); + + for (final DataTreeModification<Node> change : changes) { + final DataObjectModification<Node> root = change.getRootNode(); + final ModificationType modificationType = root.getModificationType(); + if (LOG.isTraceEnabled()) { + LOG.trace("Handle this modificationType:{} path:{} root:{}", modificationType, change.getRootPath(), + root); + } + switch (modificationType) { + case SUBTREE_MODIFIED: + // Change of subtree information + // update(change); OLD + doProcessing(Action.UPDATE, root.getDataAfter()); + break; + case WRITE: + // Create or modify top level node + // Treat an overwrite as an update + boolean update = root.getDataBefore() != null; + if (update) { + // update(change); + doProcessing(Action.UPDATE, root.getDataAfter()); + } else { + // add(change); + doProcessing(Action.CREATE, root.getDataAfter()); + } + break; + case DELETE: + // Node removed + // remove(change); + doProcessing(Action.REMOVE, root.getDataBefore()); + break; + } + } + } + + /* + * ---------------------------------------------------------------- + */ + + /** + * Process event and forward to clients if Node is a NetconfNode + * @param action + * @param node Basis node + */ + private void doProcessing(Action action, Node node) { + + NodeId nodeId = null; + NetconfNode nnode = null; + + try { + if (node != null) { + nodeId = node.key().getNodeId(); //Never null + nnode = node.augmentation(NetconfNode.class); + } + + if (node == null || nnode == null) { + LOG.warn("Unexpected node {}, netconf node {} id {}", node, nnode, nodeId); + } else { + // Do not forward any controller related events to devicemanager + if (nodeId.equals(CONTROLLER)) { + LOG.debug("Stop processing for [{}]", nodeId); + } else { + // Action forwarded to devicehandler + deviceManagerService.netconfNodeChangeHandler(action, nodeId, nnode); + } + } + } catch (NullPointerException e) { + LOG.warn("Unexpected null .. stop processing.", e); + } + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/GenericTransactionUtils.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/GenericTransactionUtils.java new file mode 100644 index 000000000..ed4278923 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/GenericTransactionUtils.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util; + +import com.google.common.base.Preconditions; +import com.google.common.util.concurrent.FluentFuture; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.TransactionUtils; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.ReadTransaction; +import org.opendaylight.mdsal.common.api.LogicalDatastoreType; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class GenericTransactionUtils implements TransactionUtils { + static final Logger LOG = LoggerFactory.getLogger(GenericTransactionUtils.class); + + /** + * Deliver the data back or null. Warning + * + * @param <T> SubType of the DataObject to be handled + * @param dataBroker for accessing data + * @param dataStoreType to address datastore + * @param iid id to access data + * @return null or object + */ + @Override + @Nullable + public <T extends DataObject> T readData(DataBroker dataBroker, LogicalDatastoreType dataStoreType, + InstanceIdentifier<T> iid) { + + AtomicBoolean noErrorIndication = new AtomicBoolean(); + AtomicReference<String> statusText = new AtomicReference<>(); + + @Nullable T obj = readDataOptionalWithStatus(dataBroker, dataStoreType, iid, noErrorIndication, statusText); + + if (!noErrorIndication.get()) { + LOG.warn("Read transaction for identifier " + iid + " failed with status " + statusText.get()); + } + + return obj; + } + + /** + * Deliver the data back or null + * + * @param <T> SubType of the DataObject to be handled + * @param dataBroker for accessing data + * @param dataStoreType to address datastore + * @param iid id to access data + * @param noErrorIndication (Output) true if data could be read and are available and is not null + * @param statusIndicator (Output) String with status indications during the read. + * @return null or object + */ + @Override + @SuppressWarnings("null") + public @Nullable <T extends DataObject> T readDataOptionalWithStatus(DataBroker dataBroker, + LogicalDatastoreType dataStoreType, InstanceIdentifier<T> iid, AtomicBoolean noErrorIndication, + AtomicReference<String> statusIndicator) { + + @Nullable T data = null; + noErrorIndication.set(false); + + statusIndicator.set("Preconditions"); + Preconditions.checkNotNull(dataBroker); + + int retry = 0; + int retryDelayMilliseconds = 2000; + int maxRetries = 5; // 0 no Retry + + do { + if (retry > 0) { + try { + LOG.debug("Sleep {}ms", retryDelayMilliseconds); + Thread.sleep(retryDelayMilliseconds); + } catch (InterruptedException e) { + LOG.debug("Sleep interrupted", e); + Thread.currentThread().interrupt(); + } + } + + LOG.debug("Sending message with retry {} ", retry); + statusIndicator.set("Create Read Transaction"); + + try (ReadTransaction readTransaction = dataBroker.newReadOnlyTransaction();) { + @NonNull FluentFuture<Optional<T>> od = readTransaction.read(dataStoreType, iid); + statusIndicator.set("Read done"); + if (od != null) { + statusIndicator.set("Unwrap checkFuture done"); + Optional<T> optionalData = od.get(); + if (optionalData != null) { + statusIndicator.set("Unwrap optional done"); + data = optionalData.orElse(null); + statusIndicator.set("Read transaction done"); + noErrorIndication.set(true); + } + } + + readTransaction.close(); + } catch (CancellationException | ExecutionException | InterruptedException | NoSuchElementException e) { + statusIndicator.set(ExceptionUtils.getStackTrace(e)); + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + } + + } while (noErrorIndication.get() == false && retry++ < maxRetries); + + return data; + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalDateAndTime.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalDateAndTime.java new file mode 100644 index 000000000..91fed715d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalDateAndTime.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util; + +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.DateAndTime; + +/** + * Converts time stamps into internal format according to ONF1.2 and ISO 8601. + * @author herbert + * + */ +public class InternalDateAndTime { + + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + private static final InternalDateAndTime TESTPATTERN = new InternalDateAndTime("2017-01-01T00:00:00.0Z"); + private static final String INITIALPATTERN = "0000-00-00T00:00:00.0Z"; + + String internalDateAndTime = INITIALPATTERN; + + /** + * Static builder ONF1.2 + * @param time in ONF1.2 yang format + * @return InternalDateAndTime + */ + public static InternalDateAndTime valueOf(DateAndTime time) { + return new InternalDateAndTime(time); + } + + /** + * Static builder ONF1.0 + * @param time in ONF1.0 yang format + * @return InternalDateAndTime + */ + + public static InternalDateAndTime valueOf(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime time) { + return new InternalDateAndTime(time); + } + + /** + * @return Getter with String representation + */ + public String getValue() { + return internalDateAndTime; + } + + /*---------------------------------------------------------------- + * Private constructors and functions + */ + + /** + * Convert ONF 1.2 DateAndTime to String + * @param time as input + */ + private InternalDateAndTime(DateAndTime time) { + internalDateAndTime = NETCONFTIME_CONVERTER.getTimeStampFromNetconf(time.getValue()); + } + + /** + * Convert ONF 1.2 DateAndTime to String + * @param time as input + */ + private InternalDateAndTime(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime time) { + if (time != null) { + internalDateAndTime = NETCONFTIME_CONVERTER.getTimeStampFromNetconf(time.getValue()); + } else { + internalDateAndTime = INITIALPATTERN; + } + } + + /** + * Setup static TEST + * @param internalDateAndTime + */ + private InternalDateAndTime(String internalDateAndTime) { + this.internalDateAndTime = internalDateAndTime; + } + + /** + * Get a testpattern + * @return testpattern + */ + public static InternalDateAndTime getTestpattern() { + return TESTPATTERN; + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalSeverity.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalSeverity.java new file mode 100644 index 000000000..54b91ad9a --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/util/InternalSeverity.java @@ -0,0 +1,191 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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========================================================================== + ******************************************************************************/ +/** + * @author herbert + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util; + + +import org.eclipse.jdt.annotation.Nullable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SeverityType; + +public enum InternalSeverity { + + NonAlarmed, + Warning, + Minor, + Major, + Critical; + + public boolean isNoAlarmIndication() { + return this == NonAlarmed; + } + + public String getValueAsString() { + return this.name(); + } + + @Override + public String toString() { + return this.name(); + } + + public String toNetconfString() { + switch (this) { + case NonAlarmed: + return "non-alarmed"; + case Warning: + return "warning"; + case Minor: + return "minor"; + case Major: + return "major"; + case Critical: + return "critical"; + } + return "not-specified"; + } + + public SeverityType toDataProviderSeverityType() { + switch (this) { + case NonAlarmed: + return SeverityType.NonAlarmed; + case Warning: + return SeverityType.Warning; + case Minor: + return SeverityType.Minor; + case Major: + return SeverityType.Major; + case Critical: + return SeverityType.Critical; + } + return null; //Should never happen + } + + /** + * convert ONF 1.2 Severity + * @param severity as input + * @return String with related output + */ + public static InternalSeverity valueOf(org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.SeverityType severity ) { + switch( severity ) { + case NonAlarmed: + return InternalSeverity.NonAlarmed; + case Warning: + return InternalSeverity.Warning; + case Minor: + return InternalSeverity.Minor; + case Major: + return InternalSeverity.Major; + case Critical: + return InternalSeverity.Critical; + } + return null; + } + + /** + * convert ONF 1.2.1.1 Severity + * @param severity as input + * @return String with related output + */ + public static InternalSeverity valueOf(org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.SeverityType severity ) { + switch( severity ) { + case NonAlarmed: + return InternalSeverity.NonAlarmed; + case Warning: + return InternalSeverity.Warning; + case Minor: + return InternalSeverity.Minor; + case Major: + return InternalSeverity.Major; + case Critical: + return InternalSeverity.Critical; + } + return null; + } + + /** + * convert ONF 1.2.1.1p Severity + * @param severity as input + * @return String with related output + */ + public static InternalSeverity valueOf(org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.SeverityType severity ) { + switch( severity ) { + case NonAlarmed: + return InternalSeverity.NonAlarmed; + case Warning: + return InternalSeverity.Warning; + case Minor: + return InternalSeverity.Minor; + case Major: + return InternalSeverity.Major; + case Critical: + return InternalSeverity.Critical; + } + return null; + } + + + + /** + * convert a text string into Severity + * @param severityString with textes: warning minor major critical non[-]alarmed. (Capital or lowercase) + * @return related enum. Unknown oe illegal are converted to NonAlarm + */ + public static @Nullable InternalSeverity valueOfString(String severityString) { + + switch( severityString.toLowerCase().trim() ) { + case "warning": + return InternalSeverity.Warning; + case "minor": + return InternalSeverity.Minor; + case "major": + return InternalSeverity.Major; + case "critical": + return InternalSeverity.Critical; + } + return InternalSeverity.NonAlarmed; + + } + + /** + * Convert to InternalSeverity + * @param severity to be converted + * @return InternalSeverity, null converted to NonAlarmed + */ + public static InternalSeverity valueOf(@org.eclipse.jdt.annotation.Nullable SeverityType severity) { + if (severity != null) { + switch (severity) { + case NonAlarmed: + return InternalSeverity.NonAlarmed; + case Warning: + return InternalSeverity.Warning; + case Minor: + return InternalSeverity.Minor; + case Major: + return InternalSeverity.Major; + case Critical: + return InternalSeverity.Critical; + } + } + return InternalSeverity.NonAlarmed; + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/AttributeValueChangedNotificationXml.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/AttributeValueChangedNotificationXml.java new file mode 100644 index 000000000..471060c2d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/AttributeValueChangedNotificationXml.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; + +@XmlRootElement(name = "AttributeValueChangedNotification") +public class AttributeValueChangedNotificationXml extends MwtNotificationBase implements GetEventType { + + private static String EVENTTYPE = "AttributeValueChangedNotification"; + + @XmlElement(name = "attributeName") + private String attributeName; + + @XmlElement(name = "newValue") + private String newValue; + + public AttributeValueChangedNotificationXml() { + + } + + /** + * Normalized notification + * @param nodeName name of mountpoint + * @param counter of notification + * @param timeStamp from ne + * @param objectIdRef from ne + * @param attributeName from ne + * @param newValue from ne + */ + public AttributeValueChangedNotificationXml(String nodeName, Integer counter, InternalDateAndTime timeStamp, String objectIdRef, + String attributeName, String newValue) { + super(nodeName, counter, timeStamp, objectIdRef); + this.attributeName = attributeName; + this.newValue = newValue; + } + + public AttributeValueChangedNotificationXml(EventlogEntity eventlogEntitiy) { + this(eventlogEntitiy.getNodeId(), eventlogEntitiy.getCounter(), + InternalDateAndTime.valueOf(eventlogEntitiy.getTimestamp()), eventlogEntitiy.getObjectId(), + eventlogEntitiy.getAttributeName(), eventlogEntitiy.getNewValue()); + } + + + public String getAttributeName() { + return attributeName; + } + + public String getNewValue() { + return newValue; + } + + @Override + public String getEventType() { + return EVENTTYPE; + } + + public EventlogEntity getEventlogEntity() { + return new EventlogBuilder().setAttributeName(attributeName).setNewValue(newValue) + .setCounter(Integer.valueOf(this.getCounter())) + .setNodeId(this.getNodeName()).setObjectId(this.getObjectId()) + .setTimestamp(new DateAndTime(this.getTimeStamp())).setSourceType(SourceType.Netconf).build(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/GetEventType.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/GetEventType.java new file mode 100644 index 000000000..ba3e23c77 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/GetEventType.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +/** + * @author herbert + * + */ +public interface GetEventType { + public String getEventType(); +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/MwtNotificationBase.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/MwtNotificationBase.java new file mode 100644 index 000000000..156f9226e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/MwtNotificationBase.java @@ -0,0 +1,130 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus.ConnectionStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionLogStatus; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionlogEntity; + +public class MwtNotificationBase { + + private static String EMPTY = "empty"; + + private String nodeName; + private String counter; + private String timeStamp; + private @Nonnull String objectId; + + public MwtNotificationBase() { + // For Jaxb + } + + public MwtNotificationBase(String nodeName, Integer counter, InternalDateAndTime timeStamp, String objectId) { + this.nodeName = nodeName; + this.counter = String.valueOf(counter); + this.timeStamp = timeStamp.getValue(); + this.objectId = objectId; + if (this.objectId == null) { + this.objectId = EMPTY; + } + } + + @XmlElement(name = "nodeName") + public String getNodeName() { + return nodeName; + } + + @XmlElement(name = "counter") + public String getCounter() { + return counter; + } + + @XmlElement(name = "timeStamp") + public String getTimeStamp() { + return timeStamp; + } + + @XmlElement(name = "objectId") + public String getObjectId() { + return objectId; + } + + /** + * Provide ConnectionlogEntity type + * @return ConnectionlogEntity + */ + public ConnectionlogEntity getConnectionlogEntity() { + return new ConnectionlogBuilder() + .setNodeId(objectId) + .setStatus(getStatus()) + .setTimestamp(new DateAndTime(timeStamp)) + .build(); + } + + /** + * Provide connection status for mountpoint log. + * TODO Add status disconnected if mountpoint is required, but does not exists. + * @return + */ + private ConnectionLogStatus getStatus() { + + if (this instanceof ObjectCreationNotificationXml) { + return ConnectionLogStatus.Mounted; + + } else if (this instanceof ObjectDeletionNotificationXml) { + return ConnectionLogStatus.Unmounted; + + } else if (this instanceof AttributeValueChangedNotificationXml) { + String pnx = ((AttributeValueChangedNotificationXml)this).getNewValue(); + if (pnx.equals(ConnectionStatus.Connected.getName())) { + return ConnectionLogStatus.Connected; + + } else if (pnx.equals(ConnectionStatus.Connecting.getName())) { + return ConnectionLogStatus.Connecting; + + } else if (pnx.equals(ConnectionStatus.UnableToConnect.getName())) { + return ConnectionLogStatus.UnableToConnect; + } + } + return ConnectionLogStatus.Undefined; + } + + /** + * Type for the Database to document the the same name that is used in the websockets. + * @return String with type name of child class + */ + @JsonProperty("type") + public String getType() { + return this.getClass().getSimpleName(); + } + + @Override + public String toString() { + return "MwtNotificationBase [getType()="+ getType() + ", nodeName=" + nodeName + ", counter=" + counter + ", timeStamp=" + timeStamp + + ", objectId=" + objectId + "]"; + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectCreationNotificationXml.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectCreationNotificationXml.java new file mode 100644 index 000000000..a64919fa4 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectCreationNotificationXml.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import javax.xml.bind.annotation.XmlRootElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Eventlog; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; + +@XmlRootElement(name = "ObjectCreationNotification") +public class ObjectCreationNotificationXml extends MwtNotificationBase implements GetEventType { + + private static String EVENTTYPE = "ObjectCreationNotification"; + private static String ACTION = "creation"; + + public ObjectCreationNotificationXml() { + + } + + /** + * Normalized notification + * @param nodeName name of mountpoint or instance that owns the problem + * @param counter of notification + * @param timeStamp from ne + * @param objectIdRef from ne + */ + public ObjectCreationNotificationXml(String nodeName, Integer counter, InternalDateAndTime timeStamp, String objectIdRef) { + super(nodeName, counter, timeStamp, objectIdRef); + } + + /*public ObjectCreationNotificationXml(String nodeName, org.opendaylight.yang.gen.v1.uri.onf.microwavemodel.notifications.rev160809.ObjectCreationNotification notification) { + super(nodeName, notification.getCounter().toString(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue()); + } + + public ObjectCreationNotificationXml(String nodeName, org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ObjectCreationNotification notification) { + super(nodeName, notification.getCounter().toString(), InternalDateAndTime.valueOf(notification.getTimeStamp()), + notification.getObjectIdRef().getValue()); + }*/ + + @Override + public String getEventType() { + return EVENTTYPE; + } + + public Eventlog getEventlogEntity() { + return new EventlogBuilder().setAttributeName(ACTION).setNewValue(ACTION) + .setCounter(Integer.valueOf(this.getCounter())) + .setNodeId(this.getNodeName()).setObjectId(this.getObjectId()) + .setTimestamp(new DateAndTime(this.getTimeStamp())).setSourceType(SourceType.Netconf).build(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectDeletionNotificationXml.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectDeletionNotificationXml.java new file mode 100644 index 000000000..2b50411fe --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ObjectDeletionNotificationXml.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import javax.xml.bind.annotation.XmlRootElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Eventlog; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; + +@XmlRootElement(name = "ObjectDeletionNotification") +public class ObjectDeletionNotificationXml extends MwtNotificationBase implements GetEventType { + + private static String EVENTTYPE = "ObjectDeletionNotification"; + private static String ACTION = "deletion"; + + public ObjectDeletionNotificationXml() { + + } + + /** + * Normalized notification + * @param nodeName name of mountpoint or instance that owns the problem + * @param counter of notification + * @param timeStamp from ne + * @param objectIdRef from ne + */ + public ObjectDeletionNotificationXml(String nodeName, Integer counter, InternalDateAndTime timeStamp, String objectIdRef) { + super(nodeName, counter, timeStamp, objectIdRef); + } + + /* + public ObjectDeletionNotificationXml(String nodeName, ObjectDeletionNotification notification) { + super(nodeName, notification.getCounter().toString(), InternalDateAndTime.valueOf(notification.getTimeStamp()), +// notification.getObjectId().getValue()); + notification.getObjectIdRef().getValue()); + }*/ +/* + public ObjectDeletionNotificationXml(String nodeName, org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ObjectDeletionNotification notification) { + super(nodeName, notification.getCounter().toString(), InternalDateAndTime.valueOf(notification.getTimeStamp()), +// notification.getObjectId().getValue()); + notification.getObjectIdRef().getValue()); + } +*/ + @Override + public String getEventType() { + return EVENTTYPE; + } + + public Eventlog getEventlogEntity() { + return new EventlogBuilder().setAttributeName(ACTION).setNewValue(ACTION) + .setCounter(Integer.valueOf(this.getCounter())) + .setNodeId(this.getNodeName()).setObjectId(this.getObjectId()) + .setTimestamp(new DateAndTime(this.getTimeStamp())).setSourceType(SourceType.Netconf).build(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ProblemNotificationXml.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ProblemNotificationXml.java new file mode 100644 index 000000000..dcb299a8e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/ProblemNotificationXml.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.List; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database.FaultEntityManager; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Faultcurrent; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultcurrentBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Faultlog; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultlogBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; +import org.slf4j.Logger; + +@XmlRootElement(name = "ProblemNotification") +public class ProblemNotificationXml extends MwtNotificationBase implements GetEventType { + + private static String EVENTTYPE = "ProblemNotification"; + + @XmlElement(name = "problem") + private String problem; + + @XmlElement(name = "severity") + private InternalSeverity severity; + + public ProblemNotificationXml() { + + } + + /** + * Generic Problem. All the parameters are of type Strings according to YANG + * specification. + * + * @param nodeName Name of mountpoint + * @param uuId Name of Interface Pac + * @param problemNameString Name of the problem + * @param problemSeverityString Severitycode of the problem + * @param counter Counter from device + * @param internaltimeStampString Timestamp according to internal format. + */ + public ProblemNotificationXml(String nodeName, String uuId, String problemNameString, + InternalSeverity problemSeverityString, Integer counter, InternalDateAndTime internaltimeStampString) { + super(nodeName, counter, internaltimeStampString, uuId); + this.problem = problemNameString; + this.severity = problemSeverityString; + } + + public ProblemNotificationXml(FaultlogEntity input) { + this(input.getNodeId(), input.getObjectId(), input.getProblem(), InternalSeverity.valueOf(input.getSeverity()), + input.getCounter(), InternalDateAndTime.valueOf(input.getTimestamp())); + } + + public String getProblem() { + return problem; + } + + public InternalSeverity getSeverity() { + return severity; + } + + public boolean isNotManagedAsCurrentProblem() { + return ! FaultEntityManager.isManagedAsCurrentProblem(getProblem()); + } + + public boolean isNoAlarmIndication() { + return severity.isNoAlarmIndication(); + } + + /** + * Create a specific ES id for the current log. + * @return a string with the generated ES Id + */ + @JsonIgnore + public String genSpecificEsId() { + return FaultEntityManager.genSpecificEsId(getNodeName(), getObjectId(), getProblem()); + } + + @JsonIgnore + public Faultlog getFaultlog(SourceType sourceType) { + return new FaultlogBuilder().setNodeId(getNodeName()).setCounter(Integer.parseInt(getCounter())) + .setObjectId(getObjectId()).setProblem(getProblem()).setSourceType(sourceType) + .setSeverity(getSeverity().toDataProviderSeverityType()).setTimestamp(new DateAndTime(getTimeStamp())) + .build(); + } + + @JsonIgnore + public Faultcurrent getFaultcurrent() { + return new FaultcurrentBuilder().setNodeId(getNodeName()).setCounter(Integer.parseInt(getCounter())) + .setObjectId(genSpecificEsId()).setProblem(getProblem()) + .setSeverity(getSeverity().toDataProviderSeverityType()).setTimestamp(new DateAndTime(getTimeStamp())) + .build(); + } + + @Override + public String toString() { + return "ProblemNotificationXml [problem=" + problem + ", severity=" + severity + ", toString()=" + + super.toString() + "]"; + } + + @Override + public String getEventType() { + return EVENTTYPE; + } + + /** + * LOG the newly added problems of the interface pac + * @param log of logger + * @param uuid as log info + * @param resultList with all problems + * @param idxStart start of listing till end + */ + public static void debugResultList(Logger log, String uuid, List<ProblemNotificationXml> resultList, int idxStart) { + if (log.isDebugEnabled()) { + StringBuffer sb = new StringBuffer(); + int idx = 0; + for (int t = idxStart; t < resultList.size(); t++) { + sb.append(idx++); + sb.append(":{"); + sb.append(resultList.get(t)); + sb.append('}'); + } + log.debug("Found problems {} {}", uuid, sb.toString()); + } + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientDummyImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientDummyImpl.java new file mode 100644 index 000000000..b4dd874b9 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientDummyImpl.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * WrapperMock class for web-socket notifications to the web-socket service. + */ +public class WebSocketServiceClientDummyImpl implements WebSocketServiceClientInternal { + + private static final Logger LOG = LoggerFactory.getLogger(ODLEventListenerHandler.class); + + public WebSocketServiceClientDummyImpl() { + } + + @Override + public <T extends MwtNotificationBase & GetEventType> void sendViaWebsockets(String nodeName, T notificationXml) { + LOG.info("Dummy to send websocket event {} for mountpoint {}", notificationXml.getClass().getSimpleName(), nodeName); + } + + @Override + public void close() throws Exception { + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl.java new file mode 100644 index 000000000..b3c177efa --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * WrapperMock class for web-socket notifications to the web-socket service. + */ +public class WebSocketServiceClientImpl implements WebSocketServiceClientInternal { + + private static final Logger LOG = LoggerFactory.getLogger(ODLEventListenerHandler.class); + + public WebSocketServiceClientImpl() { + } + + @Override + public <T extends MwtNotificationBase & GetEventType> void sendViaWebsockets(String nodeName, T notificationXml) { + LOG.info("Dummy to send websocket event {} for mountpoint {}", notificationXml.getClass().getSimpleName(), nodeName); + } + + @Override + public void close() throws Exception { + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl2.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl2.java new file mode 100644 index 000000000..ba2a5b18b --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientImpl2.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import java.util.concurrent.Future; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.handler.ODLEventListenerHandler; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketEventInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketEventOutput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.websocketmanager.rev150105.WebsocketmanagerService; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Wrapper for forwarding web-socket notifications to the web-socket service, that is running as + * bundle. + */ +@SuppressWarnings("deprecation") +public class WebSocketServiceClientImpl2 implements WebSocketServiceClientInternal { + + private static final Logger LOG = LoggerFactory.getLogger(ODLEventListenerHandler.class); + + private final WebsocketmanagerService websocketmanagerService; + private final XmlMapper xmlMapper; + + /** + * Implementation of Websocket notification processor. + * @param rpcProviderRegistry to get MDSAL services. + */ + @Deprecated + public WebSocketServiceClientImpl2(RpcProviderRegistry rpcProviderRegistry) { + super(); + this.websocketmanagerService = rpcProviderRegistry.getRpcService(WebsocketmanagerService.class); + this.xmlMapper = new XmlMapper(); + } + + /** + * New: Implementation of Websocket notification processor. + * @param websocketmanagerService2 to be used + */ + public WebSocketServiceClientImpl2(WebsocketmanagerService websocketmanagerService2) { + super(); + this.websocketmanagerService = websocketmanagerService2; + this.xmlMapper = new XmlMapper(); + } + + @Override + public <T extends MwtNotificationBase & GetEventType> void sendViaWebsockets(String nodeName, T notificationXml) { + LOG.info("Send websocket event {} for mountpoint {}", notificationXml.getClass().getSimpleName(), nodeName); + + try { + WebsocketEventInputBuilder wsBuilder = new WebsocketEventInputBuilder(); + wsBuilder.setNodeName(nodeName); + wsBuilder.setEventType(notificationXml.getEventType()); + wsBuilder.setXmlEvent(xmlMapper.getXmlString(notificationXml)); + Future<RpcResult<WebsocketEventOutput>> result = websocketmanagerService.websocketEvent(wsBuilder.build()); + LOG.info("Send websocket result: {}", result.get().getResult().getResponse()); + } catch (Exception e) { + LOG.warn("Can not send websocket event {} for mountpoint {} {}", notificationXml.getClass().getSimpleName(), + nodeName, e.toString()); + } + } + + @Override + public void close() throws Exception { + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientInternal.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientInternal.java new file mode 100644 index 000000000..9b3e674eb --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/WebSocketServiceClientInternal.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +/** + * + */ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.WebSocketServiceClient; + +/** + * Wrapper for forwarding websocket notifications to the websocket service, that is running as container. + * @author herbert + */ +public interface WebSocketServiceClientInternal extends WebSocketServiceClient, AutoCloseable { + + public <T extends MwtNotificationBase & GetEventType> void sendViaWebsockets(String nodeName, T notificationXml); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/XmlMapper.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/XmlMapper.java new file mode 100644 index 000000000..897795a0e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/impl/xml/XmlMapper.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml; + +import java.io.StringWriter; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class XmlMapper { + private static final Logger LOG = LoggerFactory.getLogger(XmlMapper.class); + + public String getXmlString(MwtNotificationBase base) { + String xml; + JAXBContext jaxbContext; + try { + jaxbContext = JAXBContext.newInstance(AttributeValueChangedNotificationXml.class, + ObjectCreationNotificationXml.class, ObjectDeletionNotificationXml.class, + ProblemNotificationXml.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + + StringWriter stringWriter = new StringWriter(); + jaxbMarshaller.marshal(base, stringWriter); + xml = stringWriter.toString(); + } catch (JAXBException e) { + LOG.warn("Problem in marshalling xml file {}", e); + xml = null; + } + return xml; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceRPCServiceAPI.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceRPCServiceAPI.java new file mode 100644 index 000000000..3687625a0 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceRPCServiceAPI.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance; + +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetRequiredNetworkElementKeysOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeOutputBuilder; + +public interface MaintenanceRPCServiceAPI { + + public GetRequiredNetworkElementKeysOutputBuilder getRequiredNetworkElementKeys(); + + public ShowRequiredNetworkElementOutputBuilder showRequiredNetworkElement(ShowRequiredNetworkElementInput input); + + public GetMaintenanceModeOutputBuilder getMaintenanceMode(GetMaintenanceModeInput input); + + public SetMaintenanceModeOutputBuilder setMaintenanceMode(SetMaintenanceModeInput input); + + public TestMaintenanceModeOutputBuilder testMaintenanceMode(TestMaintenanceModeInput input); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceService.java new file mode 100644 index 000000000..dabcfd052 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/MaintenanceService.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance; + +public interface MaintenanceService { + + /** + * Verify maintenance state of given object according to the filter settings. + * The object is specified by the criteria provided in the parameters. + * The data _id (uuid) is equal to the mountpointReference. + * @param mountpointReference used as reference, to query the data from database. + * @param objectIdRef first level id in onf core model, delivered by notification objectid + * @param problem problem name of device, delivered in problem notification + * @return boolean indication + */ + boolean isONFObjectInMaintenance(String mountpointReference, String objectIdRef, String problem); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/HtDatabaseMaintenanceService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/HtDatabaseMaintenanceService.java new file mode 100644 index 000000000..4d0a56fd3 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/HtDatabaseMaintenanceService.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.common.HtAssert; +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.database.EsDataObjectReaderWriter2; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Entity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HtDatabaseMaintenanceService { + + private static final Logger LOG = LoggerFactory.getLogger(HtDatabaseMaintenanceService.class); + + private final EsDataObjectReaderWriter2<MaintenanceEntity> maintenanceRW; + private final EsDataObjectReaderWriter2<NetworkElementConnectionEntity> requiredNeRW; + + HtDatabaseMaintenanceService(@NonNull HtDatabaseClient client) throws ClassNotFoundException { + HtAssert.nonnull(client); + + // Create control structure + maintenanceRW = new EsDataObjectReaderWriter2<>(client, Entity.Maintenancemode, MaintenanceEntity.class, + MaintenanceBuilder.class).setEsIdAttributeName("_id"); + + requiredNeRW = new EsDataObjectReaderWriter2<>(client, Entity.NetworkelementConnection, + NetworkElementConnectionEntity.class, NetworkElementConnectionBuilder.class) + .setEsIdAttributeName("_id"); + + } + + /** + * Get existing object for mountpoint to manage maintenance mode + * @return Object with configuration + */ + @Nullable MaintenanceEntity getMaintenance(String mountpointId) { + MaintenanceEntity deviceMaintenanceMode = null; + if (maintenanceRW != null || mountpointId != null) { + deviceMaintenanceMode = maintenanceRW.read(mountpointId); + } + return deviceMaintenanceMode; + } + + MaintenanceEntity setMaintenance(MaintenanceEntity m) { + if (maintenanceRW != null) { + if (maintenanceRW.write(m, m.getNodeId() ) == null) { + throw new IllegalArgumentException("Problem writing to database: "+m.getId()); + } + LOG.info("Wrote maintenance object {}", m.toString()); + } + return m; + } + + List<MaintenanceEntity> getAll() { + return maintenanceRW != null ? maintenanceRW.doReadAll().getHits() : new ArrayList<>(); + } + + MaintenanceEntity createIfNotExists(String mountpointId) { + MaintenanceEntity deviceMaintenanceMode = null; + if (maintenanceRW != null) { + deviceMaintenanceMode = maintenanceRW.read(mountpointId); + if (deviceMaintenanceMode == null) { + LOG.debug("creating empty maintenance object in database"); + deviceMaintenanceMode = MaintenanceCalculator.getDefaultMaintenance(mountpointId); + maintenanceRW.write(deviceMaintenanceMode, mountpointId); + } else { + LOG.debug("maintenance object already exists in database"); + } + } else { + LOG.warn("cannot create maintenance obj. db reader/writer is null"); + } + return deviceMaintenanceMode; + } + + void deleteIfNotRequired(String mountPointNodeName) { + + if (!this.isRequireNe(mountPointNodeName)) { + if (maintenanceRW != null) { + LOG.debug("removing maintenance object in database for " + mountPointNodeName); + maintenanceRW.remove(mountPointNodeName); + } else { + LOG.warn("cannot create maintenance obj. db reader/writer is null"); + } + } + + } + + + // -- Private + /** + * Check in required ne if entry exists for mountpointNodeName + * + * @param mountPointNodeName + * @return + */ + private boolean isRequireNe(String mountPointNodeName) { + NetworkElementConnectionEntity ne = null; + if (requiredNeRW != null) { + LOG.debug("searching for entry in required-networkelement for " + mountPointNodeName); + ne = requiredNeRW.read(mountPointNodeName); + } else { + LOG.warn("cannot read db. no db reader writer initialized"); + } + return ne != null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceCalculator.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceCalculator.java new file mode 100644 index 000000000..5ee846ee6 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceCalculator.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import javax.annotation.Nonnull; +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MaintenanceCalculator { + + private static final Logger LOG = LoggerFactory.getLogger(MaintenanceCalculator.class); + + private static ZoneId EsMaintenanceFilterTimeZone = ZoneId.of("UTC"); + //private static DateTimeFormatter FORMAT = DateTimeFormatter.ISO_DATE_TIME; // "1986-04-08T12:30:00" + private static DateTimeFormatter FORMAT = DateTimeFormatter.ISO_OFFSET_DATE_TIME; // 2011-12-03T10:15:30+01:00 + private static ZonedDateTime EMPTYDATETIME = ZonedDateTime.ofInstant(Instant.EPOCH, EsMaintenanceFilterTimeZone); + + /** Intended to be used static **/ + private MaintenanceCalculator() { + } + + /** + * Provide default maintenanceinformation for a device + * @param mountpointId nodeId of device + * @return default data + */ + static MaintenanceEntity getDefaultMaintenance(String mountpointId) { + + DateAndTime now = NetconfTimeStamp.getConverter().getTimeStamp(); + + MaintenanceBuilder deviceMaintenanceModeBuilder = new MaintenanceBuilder(); + deviceMaintenanceModeBuilder.setNodeId(mountpointId).setId(mountpointId); + // Use time from mountpoint creation + deviceMaintenanceModeBuilder.setDescription(""); + // Use time from mountpoint creation + deviceMaintenanceModeBuilder.setStart(now); + deviceMaintenanceModeBuilder.setEnd(now); + // Reference to all + deviceMaintenanceModeBuilder.setObjectIdRef(""); + deviceMaintenanceModeBuilder.setProblem(""); + deviceMaintenanceModeBuilder.setActive(false); + + return deviceMaintenanceModeBuilder.build(); + } + + + + /** + * Verify maintenance status + * @param maintenance if null false, else according to settings + * @param objectIdRef NETCONF object id + * @param problem name that was provided + * @param now time to verify with + * @return true if in maintenance status + */ + public static boolean isONFObjectInMaintenance(MaintenanceEntity maintenance, String objectIdRef, String problem, + ZonedDateTime now) { + + if (maintenance != null) { + Boolean isActive = maintenance.isActive(); + if (isActive != null && isActive && isInMaintenance(maintenance, objectIdRef, problem, now)) { + return true; + } + + } + return false; + } + + /** Shortcut **/ + public static boolean isONFObjectInMaintenance(MaintenanceEntity maintenance, String objectIdRef, String problem) { + return isONFObjectInMaintenance(maintenance, objectIdRef, problem, getNow()); + } + + + /*--------------------------------------------- + * private static helper functions to verify + */ + + /** + * Get the actual time in the Filter time zone. + * @return actual Time + */ + private static ZonedDateTime getNow() { + return ZonedDateTime.now(EsMaintenanceFilterTimeZone); + } + + + /** + * Verify if the filter is active for an object + * + * @param now point of time to verify + * @return if the object is covered by filter and now within point of time + */ + private static boolean isInMaintenance(MaintenanceEntity maintenance, String objectIdRef, String problem, ZonedDateTime now) { + return appliesToObjectReference(maintenance, objectIdRef, problem) && isInPeriod(maintenance.getStart(), maintenance.getEnd(), now); + } + + /** + * Compare the if probe is within the range of start and end. + * + * @param start of range + * @param end of range + * @param probe time to verify + * @return boolean result true if (start <= probe <= end) + */ + public static boolean isInPeriod(DateAndTime start, DateAndTime end, ZonedDateTime probe) { + ZonedDateTime startZT = valueOf(start.getValue()); + ZonedDateTime endZT = valueOf(end.getValue()); + return startZT.compareTo(endZT) < 0 && startZT.compareTo(probe) <= 0 && endZT.compareTo(probe) >= 0; + } + + /** + * Verify if the definied object is matching to the referenced object + * @param definition definition with parameters + * @param pObjectIdRef If empty considered as true + * @param pProblem if empty considered as true + * @return true if if referenced + */ + private static boolean appliesToObjectReference(@Nonnull MaintenanceEntity definition, @Nonnull String pObjectIdRef, @Nonnull String pProblem) { + boolean res = (pObjectIdRef.isEmpty() || pObjectIdRef.contains(definition.getObjectIdRef())) + && (pProblem.isEmpty() || pProblem.contains(definition.getProblem())); + LOG.debug("Check result applies {}: {} {} against: {}", res, pObjectIdRef, pProblem, definition); + return res; + } + + /** + * Convert String to time value + * @param zoneTimeString with time + * @return ZonedDateTime string + */ + static ZonedDateTime valueOf(String zoneTimeString) { + if (zoneTimeString == null || zoneTimeString.isEmpty()) { + LOG.warn("Null or empty zoneTimeString"); + return EMPTYDATETIME; + } + try { + return ZonedDateTime.parse(zoneTimeString, FORMAT); + } catch (DateTimeParseException e) { + LOG.warn("Can not parse zoneTimeString '{}'",zoneTimeString); + return EMPTYDATETIME; + } + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceServiceImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceServiceImpl.java new file mode 100644 index 000000000..fb306b6cd --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/maintenance/impl/MaintenanceServiceImpl.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl; + +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.MaintenanceRPCServiceAPI; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.MaintenanceService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.GetRequiredNetworkElementKeysOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.SetMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.ShowRequiredNetworkElementOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.TestMaintenanceModeOutputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.devicemanager.rev190109.show.required.network.element.output.RequiredNetworkElementBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MaintenanceServiceImpl implements MaintenanceService, MaintenanceRPCServiceAPI, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(MaintenanceServiceImpl.class); + + private final HtDatabaseMaintenanceService database; + + public MaintenanceServiceImpl(HtDatabaseClient client) throws ClassNotFoundException { + + LOG.info("Create {} start", MaintenanceServiceImpl.class); + database = new HtDatabaseMaintenanceService(client); + LOG.info("Create {} finished. DB Service {} started.", MaintenanceServiceImpl.class, client != null ? "sucessfully" : "not" ); + + } + + public void createIfNotExists(String mountPointNodeName) { + database.createIfNotExists(mountPointNodeName); + } + + public void deleteIfNotRequired(String mountPointNodeName) { + database.deleteIfNotRequired(mountPointNodeName); + } + + /*------------------------------------------------- + * Interface AutoClosable + */ + + @Override + public void close() throws Exception { + } + + /*------------------------------------------------- + * Interface MaintenanceRPCServiceAPI + */ + + @Override + public GetRequiredNetworkElementKeysOutputBuilder getRequiredNetworkElementKeys() { + List<MaintenanceEntity> all = database.getAll(); + + List<String> mountpointList = new ArrayList<>(); + for (MaintenanceEntity oneOfAll : all) { + mountpointList.add(oneOfAll.getNodeId()); + + } + GetRequiredNetworkElementKeysOutputBuilder outputBuilder = new GetRequiredNetworkElementKeysOutputBuilder(); + outputBuilder.setMountpointNames(mountpointList); + return outputBuilder; + } + + @Override + public ShowRequiredNetworkElementOutputBuilder showRequiredNetworkElement(ShowRequiredNetworkElementInput input) { + ShowRequiredNetworkElementOutputBuilder outputBuilder = new ShowRequiredNetworkElementOutputBuilder(); + MaintenanceEntity maintenanceMode = database.getMaintenance(input.getMountpointName()); + if (maintenanceMode != null) { + RequiredNetworkElementBuilder valueBuilder = new RequiredNetworkElementBuilder(); + + valueBuilder.setMountpointName(maintenanceMode.getNodeId()); + valueBuilder.setStatus(String.valueOf(MaintenanceCalculator.isONFObjectInMaintenance(maintenanceMode, "",""))); + valueBuilder.setDescription("Pretty description here"); + outputBuilder.setRequiredNetworkElement(valueBuilder.build()); + } else { + LOG.warn("No info in database for {}",input.getMountpointName()); + } + return outputBuilder; + } + + @Override + public GetMaintenanceModeOutputBuilder getMaintenanceMode(GetMaintenanceModeInput input) { + + GetMaintenanceModeOutputBuilder outputBuilder; + MaintenanceEntity maintenanceMode = database.getMaintenance(input.getMountpointName()); + if (maintenanceMode != null) { + outputBuilder = new GetMaintenanceModeOutputBuilder(maintenanceMode); + } else { + throw new IllegalArgumentException("No info in database for "+input.getMountpointName()); + } + return outputBuilder; + } + + @Override + public SetMaintenanceModeOutputBuilder setMaintenanceMode(SetMaintenanceModeInput input) { + + SetMaintenanceModeOutputBuilder outputBuilder = new SetMaintenanceModeOutputBuilder(); + MaintenanceBuilder mb = new MaintenanceBuilder(input); + MaintenanceEntity m = mb.build(); + database.setMaintenance(m); + return outputBuilder; + + } + + @Override + public TestMaintenanceModeOutputBuilder testMaintenanceMode(TestMaintenanceModeInput input) { + + StringBuffer resultString = new StringBuffer(); + + MaintenanceEntity maintenanceMode = database.getMaintenance(input.getMountpointName()); + + ZonedDateTime now = MaintenanceCalculator.valueOf(input.getTestDate()); + + resultString.append("In database table: "); + resultString.append(maintenanceMode != null); + resultString.append(" Maintenance active: "); + resultString.append(MaintenanceCalculator.isONFObjectInMaintenance(maintenanceMode, input.getObjectIdRef(), + input.getProblemName(), now)); + resultString.append(" at Timestamp: "); + resultString.append(now); + TestMaintenanceModeOutputBuilder outputBuilder = maintenanceMode != null + ? new TestMaintenanceModeOutputBuilder(maintenanceMode) + : new TestMaintenanceModeOutputBuilder(); + outputBuilder.setResultString(resultString.toString()); + return outputBuilder; + + } + + /*------------------------------------------------- + * Interface MaintenaceService + */ + + @Override + public boolean isONFObjectInMaintenance(String mountpointReference, String objectIdRef, String problem) { + MaintenanceEntity maintenanceMode = database.getMaintenance(mountpointReference); + boolean res = MaintenanceCalculator.isONFObjectInMaintenance(maintenanceMode, objectIdRef, problem); + LOG.debug("inMaintenance={} for mountpoint/id/problem:{} {} {} Definition: {}",res, mountpointReference, objectIdRef, problem, this ); + return res; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/MicrowaveModelPerformanceDataProvider.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/MicrowaveModelPerformanceDataProvider.java new file mode 100644 index 000000000..c3e4c1e4e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/MicrowaveModelPerformanceDataProvider.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; + + +/** + * Identify the NE as provider for performance data according to microwave model. + * + * @author herbert + */ + +public interface MicrowaveModelPerformanceDataProvider { + + public void resetPMIterator(); + + public boolean hasNext(); + + public void next(); + + public AllPm getHistoricalPM(); + + public String pmStatusToString(); + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerImpl.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerImpl.java new file mode 100644 index 000000000..9ad1b2578 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerImpl.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl; + +import org.eclipse.jdt.annotation.Nullable; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.config.PmConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.service.MicrowaveHistoricalPerformanceWriterService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PerformanceManagerImpl implements DeviceManagerService, AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(PerformanceManagerImpl.class); + + private @Nullable PerformanceManagerTask task; + + public PerformanceManagerImpl(long seconds, MicrowaveHistoricalPerformanceWriterService databaseService, ConfigurationFileRepresentation config) { + + LOG.info("Construct {}", PerformanceManagerImpl.class.getSimpleName()); + + this.task = null; + PmConfig configurationPM = new PmConfig(config); + LOG.info("Performance manager configuration: {}", configurationPM); + + if (!configurationPM.isPerformanceManagerEnabled()) { + LOG.info("Don't start performance manager"); + + } else { + LOG.info("{} Seconds", seconds); + if (MicrowaveHistoricalPerformanceWriterService.isAvailable(databaseService)) { + + LOG.info("Start of PM task"); + task = new PerformanceManagerTask(seconds, databaseService); + task.start(); + LOG.info("PM task scheduled"); + + } else { + LOG.info("Database not available. Do not start PM task"); + } + } + + LOG.info("Construct end {}", PerformanceManagerImpl.class.getSimpleName()); + } + + @Override + public void close() { + LOG.info("Close {}", PerformanceManagerImpl.class.getSimpleName()); + if (task != null) { + task.stop(); + } + } + + public void registration(String mountPointNodeName, ONFCoreNetworkElementRepresentation ne) { + LOG.debug("Register {}",mountPointNodeName); + if (task != null) { + task.registration(mountPointNodeName, ne); + } + } + + public void deRegistration(String mountPointNodeName) { + LOG.debug("Deregister {}",mountPointNodeName); + if (task != null) { + task.deRegistration(mountPointNodeName); + } + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerTask.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerTask.java new file mode 100644 index 000000000..3d8116816 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/PerformanceManagerTask.java @@ -0,0 +1,238 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl; + +import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.ONFCoreNetworkElementRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.service.MicrowaveHistoricalPerformanceWriterService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PerformanceManagerTask implements Runnable { + + private static final Logger LOG = LoggerFactory.getLogger(PerformanceManagerTask.class); + private static final String LOGMARKER = "PMTick"; + + private int tickCounter = 0; + + private final ConcurrentHashMap<String, ONFCoreNetworkElementRepresentation> queue = new ConcurrentHashMap<>(); + private final MicrowaveHistoricalPerformanceWriterService databaseService; + private final ScheduledExecutorService scheduler; + private final long seconds; + + private ScheduledFuture<?> taskHandle = null; + private Iterator<ONFCoreNetworkElementRepresentation> neIterator = null; + private ONFCoreNetworkElementRepresentation actualNE = null; + + /** + * Constructor of PM Task + * @param seconds seconds to call PM Task + * @param databaseService DB Service to load PM data to + */ + + public PerformanceManagerTask(long seconds, MicrowaveHistoricalPerformanceWriterService databaseService) { + + LOG.debug("Init task {}", PerformanceManagerTask.class.getSimpleName()); + this.seconds = seconds; + this.databaseService = databaseService; + this.scheduler = Executors.newSingleThreadScheduledExecutor(); + + } + + /** + * Start PM Task + */ + public void start() { + LOG.info("PM task created"); + taskHandle = this.scheduler.scheduleAtFixedRate(this, 0, seconds, TimeUnit.SECONDS); + LOG.info("PM task scheduled"); + } + + /** + * Stop everything + */ + public void stop() { + LOG.info("Stop {}", PerformanceManagerImpl.class.getSimpleName()); + if (taskHandle != null) { + taskHandle.cancel(true); + try { + scheduler.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOG.debug("Schdule stopped.",e); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } + } + } + + /** + * Add NE/Mountpoint to PM Processig + * @param mountPointNodeName to be added + * @param ne that is connected to the mountpoint + */ + public void registration(String mountPointNodeName, ONFCoreNetworkElementRepresentation ne) { + queue.put(mountPointNodeName, ne); + } + + /** + * Remove mountpoint/NE from PM process + * @param mountPointNodeName that has to be removed + */ + public void deRegistration(String mountPointNodeName) { + LOG.debug("Deregister {}",mountPointNodeName); + ONFCoreNetworkElementRepresentation removedNE = queue.remove(mountPointNodeName); + + if ( removedNE == null) { + LOG.warn("Couldn't delete {}",mountPointNodeName); + } + } + + + /*-------------------------------------------------------------- + * Task to read PM data from NE + */ + + /** + * Task runner to read all performance data from Network Elements. + * Catch exceptions to make sure, that the Task is not stopped. + */ + @Override + public void run() { + + LOG.debug("{} start {} Start with mountpoint {}",LOGMARKER, tickCounter, actualNE == null ? "No NE" : actualNE.getMountPointNodeName()); + + //Proceed to next NE/Interface + getNextInterface(); + + LOG.debug("{} {} Next interface to handle {}", LOGMARKER, tickCounter, + actualNE == null ? "No NE/IF" : actualNE.getMountPointNodeName() + " " + actualNE.pmStatusToString()); + + if (actualNE != null) { + try { + LOG.debug("{} Start to read PM from NE ({})", LOGMARKER, tickCounter); + AllPm allPm = actualNE.getHistoricalPM(); + LOG.debug("{} {} Got PM list. Start write to DB", LOGMARKER, tickCounter); + databaseService.writePM(allPm); + LOG.debug("{} {} PM List end.", LOGMARKER, tickCounter); + } catch (Exception e) { + LOG.warn("{} {} PM read/write failed. Write log entry {}", LOGMARKER, tickCounter, e); + String msg = e.getMessage(); + if (msg == null || msg.isEmpty()) { + if (e.getCause() != null) { + msg = e.getCause().toString(); + } + if (msg == null || msg.isEmpty()){ + msg = "No message or cause"; + } + } + databaseService.writePMLog(actualNE.getMountPointNodeName(), actualNE.pmStatusToString(), msg); + } + } + + LOG.debug("{} end {}",LOGMARKER, tickCounter); + tickCounter++; + } + + /** + * Reset queue to start from beginning + */ + private void resetQueue() { + actualNE = null; + neIterator = null; + } + + /** + * Get then next interface in the list. + * First try to find a next on the actual NE. + * If not available search next interface at a NE + * Special Situations to handle: Empty queue, NEs, but no interfaces + */ + private void getNextInterface() { + boolean started = false; + int loopCounter = 0; + + LOG.debug("{} {} getNextInterface enter. Queue size {} ", LOGMARKER, tickCounter, queue.size()); + + if (actualNE != null && !queue.containsValue(actualNE)) { + LOG.debug("{} {} NE Removed duringprocessing A",LOGMARKER, tickCounter); + resetQueue(); + } + + while (true) { + + if (loopCounter++ >= 1000) { + LOG.error("{} {} Problem in PM iteration. endless condition reached", LOGMARKER, tickCounter); + resetQueue(); + break; + } + + LOG.debug("{} {} Loop ne {}:neiterator {}:Interfaceiterator:{} Loop:{}", + LOGMARKER, + tickCounter, + actualNE == null? "null" : actualNE.getMountPointNodeName(), + neIterator == null ? "null" : neIterator.hasNext(), + actualNE == null ? "null" : actualNE.hasNext(), + loopCounter); + + if (actualNE != null && actualNE.hasNext()) { + // Yes, there is an interface, deliver back + LOG.debug("{} {} getNextInterface yes A",LOGMARKER, tickCounter); + actualNE.next(); + break; + + } else { + // No element in neInterfaceInterator .. get next NE and try + if (neIterator != null && neIterator.hasNext()) { + // Set a new NE + LOG.debug("{} {} Next NE A",LOGMARKER, tickCounter); + actualNE = neIterator.next(); + actualNE.resetPMIterator(); + + } else { + // Goto start condition 1) first entry 2) end of queue reached + LOG.debug("{} {} Reset",LOGMARKER, tickCounter); + resetQueue(); + + if (queue.isEmpty()) { + LOG.debug("{} {} no nextInterfac. queue empty",LOGMARKER, tickCounter); + break; + } else if (!started){ + LOG.debug("{} {} getNextInterface start condition. Get interator.",LOGMARKER, tickCounter); + neIterator = queue.values().iterator(); + started = true; + } else { + LOG.debug("{} {} no nextInterface",LOGMARKER, tickCounter); + break; + } + } + } + } //while + + if (actualNE != null && !queue.containsValue(actualNE)) { + LOG.debug("{} {} NE Removed duringprocessing B",LOGMARKER, tickCounter); + resetQueue(); + } + + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/config/PmConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/config/PmConfig.java new file mode 100644 index 000000000..e4d06c6fb --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/config/PmConfig.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.config; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; + +public class PmConfig implements Configuration { + + private static final String SECTION_MARKER_PM = "pm"; + + private static final String PROPERTY_KEY_ENABLED = "pmEnabled"; + private static final String DEFAULT_VALUE_ENABLED = String.valueOf(true); + + + private final ConfigurationFileRepresentation configuration; + + public PmConfig(ConfigurationFileRepresentation configuration) { + this.configuration = configuration; + this.configuration.addSection(SECTION_MARKER_PM); + defaults(); + } + + public boolean isPerformanceManagerEnabled() { + return configuration.getPropertyBoolean(SECTION_MARKER_PM, PROPERTY_KEY_ENABLED); + } + + @Override + public String getSectionName() { + return SECTION_MARKER_PM; + } + + @Override + public void defaults() { + //Add default if not available + configuration.setPropertyIfNotAvailable(SECTION_MARKER_PM, PROPERTY_KEY_ENABLED, DEFAULT_VALUE_ENABLED); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/service/MicrowaveHistoricalPerformanceWriterService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/service/MicrowaveHistoricalPerformanceWriterService.java new file mode 100644 index 000000000..ef57b1088 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/service/MicrowaveHistoricalPerformanceWriterService.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.service; + +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.AllPm; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.database.HtDataBaseReaderAndWriter; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance15Minutes; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformance24Hours; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types.EsHistoricalPerformanceLogEntry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MicrowaveHistoricalPerformanceWriterService { + + private static final Logger LOG = LoggerFactory.getLogger(MicrowaveHistoricalPerformanceWriterService.class); + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + + private final HtDatabaseClient client; + private HtDataBaseReaderAndWriter<EsHistoricalPerformance15Minutes> historicalPerformance15mRW; + private HtDataBaseReaderAndWriter<EsHistoricalPerformance24Hours> historicalPerformance24hRW; + private HtDataBaseReaderAndWriter<EsHistoricalPerformanceLogEntry> historicalPerformanceLogRW; + + public MicrowaveHistoricalPerformanceWriterService(HtDatabaseClient client) { + + LOG.info("Create {} start", MicrowaveHistoricalPerformanceWriterService.class); + this.client = client; + try { + + historicalPerformance15mRW = new HtDataBaseReaderAndWriter<>(client, + EsHistoricalPerformance15Minutes.ESDATATYPENAME, EsHistoricalPerformance15Minutes.class); + historicalPerformance24hRW = new HtDataBaseReaderAndWriter<>(client, + EsHistoricalPerformance24Hours.ESDATATYPENAME, EsHistoricalPerformance24Hours.class); + historicalPerformanceLogRW = new HtDataBaseReaderAndWriter<>(client, + EsHistoricalPerformanceLogEntry.ESDATATYPENAME, EsHistoricalPerformanceLogEntry.class); + + } catch (Exception e) { + client = null; + LOG.error("Can not start database client. Exception: {}", e.getMessage()); + } + + LOG.info("Create {} finished. DB Service {} started.", MicrowaveHistoricalPerformanceWriterService.class, + client != null ? "sucessfully" : "not"); + } + + + public void writePM(AllPm pm) { + + LOG.debug("Write {} pm records", pm.size()); + + LOG.debug("Write 15m write to DB"); + historicalPerformance15mRW.doWrite(pm.getPm15()); + LOG.debug("Write 15m done, Write 24h write to DB"); + historicalPerformance24hRW.doWrite(pm.getPm24()); + LOG.debug("Write 24h done"); + + } + + public void writePMLog(String mountpointName, String layerProtocolName, String msg) { + + LOG.debug("Write PM Log: {}", msg); + EsHistoricalPerformanceLogEntry logEntry = new EsHistoricalPerformanceLogEntry(mountpointName, + layerProtocolName, NETCONFTIME_CONVERTER.getTimeStamp().getValue(), msg); + historicalPerformanceLogRW.doWrite(logEntry); + LOG.debug("Write PM Log done"); + + } + + + static public boolean isAvailable(MicrowaveHistoricalPerformanceWriterService s) { + + if (s == null || s.client == null) { + return false; + } + return true; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance15Minutes.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance15Minutes.java new file mode 100644 index 000000000..6754fced9 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance15Minutes.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types; + +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EsHistoricalPerformance15Minutes extends EsHistoricalPerformanceBase { + + public static final String ESDATATYPENAME = "historicalperformance15min"; + + private static final Logger LOG = LoggerFactory.getLogger(EsHistoricalPerformance15Minutes.class); + + public EsHistoricalPerformance15Minutes(String nodeName, Lp lp) { + super(nodeName, lp); + } + + public <T extends OtnHistoryDataG> EsHistoricalPerformance15Minutes setHistoricalRecord15Minutes(OtnHistoryDataG record) { + if (record.getGranularityPeriod() != org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType.Period15Min) { + LOG.warn("Granularity mismatch for {} expected {} found {}", getNodeName(),getUuidInterface(), org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType.Period15Min, record.getGranularityPeriod()); + } + set(record); + return this; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance24Hours.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance24Hours.java new file mode 100644 index 000000000..03c68451d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformance24Hours.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types; + +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; + +public class EsHistoricalPerformance24Hours extends EsHistoricalPerformanceBase { + + public static final String ESDATATYPENAME = "historicalperformance24h"; + + public EsHistoricalPerformance24Hours(String nodeName, Lp lp) { + super(nodeName, lp); + } + + public <T extends OtnHistoryDataG> EsHistoricalPerformance24Hours setHistoricalRecord24Hours(T record) { + set(record); + return this; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceBase.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceBase.java new file mode 100644 index 000000000..544e46cbe --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceBase.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types; + +import org.onap.ccsdk.features.sdnr.wt.base.netconf.util.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsObject; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.LinkIdentifyingObject; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.core.model.rev170320.logical.termination.point.g.Lp; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class EsHistoricalPerformanceBase extends EsObject { + + private static final Logger LOG = LoggerFactory.getLogger(EsHistoricalPerformanceBase.class); + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + + @JsonIgnore private final String nodeName; + @JsonIgnore private final String uuidInterface; + @JsonIgnore private final String layerProtocolName; + + @JsonIgnore private String radioSignalId = null; //Meaning of connection Id + @JsonIgnore private String timeStamp = null; + @JsonIgnore private Boolean suspectIntervalFlag = null; + @JsonIgnore private String granularityPeriod = null; //Representation of GranularityPeriodType + @JsonIgnore private String scannerId = null; + @JsonIgnore private Object performanceData = null; + + + public EsHistoricalPerformanceBase(String nodeName, Lp actualInterface) { + this.nodeName = nodeName; + this.uuidInterface = actualInterface.getUuid().getValue(); + this.layerProtocolName = actualInterface.getLayerProtocolName().getValue(); + + } + + protected <T extends OtnHistoryDataG> void set(T record) { + if (record == null) { + LOG.warn("PM Record: null record. Can not handle"); + return; + } + + if (LOG.isTraceEnabled()) { + LOG.trace("PM Record: class {} '{}' ", record.getClass().getSimpleName(), record); + } + + timeStamp = NETCONFTIME_CONVERTER.getTimeStampFromNetconf(record.getPeriodEndTime().getValue()); + suspectIntervalFlag = record.isSuspectIntervalFlag(); + granularityPeriod = getYangGranularityPeriodString( record.getGranularityPeriod() ); + scannerId = record.getHistoryDataId(); + + if (record instanceof LinkIdentifyingObject) { + radioSignalId = ((LinkIdentifyingObject) record).getSignalId(); + } + + performanceData = new EsPerformanceData(record); + setEsId(genSpecificEsId(record.getPeriodEndTime().getValue())); + } + + + @JsonGetter("node-name") + public String getNodeName() { + return nodeName; + } + + @JsonGetter("uuid-interface") + public String getUuidInterface() { + return uuidInterface; + } + + @JsonGetter("layer-protocol-name") + public String getLayerProtocolName() { + return layerProtocolName; + } + + @JsonGetter("radio-signal-id") + public String getRadioSignalId() { + return radioSignalId; + } + + @JsonGetter("time-stamp") + public String getTimeStamp() { + return timeStamp; + } + + @JsonGetter("suspect-interval-flag") + public Boolean getSuspect() { + return suspectIntervalFlag; + } + + @JsonGetter("granularity-period") + public String getGranularityPeriod() { + return granularityPeriod; + } + + @JsonGetter("scanner-id") + public String getScannerId() { + return scannerId; + } + + @JsonGetter("performance-data") + public Object getData() { + return performanceData; + } + + + + //Adapt JSON Text + //@JsonGetter("granularityPeriod") + + private static String getYangGranularityPeriodString(org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType yangGanularityPeriod) { + switch(yangGanularityPeriod == null ? org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.GranularityPeriodType.Unknown : yangGanularityPeriod) { + case Period15Min: + return "PERIOD_15MIN"; + case Period24Hours: + return "PERIOD_24HOURS"; + default: + return "PERIOD_UNKOWN"; + } + } + + /** + * Create a specific ES id for the current log. + * @param time is the input. + * @return a string with the generated ES Id + */ + protected String genSpecificEsId(String time) { + + StringBuffer strBuf = new StringBuffer(); + strBuf.append(nodeName); + strBuf.append("/"); + strBuf.append(uuidInterface); + strBuf.append("/"); + strBuf.append(time == null || time.isEmpty() ? "Empty" : time); + + return strBuf.toString(); + } + + @Override + public String toString() { + return "EsHistoricalPerformanceBase [nodeName=" + nodeName + ", uuidInterface=" + uuidInterface + + ", layerProtocolName=" + layerProtocolName + ", radioSignalId=" + radioSignalId + ", timeStamp=" + + timeStamp + ", suspectIntervalFlag=" + suspectIntervalFlag + ", granularityPeriod=" + + granularityPeriod + ", scannerId=" + scannerId + ", performanceData=" + performanceData + "]"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceLogEntry.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceLogEntry.java new file mode 100644 index 000000000..57872d8af --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsHistoricalPerformanceLogEntry.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types; + +import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsObject; + +/** + * + * Event from Network to be recorded in the database + * + */ + +public class EsHistoricalPerformanceLogEntry extends EsObject { + + public static final String ESDATATYPENAME = "performancelog"; + + private String mountpoint; + private String interfaceIdx; + private String timeStamp; + private String logText; + + /** + * Create Log entry for NE/Interfaceproblems during PM execution + * @param mountpoint Name of + * @param interfaceIdx Name of + * @param timeStamp Time and date of occurence + * @param logText to write + */ + public EsHistoricalPerformanceLogEntry(String mountpoint, String interfaceIdx, String timeStamp, String logText) { + super(); + this.mountpoint = mountpoint; + this.interfaceIdx = interfaceIdx; + this.timeStamp = timeStamp; + this.logText = logText; + } + + /** + * For jackson purpose + */ + EsHistoricalPerformanceLogEntry() { + } + + /** + * @return the mountpoint + */ + public String getMountpoint() { + return mountpoint; + } + + /** + * @return the interfaceIdx + */ + public String getInterfaceIdx() { + return interfaceIdx; + } + + /** + * @return the timeStamp + */ + public String getTimeStamp() { + return timeStamp; + } + + /** + * @return the logText + */ + public String getLogText() { + return logText; + } + + + + public static String getEsdatatypename() { + return ESDATATYPENAME; + } + + } diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsPerformanceData.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsPerformanceData.java new file mode 100644 index 000000000..607d1900a --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/performancemanager/impl/database/types/EsPerformanceData.java @@ -0,0 +1,445 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.database.types; + +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType12; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType1211; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.onfcore.container.ExtendedAirInterfaceHistoricalPerformanceType1211p; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.g._874._1.model.rev170320.OtnHistoryDataG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfaceHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.AirInterfacePerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ContainerHistoricalPerformanceTypeG; +import org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev170324.ContainerPerformanceTypeG; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EsPerformanceData { + + @JsonIgnore + private static final Logger LOG = LoggerFactory.getLogger(EsPerformanceData.class); + + @JsonIgnore + private AirInterfacePerformanceTypeG dataAirInterface12 = null; + @JsonIgnore + private ContainerPerformanceTypeG dataEthContainer12 = null; + + @JsonIgnore + private org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfacePerformanceTypeG dataAirInterface1211 = null; + @JsonIgnore + private org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ContainerPerformanceTypeG dataEthContainer1211 = null; + + @JsonIgnore + private org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfacePerformanceTypeG dataAirInterface1211p = null; + @JsonIgnore + private org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ContainerPerformanceTypeG dataEthContainer1211p = null; + + public <T extends OtnHistoryDataG> EsPerformanceData(T otnHistoryData) { + + if (otnHistoryData instanceof AirInterfaceHistoricalPerformanceTypeG) { + this.dataAirInterface12 = ((AirInterfaceHistoricalPerformanceTypeG) otnHistoryData).getPerformanceData(); + } else if (otnHistoryData instanceof ContainerHistoricalPerformanceTypeG) { + this.dataEthContainer12 = ((ContainerHistoricalPerformanceTypeG) otnHistoryData).getPerformanceData(); + } else if (otnHistoryData instanceof ExtendedAirInterfaceHistoricalPerformanceType12) { + this.dataAirInterface12 = ((ExtendedAirInterfaceHistoricalPerformanceType12) otnHistoryData) + .getAirInterfaceHistoricalPerformanceType().getPerformanceData(); + } else if (otnHistoryData instanceof org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceHistoricalPerformanceTypeG) { + this.dataAirInterface1211 = ((org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.AirInterfaceHistoricalPerformanceTypeG) otnHistoryData) + .getPerformanceData(); + } else if (otnHistoryData instanceof org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ContainerHistoricalPerformanceTypeG) { + this.dataEthContainer1211 = ((org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev180907.ContainerHistoricalPerformanceTypeG) otnHistoryData) + .getPerformanceData(); + } else if (otnHistoryData instanceof ExtendedAirInterfaceHistoricalPerformanceType1211) { + this.dataAirInterface1211 = ((ExtendedAirInterfaceHistoricalPerformanceType1211) otnHistoryData) + .getAirInterfaceHistoricalPerformanceType().getPerformanceData(); + } else if (otnHistoryData instanceof org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceHistoricalPerformanceTypeG) { + this.dataAirInterface1211p = ((org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.AirInterfaceHistoricalPerformanceTypeG) otnHistoryData) + .getPerformanceData(); + } else if (otnHistoryData instanceof org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ContainerHistoricalPerformanceTypeG) { + this.dataEthContainer1211p = ((org.opendaylight.yang.gen.v1.urn.onf.params.xml.ns.yang.microwave.model.rev181010.ContainerHistoricalPerformanceTypeG) otnHistoryData) + .getPerformanceData(); + } else if (otnHistoryData instanceof ExtendedAirInterfaceHistoricalPerformanceType1211p) { + this.dataAirInterface1211p = ((ExtendedAirInterfaceHistoricalPerformanceType1211p) otnHistoryData) + .getAirInterfaceHistoricalPerformanceType().getPerformanceData(); + } else { + LOG.warn("Can not assign historical performance type {}", otnHistoryData.getClass().getName()); + } + } + + @JsonGetter("es") + public java.lang.Integer getEs() { + return dataAirInterface12 != null ? dataAirInterface12.getEs() + : dataAirInterface1211 != null ? dataAirInterface1211.getEs() + : dataAirInterface1211p != null ? dataAirInterface1211p.getEs() : null; + } + + @JsonGetter("ses") + java.lang.Integer getSes() { + return dataAirInterface12 != null ? dataAirInterface12.getSes() + : dataAirInterface1211 != null ? dataAirInterface1211.getSes() + : dataAirInterface1211p != null ? dataAirInterface1211p.getSes() : null; + } + + @JsonGetter("cses") + java.lang.Integer getCses() { + return dataAirInterface12 != null ? dataAirInterface12.getCses() + : dataAirInterface1211 != null ? dataAirInterface1211.getCses() + : dataAirInterface1211p != null ? dataAirInterface1211p.getCses() : null; + } + + @JsonGetter("unavailability") + java.lang.Integer getUnavailability() { + return dataAirInterface12 != null ? dataAirInterface12.getUnavailability() + : dataAirInterface1211 != null ? dataAirInterface1211.getUnavailability() + : dataAirInterface1211p != null ? dataAirInterface1211p.getUnavailability() : null; + } + + @JsonGetter("tx-level-min") + java.lang.Byte getTxLevelMin() { + return dataAirInterface12 != null ? dataAirInterface12.getTxLevelMin() + : dataAirInterface1211 != null ? dataAirInterface1211.getTxLevelMin() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTxLevelMin() : null; + } + + @JsonGetter("tx-level-max") + java.lang.Byte getTxLevelMax() { + return dataAirInterface12 != null ? dataAirInterface12.getTxLevelMax() + : dataAirInterface1211 != null ? dataAirInterface1211.getTxLevelMax() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTxLevelMax() : null; + } + + @JsonGetter("tx-level-avg") + java.lang.Byte getTxLevelAvg() { + return dataAirInterface12 != null ? dataAirInterface12.getTxLevelAvg() + : dataAirInterface1211 != null ? dataAirInterface1211.getTxLevelAvg() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTxLevelAvg() : null; + } + + @JsonGetter("rx-level-min") + java.lang.Byte getRxLevelMin() { + return dataAirInterface12 != null ? dataAirInterface12.getRxLevelMin() + : dataAirInterface1211 != null ? dataAirInterface1211.getRxLevelMin() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRxLevelMin() : null; + } + + @JsonGetter("rx-level-max") + java.lang.Byte getRxLevelMax() { + return dataAirInterface12 != null ? dataAirInterface12.getRxLevelMax() + : dataAirInterface1211 != null ? dataAirInterface1211.getRxLevelMax() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRxLevelMax() : null; + } + + @JsonGetter("rx-level-avg") + java.lang.Byte getRxLevelAvg() { + return dataAirInterface12 != null ? dataAirInterface12.getRxLevelAvg() + : dataAirInterface1211 != null ? dataAirInterface1211.getRxLevelAvg() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRxLevelAvg() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time2-states") + java.lang.Integer getTime2States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime2States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime2States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime2States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time4-states-s") + java.lang.Integer getTime4StatesS() { + return dataAirInterface12 != null ? dataAirInterface12.getTime4StatesS() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime4StatesS() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime4StatesS() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time4-states") + java.lang.Integer getTime4States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime4States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime4States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime4States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time8-states") + java.lang.Integer getTime8States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime8States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime8States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime8States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time16-states-s") + java.lang.Integer getTime16StatesS() { + return dataAirInterface12 != null ? dataAirInterface12.getTime16StatesS() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime16StatesS() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime16StatesS() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time16-states") + java.lang.Integer getTime16States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime16States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime16States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime16States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time32-states") + java.lang.Integer getTime32States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime32States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime32States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime32States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time64-states") + java.lang.Integer getTime64States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime64States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime64States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime64States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time128-states") + java.lang.Integer getTime128States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime128States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime128States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime128States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time256-states") + java.lang.Integer getTime256States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime256States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime256States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime256States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time512-states") + java.lang.Integer getTime512States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime512States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime512States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime512States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time512-states-l") + java.lang.Integer getTime512StatesL() { + return dataAirInterface12 != null ? dataAirInterface12.getTime512StatesL() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime512StatesL() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime512StatesL() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time1024-states") + java.lang.Integer getTime1024States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime1024States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime1024States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime1024States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time1024-states-l") + java.lang.Integer getTime1024StatesL() { + return dataAirInterface12 != null ? dataAirInterface12.getTime1024StatesL() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime1024StatesL() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime1024StatesL() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time2048-states") + java.lang.Integer getTime2048States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime2048States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime2048States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime2048States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time2048-states-l") + java.lang.Integer getTime2048StatesL() { + return dataAirInterface12 != null ? dataAirInterface12.getTime2048StatesL() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime2048StatesL() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime2048StatesL() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time4096-states") + java.lang.Integer getTime4096States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime4096States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime4096States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime4096States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time4096-states-l") + java.lang.Integer getTime4096StatesL() { + return dataAirInterface12 != null ? dataAirInterface12.getTime4096StatesL() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime4096StatesL() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime4096StatesL() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time8192-states") + java.lang.Integer getTime8192States() { + return dataAirInterface12 != null ? dataAirInterface12.getTime8192States() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime8192States() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTime8192States() : null; + } + + @SuppressWarnings("deprecation") + @JsonGetter("time8192-states-l") + java.lang.Integer getTime8192StatesL() { + return dataAirInterface12 != null ? dataAirInterface12.getTime8192StatesL() + : dataAirInterface1211 != null ? dataAirInterface1211.getTime8192StatesL() + : dataAirInterface1211p != null ? dataAirInterface1211p.getEs() : null; + } + + @JsonGetter("snir-min") + java.lang.Byte getSnirMin() { + return dataAirInterface12 != null ? dataAirInterface12.getSnirMin() + : dataAirInterface1211 != null ? dataAirInterface1211.getSnirMin() + : dataAirInterface1211p != null ? dataAirInterface1211p.getSnirMin() : null; + } + + @JsonGetter("snir-max") + java.lang.Byte getSnirMax() { + return dataAirInterface12 != null ? dataAirInterface12.getSnirMax() + : dataAirInterface1211 != null ? dataAirInterface1211.getSnirMax() + : dataAirInterface1211p != null ? dataAirInterface1211p.getSnirMax() : null; + } + + @JsonGetter("snir-avg") + java.lang.Byte getSnirAvg() { + return dataAirInterface12 != null ? dataAirInterface12.getSnirAvg() + : dataAirInterface1211 != null ? dataAirInterface1211.getSnirAvg() + : dataAirInterface1211p != null ? dataAirInterface1211p.getSnirAvg() : null; + } + + @JsonGetter("xpd-min") + java.lang.Byte getXpdMin() { + return dataAirInterface12 != null ? dataAirInterface12.getXpdMin() + : dataAirInterface1211 != null ? dataAirInterface1211.getXpdMin() + : dataAirInterface1211p != null ? dataAirInterface1211p.getXpdMin() : null; + } + + @JsonGetter("xpd-max") + java.lang.Byte getXpdMax() { + return dataAirInterface12 != null ? dataAirInterface12.getXpdMax() + : dataAirInterface1211 != null ? dataAirInterface1211.getXpdMax() + : dataAirInterface1211p != null ? dataAirInterface1211p.getXpdMax() : null; + } + + @JsonGetter("xpd-avg") + java.lang.Byte getXpdAvg() { + return dataAirInterface12 != null ? dataAirInterface12.getXpdAvg() + : dataAirInterface1211 != null ? dataAirInterface1211.getXpdAvg() + : dataAirInterface1211p != null ? dataAirInterface1211p.getXpdAvg() : null; + } + + @JsonGetter("rf-temp-min") + java.lang.Byte getRfTempMin() { + return dataAirInterface12 != null ? dataAirInterface12.getRfTempMin() + : dataAirInterface1211 != null ? dataAirInterface1211.getRfTempMin() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRfTempMin() : null; + } + + @JsonGetter("rf-temp-max") + java.lang.Byte getRfTempMax() { + return dataAirInterface12 != null ? dataAirInterface12.getRfTempMax() + : dataAirInterface1211 != null ? dataAirInterface1211.getRfTempMax() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRfTempMax() : null; + } + + @JsonGetter("rf-temp-avg") + java.lang.Byte getRfTempAvg() { + return dataAirInterface12 != null ? dataAirInterface12.getRfTempAvg() + : dataAirInterface1211 != null ? dataAirInterface1211.getRfTempAvg() + : dataAirInterface1211p != null ? dataAirInterface1211p.getRfTempAvg() : null; + } + + @JsonGetter("defect-blocks-sum") + java.lang.Short getDefectBlocksSum() { + return dataAirInterface12 != null ? dataAirInterface12.getDefectBlocksSum() + : dataAirInterface1211 != null ? dataAirInterface1211.getDefectBlocksSum() + : dataAirInterface1211p != null ? dataAirInterface1211p.getDefectBlocksSum() : null; + } + + @JsonGetter("time-period") + java.lang.Integer getTimePeriod() { + return dataAirInterface12 != null ? dataAirInterface12.getTimePeriod() + : dataEthContainer12 != null ? dataEthContainer12.getTimePeriod() + : dataAirInterface1211 != null ? dataAirInterface1211.getTimePeriod() + : dataEthContainer1211 != null ? dataEthContainer1211.getTimePeriod() + : dataAirInterface1211p != null ? dataAirInterface1211p.getTimePeriod() + : dataEthContainer1211p != null ? dataEthContainer1211p.getTimePeriod() + : null; + } + + @JsonGetter("tx-ethernet-bytes-max-s") + java.lang.Integer getTxEthernetBytesMaxS() { + return dataEthContainer12 != null ? dataEthContainer12.getTxEthernetBytesMaxS() + : dataEthContainer1211 != null ? dataEthContainer1211.getTxEthernetBytesMaxS() + : dataEthContainer1211p != null ? dataEthContainer1211p.getTxEthernetBytesMaxS() : null; + } + + @JsonGetter("tx-ethernet-bytes-max-m") + java.lang.Long getTxEthernetBytesMaxM() { + return dataEthContainer12 != null ? dataEthContainer12.getTxEthernetBytesMaxM() + : dataEthContainer1211 != null ? dataEthContainer1211.getTxEthernetBytesMaxM() + : dataEthContainer1211p != null ? dataEthContainer1211p.getTxEthernetBytesMaxM() : null; + } + + @JsonGetter("tx-ethernet-bytes-sum") + public java.lang.Long getTxEthernetBytesSum() { + return dataEthContainer12 != null ? dataEthContainer12.getTxEthernetBytesSum() + : dataEthContainer1211 != null ? dataEthContainer1211.getTxEthernetBytesSum() + : dataEthContainer1211p != null ? dataEthContainer1211p.getTxEthernetBytesSum() : null; + } + + @Override + public String toString() { + return "EsPerformanceData [getEs()=" + getEs() + ", getSes()=" + getSes() + ", getCses()=" + getCses() + + ", getUnavailability()=" + getUnavailability() + ", getTxLevelMin()=" + getTxLevelMin() + + ", getTxLevelMax()=" + getTxLevelMax() + ", getTxLevelAvg()=" + getTxLevelAvg() + ", getRxLevelMin()=" + + getRxLevelMin() + ", getRxLevelMax()=" + getRxLevelMax() + ", getRxLevelAvg()=" + getRxLevelAvg() + + ", getTime2States()=" + getTime2States() + ", getTime4StatesS()=" + getTime4StatesS() + + ", getTime4States()=" + getTime4States() + ", getTime8States()=" + getTime8States() + + ", getTime16StatesS()=" + getTime16StatesS() + ", getTime16States()=" + getTime16States() + + ", getTime32States()=" + getTime32States() + ", getTime64States()=" + getTime64States() + + ", getTime128States()=" + getTime128States() + ", getTime256States()=" + getTime256States() + + ", getTime512States()=" + getTime512States() + ", getTime512StatesL()=" + getTime512StatesL() + + ", getTime1024States()=" + getTime1024States() + ", getTime1024StatesL()=" + getTime1024StatesL() + + ", getTime2048States()=" + getTime2048States() + ", getTime2048StatesL()=" + getTime2048StatesL() + + ", getTime4096States()=" + getTime4096States() + ", getTime4096StatesL()=" + getTime4096StatesL() + + ", getTime8192States()=" + getTime8192States() + ", getTime8192StatesL()=" + getTime8192StatesL() + + ", getSnirMin()=" + getSnirMin() + ", getSnirMax()=" + getSnirMax() + ", getSnirAvg()=" + getSnirAvg() + + ", getXpdMin()=" + getXpdMin() + ", getXpdMax()=" + getXpdMax() + ", getXpdAvg()=" + getXpdAvg() + + ", getRfTempMin()=" + getRfTempMin() + ", getRfTempMax()=" + getRfTempMax() + ", getRfTempAvg()=" + + getRfTempAvg() + ", getDefectBlocksSum()=" + getDefectBlocksSum() + ", getTimePeriod()=" + + getTimePeriod() + ", getTxEthernetBytesMaxS()=" + getTxEthernetBytesMaxS() + + ", getTxEthernetBytesMaxM()=" + getTxEthernetBytesMaxM() + ", getTxEthernetBytesSum()=" + + getTxEthernetBytesSum() + "]"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayFilter.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayFilter.java new file mode 100644 index 000000000..92af68bc0 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayFilter.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter; + +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NotificationDelayFilter<T> implements AutoCloseable { + + private static final Logger LOG = LoggerFactory.getLogger(NotificationDelayFilter.class); + + private final ConcurrentHashMap <String, NotificationWithServerTimeStamp<T>> problemItems; +// private final HashMap<String, NotificationWithServerTimeStamp<T>> nonProblemItems; + private final NotificationDelayedListener<T> timeoutListener; + + private static long delay; + private static boolean enabled; + + public static void setDelay(long l) { + NotificationDelayFilter.delay = l; + } + + public static long getDelay() { + return NotificationDelayFilter.delay; + } + + public static boolean isEnabled() { + return NotificationDelayFilter.enabled; + } + + public static void setEnabled(boolean enabled) { + NotificationDelayFilter.enabled = enabled; + } + + private final ScheduledExecutorService scheduler; + private final Runnable timerRunner = () -> onTick(); + + private final String nodeName; + + public NotificationDelayFilter(String nodeName, NotificationDelayedListener<T> timeoutListener) { + this.nodeName = nodeName; + this.timeoutListener = timeoutListener; + this.problemItems = new ConcurrentHashMap <>(); + this.scheduler = Executors.newScheduledThreadPool(1); + this.startTimer(); + } + + /** + * If process the notification + * @return true if other processing is required, false if not + */ + public boolean processNotification(boolean cleared, String problemName, T notificationXml) { + // ToggleAlarmFilter functionality + if (NotificationDelayFilter.isEnabled()) { + if (cleared) { + clearAlarmNotification(problemName, notificationXml); + } else { + pushAlarmNotification(problemName, notificationXml); + } + return false; + } else { + return true; + } + // end of ToggleAlarmFilter + } + + /** + * Push notification with a specific severity (everything except non-alarmed) + * @param problemName key + * @param notification related notification + */ + public void pushAlarmNotification(String problemName, T notification) { + synchronized (problemItems) { + + boolean cp = this.problemItems.containsKey(problemName); + if (!cp) { + // no alarm in entries => create entry and push the alarm currently + NotificationWithServerTimeStamp<T> item = new NotificationWithServerTimeStamp<>( + notification); + LOG.debug("add event into list for node " + this.nodeName + " for alarm " + problemName + ": " + + item.toString()); + this.problemItems.put(problemName, item); + if (this.timeoutListener != null) { + this.timeoutListener.onNotificationDelay(notification); + } + } else { + LOG.debug("clear contra event for node " + this.nodeName + " for alarm " + problemName); + this.problemItems.get(problemName).clrContraEvent(); + } + + } + } + + /** + * Push notification with severity non-alarmed + * @param problemName key + * @param notification related notification + */ + public void clearAlarmNotification(String problemName, T notification) { + synchronized (problemItems) { + + boolean cp = this.problemItems.containsKey(problemName); + if (cp) { + LOG.debug("set contra event for alarm " + problemName); + this.problemItems.get(problemName).setContraEvent(notification); + } else { + // not in list => push directly through + if (this.timeoutListener != null) { + this.timeoutListener.onNotificationDelay(notification); + } + } + } + } + + private void startTimer() { + scheduler.scheduleAtFixedRate(timerRunner, 0, 1, TimeUnit.SECONDS); + } + + private void stopTimer() { + scheduler.shutdown(); + } + + /** + * check for clearing item out of the list + */ + private void onTick() { + long now = System.currentTimeMillis(); + try { + + synchronized (problemItems) { + + for (Entry<String, NotificationWithServerTimeStamp<T>> entry : problemItems + .entrySet()) { + NotificationWithServerTimeStamp<T> value = entry.getValue(); + if (value.isStable(now)) { + // send contra Alarm if exists + if (value.getContraAlarmNotification() != null) { + if (this.timeoutListener != null) { + this.timeoutListener.onNotificationDelay(value.getContraAlarmNotification()); + } + } + problemItems.remove(entry.getKey()); + LOG.debug("removing entry for "+this.nodeName+" for alarm " + entry.getKey()); + } else { + LOG.trace("currently state is still unstable for alarm " + entry.getKey()); + } + } + + } + } catch (Exception e) { + //Prevent stopping the task + LOG.warn("Exception during NotificationDelayFilter Task", e); + } + } + + @Override + public void close() throws Exception { + this.stopTimer(); + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayService.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayService.java new file mode 100644 index 000000000..a9a04595a --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayService.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter; + +import java.util.HashMap; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.DeviceManagerService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.conf.ToggleAlarmConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NotificationDelayService<T> implements DeviceManagerService, AutoCloseable, IConfigChangedListener { + private static final Logger LOG = LoggerFactory.getLogger(NotificationDelayService.class); + + private final HashMap<String, NotificationDelayFilter<T>> filters; + private final ToggleAlarmConfig config; + + public NotificationDelayService(ConfigurationFileRepresentation htconfig) { + this.filters = new HashMap<>(); + htconfig.registerConfigChangedListener(this); + config = new ToggleAlarmConfig(htconfig); + onConfigChanged(); + } + + public NotificationDelayFilter<T> getInstance(String nodeName, NotificationDelayedListener<T> eventListener) { + NotificationDelayFilter<T> filter = filters.getOrDefault(nodeName, null); + + LOG.trace("nodeName={}, filter!=null? {}", nodeName, filter != null); + if (filter == null) { + filter = new NotificationDelayFilter<>(nodeName, eventListener); + this.filters.put(nodeName, filter); + } + return filter; + } + + @Override + public void onConfigChanged() { + NotificationDelayFilter.setDelay(config.getDelay()); + NotificationDelayFilter.setEnabled(config.isEnabled()); + } + + @Override + public void close() throws Exception { + // close all filters + for (NotificationDelayFilter<T> filter : this.filters.values()) { + filter.close(); + } + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayedListener.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayedListener.java new file mode 100644 index 000000000..eab541d13 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationDelayedListener.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter; + +public interface NotificationDelayedListener<T> { + + public void onNotificationDelay(T notification); + +} + diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationWithServerTimeStamp.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationWithServerTimeStamp.java new file mode 100644 index 000000000..1cf32cffc --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/NotificationWithServerTimeStamp.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter; + +public class NotificationWithServerTimeStamp<T2> { + private final T2 alarmNotification; + private T2 contraAlarmNotification; + private final long timestampStart; + private long timestamp; + + public NotificationWithServerTimeStamp(T2 n) { + this(n, System.currentTimeMillis()); + } + + public NotificationWithServerTimeStamp(T2 n, long ts) { + this.alarmNotification = n; + this.contraAlarmNotification = null; + this.timestamp = ts; + this.timestampStart=ts; + } + + @SuppressWarnings("unused") + public long getStartTime() { + return this.timestampStart; + } + public void refresh() { + this.refresh(System.currentTimeMillis()); + } + + public void refresh(long ts) { + this.timestamp = ts; + } + + public void setContraEvent(T2 notification) { + this.contraAlarmNotification = notification; + this.refresh(); + } + + public void clrContraEvent() { + this.contraAlarmNotification = null; + this.refresh(); + } + + public boolean isStable(long now) { + return this.timestamp + NotificationDelayFilter.getDelay() < now; + } + + @SuppressWarnings("unused") + public T2 getAlarmNotification() { + return this.alarmNotification; + } + + public T2 getContraAlarmNotification() { + return this.contraAlarmNotification; + } + + @Override + public String toString() { + return "NotificationWithServerTimeStamp [alarmNotification=" + alarmNotification + + ", contraAlarmNotification=" + contraAlarmNotification + ", timestampStart=" + timestampStart + + ", timestamp=" + timestamp + "]"; + } +} diff --git a/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/conf/ToggleAlarmConfig.java b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/conf/ToggleAlarmConfig.java new file mode 100644 index 000000000..e7c6c7a2d --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/toggleAlarmFilter/conf/ToggleAlarmConfig.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.conf; + +import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; + +public class ToggleAlarmConfig implements Configuration { + + private static final String SECTION_MARKER_TA = "toggleAlarmFilter"; + + private static final String PROPERTY_KEY_ENABLED = "taEnabled"; + private static final String PROPERTY_KEY_DELAY = "taDelay"; + + private static final boolean DEFAULT_VALUE_ENABLED = true; + private static final long DEFAULT_VALUE_DELAY = 3000; //in ms + + private final ConfigurationFileRepresentation configuration; + + public ToggleAlarmConfig(ConfigurationFileRepresentation configuration) { + this.configuration = configuration; + this.configuration.addSection(SECTION_MARKER_TA); + defaults(); + } + + public boolean isEnabled() { + return configuration.getPropertyBoolean(SECTION_MARKER_TA, PROPERTY_KEY_ENABLED); + } + public long getDelay() { + return configuration.getPropertyLong(SECTION_MARKER_TA, PROPERTY_KEY_DELAY).orElse(DEFAULT_VALUE_DELAY); + } + + @Override + public String getSectionName() { + return SECTION_MARKER_TA; + } + + @Override + public void defaults() { + //Add default if not available + configuration.setPropertyIfNotAvailable(SECTION_MARKER_TA, PROPERTY_KEY_ENABLED, DEFAULT_VALUE_ENABLED); + configuration.setPropertyIfNotAvailable(SECTION_MARKER_TA, PROPERTY_KEY_DELAY, DEFAULT_VALUE_DELAY); + } +} |