diff options
Diffstat (limited to 'vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src')
9 files changed, 863 insertions, 0 deletions
diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/CrudService.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/CrudService.java new file mode 100644 index 00000000..9c6ef56e --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/CrudService.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health; + +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.List; +import javax.annotation.Nonnull; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * Example of an aggregated access interface. + * <p/> + * Shared by all the customizers hiding the ugly details of our data management. + * + * TODO update javadoc + */ +public interface CrudService<T extends DataObject> { + + /** + * Perform write of provided data. + */ + void writeData(@Nonnull final InstanceIdentifier<T> identifier, @Nonnull final T data) + throws WriteFailedException; + + + /** + * Perform delete of existing data. + */ + void deleteData(@Nonnull final InstanceIdentifier<T> identifier, @Nonnull final T data) + throws WriteFailedException; + + /** + * Perform update of existing data. + */ + void updateData(@Nonnull final InstanceIdentifier<T> identifier, @Nonnull final T dataOld, + @Nonnull final T dataNew) + throws WriteFailedException; + + /** + * Read data identified by provided identifier. + */ + T readSpecific(@Nonnull final InstanceIdentifier<T> identifier) throws ReadFailedException; + + /** + * Read all nodes of type {@link T}. + */ + List<T> readAll() throws ReadFailedException; +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ElementCrudService.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ElementCrudService.java new file mode 100644 index 00000000..4854b0b9 --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ElementCrudService.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + + /* + * Modifications copyright (c) 2018 AT&T Intellectual Property + */ + +package org.onap.vnf.health; + +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheckBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.HealthVnfOnapPluginState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Simple example of class handling Crud operations for plugin. + * <p/> + * No real handling, serves just as an illustration. + * + * TODO update javadoc + */ +final class ElementCrudService implements CrudService<HealthCheck> { + + private static final Logger LOG = LoggerFactory.getLogger(ElementCrudService.class); + + @Override + public void writeData(@Nonnull final InstanceIdentifier<HealthCheck> identifier, @Nonnull final HealthCheck data) + throws WriteFailedException { + if (data != null) { + + // identifier.firstKeyOf(SomeClassUpperInHierarchy.class) can be used to identify + // relationships such as to which parent these data are related to + + // Performs any logic needed for persisting such data + LOG.info("Writing path[{}] / data [{}]", identifier, data); + } else { + throw new WriteFailedException.CreateFailedException(identifier, data, + new NullPointerException("Provided data are null")); + } + } + + @Override + public void deleteData(@Nonnull final InstanceIdentifier<HealthCheck> identifier, @Nonnull final HealthCheck data) + throws WriteFailedException { + if (data != null) { + + // identifier.firstKeyOf(SomeClassUpperInHierarchy.class) can be used to identify + // relationships such as to which parent these data are related to + + // Performs any logic needed for persisting such data + LOG.info("Removing path[{}] / data [{}]", identifier, data); + } else { + throw new WriteFailedException.DeleteFailedException(identifier, + new NullPointerException("Provided data are null")); + } + } + + @Override + public void updateData(@Nonnull final InstanceIdentifier<HealthCheck> identifier, @Nonnull final HealthCheck dataOld, + @Nonnull final HealthCheck dataNew) throws WriteFailedException { + if (dataOld != null && dataNew != null) { + + // identifier.firstKeyOf(SomeClassUpperInHierarchy.class) can be used to identify + // relationships such as to which parent these data are related to + + // Performs any logic needed for persisting such data + LOG.info("Update path[{}] from [{}] to [{}]", identifier, dataOld, dataNew); + } else { + throw new WriteFailedException.DeleteFailedException(identifier, + new NullPointerException("Provided data are null")); + } + } + + @Override + public HealthCheck readSpecific(@Nonnull final InstanceIdentifier<HealthCheck> identifier) throws ReadFailedException { + + // Returns sample data + return new HealthCheckBuilder() + .setVnfName("scope represented") + .setState("sample status") + .setTime("01-01-1000:0000") + .build(); + } + + @Override + public List<HealthCheck> readAll() throws ReadFailedException { + // read all data under parent node,in this case {@link ModuleState} + return Collections.singletonList( + readSpecific(InstanceIdentifier.create(HealthVnfOnapPluginState.class).child(HealthCheck.class))); + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/Module.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/Module.java new file mode 100644 index 00000000..5c26f7f9 --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/Module.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health; + +import static org.onap.vnf.health.ModuleConfiguration.ELEMENT_SERVICE_NAME; + +import org.onap.vnf.health.read.ModuleStateReaderFactory; + +import com.google.inject.AbstractModule; +import com.google.inject.TypeLiteral; +import com.google.inject.multibindings.Multibinder; +import com.google.inject.name.Names; + +import org.onap.vnf.health.write.ModuleWriterFactory; +import io.fd.honeycomb.translate.read.ReaderFactory; +import io.fd.honeycomb.translate.write.WriterFactory; +import net.jmob.guice.conf.core.ConfigurationModule; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; + +/** + * Module class instantiating health-vnf-onap-plugin plugin components. + */ +public final class Module extends AbstractModule { + + // TODO This initiates all the plugin components, but it still needs to be registered/wired into an integration + // module producing runnable distributions. There is one such distribution in honeycomb project: + // vpp-integration/minimal-distribution + // In order to integrate this plugin with the distribution: + // 1. Add a dependency on this maven module to the the distribution's pom.xml + // 2. Add an instance of this module into the distribution in its Main class + + @Override + protected void configure() { + // requests injection of properties + install(ConfigurationModule.create()); + requestInjection(ModuleConfiguration.class); + + // creates binding for interface implementation by name + bind(new TypeLiteral<CrudService<HealthCheck>>(){}) + .annotatedWith(Names.named(ELEMENT_SERVICE_NAME)) + .to(ElementCrudService.class); + + // can hold multiple binding for separate yang modules + final Multibinder<ReaderFactory> readerFactoryBinder = Multibinder.newSetBinder(binder(), ReaderFactory.class); + readerFactoryBinder.addBinding().to(ModuleStateReaderFactory.class); + + // create writer factory binding + // can hold multiple binding for separate yang modules + final Multibinder<WriterFactory> writerFactoryBinder = Multibinder.newSetBinder(binder(), WriterFactory.class); + writerFactoryBinder.addBinding().to(ModuleWriterFactory.class); + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ModuleConfiguration.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ModuleConfiguration.java new file mode 100644 index 00000000..70f097a9 --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/ModuleConfiguration.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health; + +import net.jmob.guice.conf.core.BindConfig; +import net.jmob.guice.conf.core.InjectConfig; +import net.jmob.guice.conf.core.Syntax; + +/** + * Class containing static configuration for health-vnf-onap-plugin module,<br> + * either loaded from property file health-vnf-onap-plugin.json from classpath. + * <p/> + * Further documentation for the configuration injection can be found at: + * https://github.com/yyvess/gconf + */ +@BindConfig(value = "health-vnf-onap-plugin", syntax = Syntax.JSON) +public final class ModuleConfiguration { + + // TODO change the sample property to real plugin configuration + // If there is no such configuration, remove this, health-vnf-onap-plugin.json resource and its wiring from Module class + + /** + * Sample property that's injected from external json configuration file. + */ + @InjectConfig("sample-prop") + public String sampleProp; + + /** + * Constant name used to identify health-vnf-onap-plugin plugin specific components during dependency injection. + */ + public static final String ELEMENT_SERVICE_NAME = "element-service"; +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/RESTManager.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/RESTManager.java new file mode 100644 index 00000000..abe7244e --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/RESTManager.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vnf.health; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RESTManager { + + private static final Logger logger = LoggerFactory.getLogger(RESTManager.class); + + public class Pair<A, B> { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + public Pair<Integer, String> post(String url, String username, String password, + Map<String, String> headers, String contentType, String body) { + CredentialsProvider credentials = new BasicCredentialsProvider(); + credentials.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(username, password)); + + logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username, + ((password != null) ? password.length() : "-"), contentType); + if (headers != null) { + logger.debug("Headers: "); + headers.forEach((name, value) -> logger.debug("{} -> {}", name, value)); + } + logger.debug(body); + + try (CloseableHttpClient client = + HttpClientBuilder + .create() + .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .setDefaultCredentialsProvider(credentials) + .build()) { + + HttpPost post = new HttpPost(url); + if (headers != null) { + for (Entry<String, String> entry : headers.entrySet()) { + post.addHeader(entry.getKey(), headers.get(entry.getKey())); + } + } + post.addHeader("Content-Type", contentType); + + StringEntity input = new StringEntity(body); + input.setContentType(contentType); + post.setEntity(input); + + HttpResponse response = client.execute(post); + if (response != null) { + String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + logger.debug("HTTP POST Response Status Code: {}", + response.getStatusLine().getStatusCode()); + logger.debug("HTTP POST Response Body:"); + logger.debug(returnBody); + + return new Pair<>(response.getStatusLine().getStatusCode(), + returnBody); + } + else { + logger.error("Response from {} is null", url); + return null; + } + } + catch (Exception e) { + logger.error("Failed to POST to {}", url, e); + return null; + } + } + + public Pair<Integer, String> get(String url, String username, String password, + Map<String, String> headers) { + + CredentialsProvider credentials = new BasicCredentialsProvider(); + credentials.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(username, password)); + + try (CloseableHttpClient client = + HttpClientBuilder + .create() + .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .setDefaultCredentialsProvider(credentials) + .build()) { + + HttpGet get = new HttpGet(url); + if (headers != null) { + for (Entry<String, String> entry : headers.entrySet()) { + get.addHeader(entry.getKey(), headers.get(entry.getKey())); + } + } + + HttpResponse response = client.execute(get); + + String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + + logger.debug("HTTP GET Response Status Code: {}", + response.getStatusLine().getStatusCode()); + logger.debug("HTTP GET Response Body:"); + logger.debug(returnBody); + + return new Pair<>(response.getStatusLine().getStatusCode(), returnBody); + } + catch (IOException e) { + logger.error("Failed to GET to {}", url, e); + return null; + } + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ElementStateCustomizer.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ElementStateCustomizer.java new file mode 100644 index 00000000..5486928d --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ElementStateCustomizer.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + + /* + * Modifications copyright (c) 2018 AT&T Intellectual Property + */ + +package org.onap.vnf.health.read; + +import org.onap.vnf.health.CrudService; +import org.onap.vnf.health.RESTManager; +import org.onap.vnf.health.RESTManager.Pair; + +import io.fd.honeycomb.translate.read.ReadContext; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.spi.read.Initialized; +import io.fd.honeycomb.translate.spi.read.InitializingReaderCustomizer; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.annotation.Nonnull; + +import org.onap.vnf.health.CrudService; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.HealthVnfOnapPluginStateBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheckBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.health.check.FaultsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.health.check.faults.Fault; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.health.check.faults.FaultBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.health.check.faults.FaultKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Reader for {@link Element} list node from our YANG model. + */ +public final class ElementStateCustomizer implements InitializingReaderCustomizer<HealthCheck, HealthCheckBuilder> { + + private final CrudService<HealthCheck> crudService; + private static final Logger LOG = LoggerFactory.getLogger(ElementStateCustomizer.class); + private final String SCRIPT; + private final String OUTPUT; + private final String VNFC; + private final Boolean PRIMARY; + private static SimpleDateFormat SDF; + + public ElementStateCustomizer(final CrudService<HealthCheck> crudService) throws IOException { + this.crudService = crudService; + + // initialize data format + SDF = new SimpleDateFormat("MM-dd-yyyy:HH.mm.ss"); + + // read properties from file + String path = "/opt/config/properties.conf"; + Properties prop = new Properties(); + InputStream prop_file = new FileInputStream(path); + prop.load(prop_file); + SCRIPT = prop.getProperty("script"); + OUTPUT = prop.getProperty("output"); + VNFC = prop.getProperty("vnfc"); + PRIMARY = Boolean.parseBoolean(prop.getProperty("primary")); + prop_file.close(); + } + + @Override + public void merge(@Nonnull final Builder<? extends DataObject> builder, @Nonnull final HealthCheck readData) { + // merge children data to parent builder + // used by infrastructure to merge data loaded in separated customizers + ((HealthVnfOnapPluginStateBuilder) builder).setHealthCheck(readData); + } + + @Nonnull + @Override + public HealthCheckBuilder getBuilder(@Nonnull final InstanceIdentifier<HealthCheck> id) { + // return new builder for this data node + return new HealthCheckBuilder(); + } + + @Override + public void readCurrentAttributes(@Nonnull final InstanceIdentifier<HealthCheck> id, + @Nonnull final HealthCheckBuilder builder, + @Nonnull final ReadContext ctx) throws ReadFailedException { + + List<String> ipAddr = new ArrayList<String>(); + if(PRIMARY) { + String ret = readFromFile("/opt/config/oam_vpktgen_ip.txt"); + if(ret != null) { + ipAddr.add(ret); + } + ret = readFromFile("/opt/config/oam_vdns_ip.txt"); + if(ret != null) { + ipAddr.add(ret); + } + } + + // assess the health status of the local service (try at most three times, otherwise return an error). + String healthStatus; + String [] cmdArgs = {"/bin/bash", "-c", SCRIPT}; + int ret = -1; + int attempts = 0; + + do { + try { + Process child = Runtime.getRuntime().exec(cmdArgs); + // wait for child process to terminate + ret = child.waitFor(); + attempts++; + } + catch (IOException e) { + LOG.error("Command: [" + SCRIPT + "] returned an error."); + e.printStackTrace(); + } + catch (InterruptedException e) { + LOG.error("Child process: [" + SCRIPT + "] returned an error. Error code: " + ret); + e.printStackTrace(); + } + } while(ret != 0 && attempts < 3); + + if(ret == 0) { + healthStatus = readFromFile(OUTPUT); + if(healthStatus == null) { + healthStatus = "unhealthy"; + } + LOG.info("Assessing the health status of the local component... Return status = \"" + healthStatus + "\""); + } + else { + healthStatus = "unhealthy"; + LOG.info("Failed to assess the health status of the local component. Return status = \"unhealthy\""); + } + + // perform read of details of data specified by key of Element in id + // final HealthCheck data = crudService.readSpecific(id); + + // check the status of other VNF components, if any + if(PRIMARY) { + for(int i = 0; i < ipAddr.size(); i++) { + if(!getRemoteVnfcHealthStatus(ipAddr.get(i))) { + healthStatus = "unhealthy"; + } + } + } + + // and sets it to builder + builder.setState(healthStatus); + builder.setVnfName(VNFC); + builder.setTime(SDF.format(new Date().getTime())); + + if(healthStatus.equals("unhealthy")) { + List<Fault> faultList = new ArrayList<Fault>(); + // build a FaultBuilder object in case of one or more VNF components are reporting faults + FaultBuilder faultBuilder = new FaultBuilder(); + faultBuilder.setVnfComponent(VNFC); + faultBuilder.setMessage("The VNF is not running correctly"); + faultBuilder.setKey(new FaultKey(faultBuilder.getVnfComponent())); + faultList.add(faultBuilder.build()); + + // build a FaultsBuilder object that contains a list of Fault instances + FaultsBuilder faultsBuilder = new FaultsBuilder(); + faultsBuilder.setInfo("One or more VNF components are unreachable"); + faultsBuilder.setFault(faultList); + + // add the Faults object to HealthCheckBuilder + builder.setFaults(faultsBuilder.build()); + } + + // create the final HealthCheck object + builder.build(); + } + /** + * + * Initialize configuration data based on operational data. + * <p/> + * Very useful when a plugin is initiated but the underlying layer already contains some operation state. + * Deriving the configuration from existing operational state enables reconciliation in case when + * Honeycomb's persistence is not available to do the work for us. + */ + @Nonnull + @Override + public Initialized<? extends DataObject> init(@Nonnull final InstanceIdentifier<HealthCheck> id, + @Nonnull final HealthCheck readValue, + @Nonnull final ReadContext ctx) { + return Initialized.create(id, readValue); + } + + private String readFromFile(String path) { + // auto close the file reader + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + String line; + while ((line = br.readLine()) != null) { + return line; + } + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + private boolean getRemoteVnfcHealthStatus(String ipAddr) { + // set up the REST manager + RESTManager mgr = new RESTManager(); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("Content-Type", "application/json"); + headers.put("Accept", "application/json"); + + // execute the request + String URI = "http://" + ipAddr + ":8183/restconf/operational/health-vnf-onap-plugin:health-vnf-onap-plugin-state/health-check"; + Pair<Integer, String> result = mgr.get(URI, "admin", "admin", headers); + + return (!result.b.contains("unhealthy")); + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ModuleStateReaderFactory.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ModuleStateReaderFactory.java new file mode 100644 index 00000000..a88a6901 --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/read/ModuleStateReaderFactory.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health.read; + +import static org.onap.vnf.health.ModuleConfiguration.ELEMENT_SERVICE_NAME; + +import java.io.IOException; + +import com.google.inject.Inject; +import com.google.inject.name.Named; +import org.onap.vnf.health.CrudService; +import io.fd.honeycomb.translate.impl.read.GenericReader; +import io.fd.honeycomb.translate.read.ReaderFactory; +import io.fd.honeycomb.translate.read.registry.ModifiableReaderRegistryBuilder; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.HealthVnfOnapPluginState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.HealthVnfOnapPluginStateBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * Factory producing readers for health-vnf-onap-plugin plugin's data. + */ +public final class ModuleStateReaderFactory implements ReaderFactory { + + public static final InstanceIdentifier<HealthVnfOnapPluginState> ROOT_STATE_CONTAINER_ID = + InstanceIdentifier.create(HealthVnfOnapPluginState.class); + + /** + * Injected crud service to be passed to customizers instantiated in this factory. + */ + @Inject + @Named(ELEMENT_SERVICE_NAME) + private CrudService<HealthCheck> crudService; + + @Override + public void init(@Nonnull final ModifiableReaderRegistryBuilder registry) { + + // register reader that only delegate read's to its children + registry.addStructuralReader(ROOT_STATE_CONTAINER_ID, HealthVnfOnapPluginStateBuilder.class); + + // just adds reader to the structure + // use addAfter/addBefore if you want to add specific order to readers on the same level of tree + // use subtreeAdd if you want to handle multiple nodes in single customizer/subtreeAddAfter/subtreeAddBefore if you also want to add order + // be aware that instance identifier passes to subtreeAdd/subtreeAddAfter/subtreeAddBefore should define subtree, + // therefore it should be relative from handled node down - InstanceIdentifier.create(HandledNode), not parent.child(HandledNode.class) + try { + registry.add( + new GenericReader<>(ROOT_STATE_CONTAINER_ID.child(HealthCheck.class), + new ElementStateCustomizer(crudService))); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ElementCustomizer.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ElementCustomizer.java new file mode 100644 index 00000000..ec41a9a2 --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ElementCustomizer.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health.write; + +import org.onap.vnf.health.CrudService; +import io.fd.honeycomb.translate.spi.write.WriterCustomizer; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * Writer for {@link Element} list node from our YANG model. + */ +//public final class ElementCustomizer implements ListWriterCustomizer<HealthCheck, HealthCheckKey> { +public final class ElementCustomizer implements WriterCustomizer<HealthCheck> { + + private final CrudService<HealthCheck> crudService; + + public ElementCustomizer(@Nonnull final CrudService<HealthCheck> crudService) { + this.crudService = crudService; + } + + @Override + public void writeCurrentAttributes(@Nonnull final InstanceIdentifier<HealthCheck> id, @Nonnull final HealthCheck dataAfter, + @Nonnull final WriteContext writeContext) throws WriteFailedException { + //perform write of data,or throw exception + //invoked by PUT operation,if provided data doesn't exist in Config data + crudService.writeData(id, dataAfter); + } + + @Override + public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<HealthCheck> id, + @Nonnull final HealthCheck dataBefore, + @Nonnull final HealthCheck dataAfter, @Nonnull final WriteContext writeContext) + throws WriteFailedException { + //perform update of data,or throw exception + //invoked by PUT operation,if provided data does exist in Config data + crudService.updateData(id, dataBefore, dataAfter); + } + + @Override + public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<HealthCheck> id, + @Nonnull final HealthCheck dataBefore, + @Nonnull final WriteContext writeContext) throws WriteFailedException { + //perform delete of data,or throw exception + //invoked by DELETE operation + crudService.deleteData(id, dataBefore); + } +} diff --git a/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ModuleWriterFactory.java b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ModuleWriterFactory.java new file mode 100644 index 00000000..8dfd1cbb --- /dev/null +++ b/vnfs/vLBMS/apis/health-vnf-onap-plugin/health-vnf-onap-plugin-impl/src/main/java/org/onap/vnf/health/write/ModuleWriterFactory.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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. + */ + +package org.onap.vnf.health.write; + +import static org.onap.vnf.health.ModuleConfiguration.ELEMENT_SERVICE_NAME; + +import com.google.inject.Inject; +import com.google.inject.name.Named; +import org.onap.vnf.health.CrudService; +import io.fd.honeycomb.translate.impl.write.GenericWriter; +import io.fd.honeycomb.translate.write.WriterFactory; +import io.fd.honeycomb.translate.write.registry.ModifiableWriterRegistryBuilder; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.HealthVnfOnapPlugin; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.health.vnf.onap.plugin.rev160918.health.vnf.onap.plugin.params.HealthCheck; + +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * Factory producing writers for health-vnf-onap-plugin plugin's data. + */ +public final class ModuleWriterFactory implements WriterFactory { + + private static final InstanceIdentifier<HealthVnfOnapPlugin> ROOT_CONTAINER_ID = InstanceIdentifier.create(HealthVnfOnapPlugin.class); + + /** + * Injected crud service to be passed to customizers instantiated in this factory. + */ + @Inject + @Named(ELEMENT_SERVICE_NAME) + private CrudService<HealthCheck> crudService; + + @Override + public void init(@Nonnull final ModifiableWriterRegistryBuilder registry) { + + //adds writer for child node + //no need to add writers for empty nodes + registry.add(new GenericWriter<>(ROOT_CONTAINER_ID.child(HealthCheck.class), new ElementCustomizer(crudService))); + } +} |