diff options
author | liamfallon <liam.fallon@est.tech> | 2021-05-26 11:02:07 +0100 |
---|---|---|
committer | liamfallon <liam.fallon@est.tech> | 2021-05-26 11:02:11 +0100 |
commit | 20c7487f77d0728d270b2bed34c2c798d17cc12d (patch) | |
tree | bb20d003255fab584ac64968967fbc6e1f205232 /participant/participant-impl/participant-impl-dcae/src/main/java | |
parent | f83411a86e2277adae69e780e8511913d61a0f17 (diff) |
Transfer tosca-poc onto master
This is the third if three commits, this commit makes the content of
the master branch the same as the tosca-poc branch.
This commit adds the "src" files for TOSCA control loops to the modules
in master.
Difference between this commit and the current master:
------------------------------------------------------
diff -qr clamp clamp-master |diff_filter.sh
Only in clamp/common: src
Only in clamp/models: src
Files clamp/participant/participant-impl/participant-impl-dcae/pom.xml and clamp-master/participant/participant-impl/participant-impl-dcae/pom.xml differ
Only in clamp/participant/participant-impl/participant-impl-dcae: src
Only in clamp/participant/participant-impl/participant-impl-policy: src
Only in clamp/participant/participant-impl/participant-impl-simulator: src
Files clamp/participant/participant-impl/pom.xml and clamp-master/participant/participant-impl/pom.xml differ
Only in clamp/participant/participant-intermediary: src
Files clamp/participant/pom.xml and clamp-master/participant/pom.xml differ
Files clamp/pom.xml and clamp-master/pom.xml differ
Files clamp/runtime/pom.xml and clamp-master/runtime/pom.xml differ
Only in clamp: runtime-controlloop
Difference between this commit and the current tosca-poc branch:
----------------------------------------------------------------
diff -qr clamp clamp-tp |diff_filter.sh
Files clamp/INFO.yaml and clamp-tp/INFO.yaml differ
Only in clamp/releases: 6.0.1-container.yaml
Only in clamp/releases: 6.0.1.yaml
Only in clamp/releases: 6.0.2-container.yaml
Only in clamp/releases: 6.0.2.yaml
Only in clamp/releases: 6.1.0-container.yaml
Only in clamp/releases: 6.1.0.yaml
Only in clamp/releases: 6.1.1-container.yaml
Only in clamp/releases: 6.1.1.yaml
Files clamp/runtime/src/main/resources/META-INF/resources/swagger.html and clamp-tp/runtime/src/main/resources/META-INF/resources/swagger.html differ
Issue-ID: POLICY-3215
Change-Id: Ica1aa3fe5d6110df2396ea856703102e800fa770
Signed-off-by: liamfallon <liam.fallon@est.tech>
Diffstat (limited to 'participant/participant-impl/participant-impl-dcae/src/main/java')
14 files changed, 1388 insertions, 0 deletions
diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/AbstractHttpClient.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/AbstractHttpClient.java new file mode 100644 index 000000000..b2d0b61d0 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/AbstractHttpClient.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.httpclient; + +import java.io.Closeable; +import java.io.IOException; +import javax.ws.rs.core.Response.Status; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.ParseException; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +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.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.util.EntityUtils; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.clamp.controlloop.participant.dcae.model.Loop; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractHttpClient implements Closeable { + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHttpClient.class); + private final HttpClientContext localContext; + private final CloseableHttpClient httpclient; + private final HttpHost target; + public static final Coder CODER = new StandardCoder(); + + /** + * Constructor. + */ + protected AbstractHttpClient(RestServerParameters restServerParameters) { + try { + final String scheme = restServerParameters.isHttps() ? "https" : "http"; + target = new HttpHost(restServerParameters.getHost(), restServerParameters.getPort(), scheme); + + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), + new UsernamePasswordCredentials(restServerParameters.getUserName(), + restServerParameters.getPassword())); + + AuthCache authCache = new BasicAuthCache(); + BasicScheme basicAuth = new BasicScheme(); + authCache.put(target, basicAuth); + localContext = HttpClientContext.create(); + localContext.setAuthCache(authCache); + + HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); + if (restServerParameters.isHttps()) { + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(new SSLContextBuilder() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()).setProtocol("TLSv1.2").build(), + new NoopHostnameVerifier()); + builder.setSSLSocketFactory(sslsf); + } + httpclient = builder.build(); + + } catch (final Exception e) { + throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR, + restServerParameters.getName() + " Client failed to start", e); + } + } + + CloseableHttpResponse execute(HttpRequest request) throws IOException { + return httpclient.execute(target, request, localContext); + } + + protected boolean executePut(String path, int statusCode) { + try (CloseableHttpResponse response = execute(new HttpPut(path))) { + return response.getStatusLine().getStatusCode() == statusCode; + } catch (Exception e) { + return false; + } + } + + protected Loop executePost(String path, int statusCode) { + try (CloseableHttpResponse response = execute(new HttpPost(path))) { + if (response.getStatusLine().getStatusCode() != statusCode) { + return null; + } + return entityToMap(response.getEntity()); + } catch (Exception e) { + return null; + } + } + + protected Loop executeGet(String path, int statusCode) { + try (CloseableHttpResponse response = execute(new HttpGet(path))) { + if (response.getStatusLine().getStatusCode() != statusCode) { + return null; + } + return entityToMap(response.getEntity()); + } catch (Exception e) { + return null; + } + } + + private Loop entityToMap(HttpEntity httpEntity) { + if (httpEntity == null) { + return new Loop(); + } + try { + return CODER.convert(EntityUtils.toString(httpEntity), Loop.class); + } catch (ParseException | IOException e) { + LOGGER.error("error reading Entity", e); + return new Loop(); + } catch (CoderException e) { + LOGGER.error("cannot convert to Loop Object", e); + return new Loop(); + } + } + + @Override + public void close() throws IOException { + httpclient.close(); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClient.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClient.java new file mode 100644 index 000000000..eb805054d --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClient.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.httpclient; + +import org.apache.http.HttpStatus; +import org.onap.policy.clamp.controlloop.participant.dcae.model.ExternalComponent; +import org.onap.policy.clamp.controlloop.participant.dcae.model.Loop; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ClampHttpClient extends AbstractHttpClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClampHttpClient.class); + + private static final String STATUS = "/restservices/clds/v2/loop/getstatus/"; + private static final String CREATE = "/restservices/clds/v2/loop/create/%s?templateName=%s"; + private static final String UPDATE = "/restservices/clds/v2/loop/updateMicroservicePolicy/"; + private static final String DEPLOY = "/restservices/clds/v2/loop/deploy/"; + private static final String STOP = "/restservices/clds/v2/loop/stop/"; + private static final String DELETE = "/restservices/clds/v2/loop/delete/"; + private static final String UNDEPLOY = "/restservices/clds/v2/loop/undeploy/"; + public static final String STATUS_NOT_FOUND = "STATUS_NOT_FOUND"; + public static final String POLICY_NOT_FOUND = "POLICY_NOT_FOUND"; + + /** + * Constructor. + */ + public ClampHttpClient(RestServerParameters restServerParameters) { + super(restServerParameters); + } + + /** + * Create. + * + * @param loopName the loopName + * @param templateName the templateName + * @return the Loop object or null if error occurred + */ + public Loop create(String loopName, String templateName) { + return executePost(String.format(CREATE, loopName, templateName), HttpStatus.SC_OK); + } + + /** + * Update. + * + * @param loopName the loopName + * @param jsonEntity the Json entity + * @return true + */ + public boolean update(String loopName, String jsonEntity) { + return executePost(UPDATE + loopName, HttpStatus.SC_OK) != null; + } + + /** + * Deploy. + * + * @param loopName the loopName + * @return true + */ + public boolean deploy(String loopName) { // DCAE + return executePut(DEPLOY + loopName, HttpStatus.SC_ACCEPTED); + } + + /** + * Get Status. + * + * @param loopName the loopName + * @return the Loop object or null if error occurred + */ + public Loop getstatus(String loopName) { + return executeGet(STATUS + loopName, HttpStatus.SC_OK); + } + + /** + * Undeploy. + * + * @param loopName the loopName + * @return true + */ + public boolean undeploy(String loopName) { + return executePut(UNDEPLOY + loopName, HttpStatus.SC_ACCEPTED); + } + + /** + * Stop. + * + * @param loopName the loopName + * @return true + */ + public boolean stop(String loopName) { + return executePut(STOP + loopName, HttpStatus.SC_OK); + } + + /** + * Delete. + * + * @param loopName the loopName + * @return true + */ + public boolean delete(String loopName) { + return executePut(DELETE + loopName, HttpStatus.SC_OK); + } + + /** + * return status from Loop object. + * + * @param loop Loop + * @return status + */ + public static String getStatusCode(Loop loop) { + if (loop == null || loop.getComponents() == null || loop.getComponents().isEmpty()) { + return STATUS_NOT_FOUND; + } + ExternalComponent externalComponent = loop.getComponents().get("DCAE"); + if (externalComponent == null || externalComponent.getComponentState() == null) { + return STATUS_NOT_FOUND; + } + + return externalComponent.getComponentState().getStateName(); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ConsulDcaeHttpClient.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ConsulDcaeHttpClient.java new file mode 100644 index 000000000..cd84a2feb --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ConsulDcaeHttpClient.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.httpclient; + +import org.apache.http.HttpStatus; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; + +public class ConsulDcaeHttpClient extends AbstractHttpClient { + + private static final String DEPLOY = "/v1/kv/dcae-pmsh:policy"; + + /** + * constructor. + */ + public ConsulDcaeHttpClient(RestServerParameters restServerParameters) { + super(restServerParameters); + } + + /** + * call consult. + * + * @param jsonEntity the Entity + * @return true + */ + public boolean deploy(String jsonEntity) { + return executePut(DEPLOY + jsonEntity, HttpStatus.SC_ACCEPTED); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/ControlLoopElementHandler.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/ControlLoopElementHandler.java new file mode 100644 index 000000000..96677f320 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/ControlLoopElementHandler.java @@ -0,0 +1,197 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.handler; + +import java.io.Closeable; +import java.io.IOException; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState; +import org.onap.policy.clamp.controlloop.participant.dcae.httpclient.ClampHttpClient; +import org.onap.policy.clamp.controlloop.participant.dcae.httpclient.ConsulDcaeHttpClient; +import org.onap.policy.clamp.controlloop.participant.dcae.model.Loop; +import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class handles implementation of controlLoopElement updates. + */ +public class ControlLoopElementHandler implements ControlLoopElementListener, Closeable { + + private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopElementHandler.class); + private final ClampHttpClient clampClient; + private final ConsulDcaeHttpClient consulClient; + + private static final String LOOP = "pmsh_loop"; + private static final String TEMPLATE = "LOOP_TEMPLATE_k8s_pmsh"; + + private static final String BLUEPRINT_DEPLOYED = "BLUEPRINT_DEPLOYED"; + private static final String MICROSERVICE_INSTALLED_SUCCESSFULLY = "MICROSERVICE_INSTALLED_SUCCESSFULLY"; + private static final int CHECK_COUNT = 10; + + private static final String BODY_CONSUL = + "{ \"subscription\": { \"subscriptionName\": \"subscriptiona\", \"administrativeState\": \"UNLOCKED\", " + + "\"fileBasedGP\": 15, \"fileLocation\": \"/pm/pm.xml\", \"nfFilter\": " + + "{ \"nfNames\": [ \"^pnf1.*\" ], \"modelInvariantIDs\": " + + "[ \"5845y423-g654-6fju-po78-8n53154532k6\", \"7129e420-d396-4efb-af02-6b83499b12f8\" ], " + + "\"modelVersionIDs\": [ \"e80a6ae3-cafd-4d24-850d-e14c084a5ca9\" ] }, \"measurementGroups\": " + + "[ { \"measurementGroup\": { \"measurementTypes\": [ { \"measurementType\": \"countera\" }, " + + "{ \"measurementType\": \"counterb\" } ], \"managedObjectDNsBasic\": [ { \"DN\": \"dna\" }, " + + "{ \"DN\": \"dnb\" } ] } }, { \"measurementGroup\": { \"measurementTypes\": " + + "[ { \"measurementType\": \"counterc\" }, { \"measurementType\": \"counterd\" } ], " + + "\"managedObjectDNsBasic\": " + "[ { \"DN\": \"dnc\" }, { \"DN\": \"dnd\" } ] } } ] } }"; + + /** + * Constructor. + */ + public ControlLoopElementHandler(RestServerParameters clampParameters, RestServerParameters consulParameters) { + clampClient = new ClampHttpClient(clampParameters); + consulClient = new ConsulDcaeHttpClient(consulParameters); + } + + /** + * Callback method to handle a control loop element state change. + * + * @param controlLoopElementId the ID of the control loop element + * @param currentState the current state of the control loop element + * @param newState the state to which the control loop element is changing to + */ + @Override + public void controlLoopElementStateChange(UUID controlLoopElementId, ControlLoopState currentState, + ControlLoopOrderedState newState) { + switch (newState) { + case UNINITIALISED: + Loop loop = clampClient.getstatus(LOOP); + if (loop != null) { + clampClient.undeploy(LOOP); + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.UNINITIALISED); + } + break; + case PASSIVE: + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.PASSIVE); + break; + case RUNNING: + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.RUNNING); + break; + default: + LOGGER.debug("Unknown orderedstate {}", newState); + break; + } + } + + private Loop getStatus() throws PfModelException { + Loop loop = clampClient.getstatus(LOOP); + if (loop == null) { + loop = clampClient.create(LOOP, TEMPLATE); + } + if (loop == null) { + throw new PfModelException(null, ""); + } + return loop; + } + + private void deploy() throws PfModelException { + if (!consulClient.deploy(BODY_CONSUL)) { + throw new PfModelException(null, "deploy to consul failed"); + } + if (!clampClient.deploy(LOOP)) { + throw new PfModelException(null, "deploy failed"); + } + } + + /** + * Callback method to handle an update on a control loop element. + * + * @param element the information on the control loop element + * @param controlLoopDefinition toscaServiceTemplate + * @throws PfModelException in case of an exception + */ + @Override + public void controlLoopElementUpdate(ControlLoopElement element, ToscaServiceTemplate controlLoopDefinition) + throws PfModelException { + try { + Loop loop = getStatus(); + + if (BLUEPRINT_DEPLOYED.equals(ClampHttpClient.getStatusCode(loop))) { + deploy(); + boolean deployedFlag = false; + for (int i = 0; i < CHECK_COUNT; i++) { + //sleep 10 seconds + TimeUnit.SECONDS.sleep(CHECK_COUNT); + loop = getStatus(); + String status = ClampHttpClient.getStatusCode(loop); + if (MICROSERVICE_INSTALLED_SUCCESSFULLY.equals(status)) { + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementState(element.getId(), element.getOrderedState(), + ControlLoopState.PASSIVE); + deployedFlag = true; + break; + } + } + if (!deployedFlag) { + LOGGER.warn("DCAE is not deployed properly, ClElement state will be UNINITIALISED2PASSIVE"); + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementState(element.getId(), element.getOrderedState(), + ControlLoopState.UNINITIALISED2PASSIVE); + } + } + } catch (PfModelException e) { + throw e; + } catch (Exception e) { + throw new PfModelException(null, e.getMessage(), e); + } + } + + /** + * Handle controlLoopElement statistics. + * + * @param controlLoopElementId controlloop element id + */ + @Override + public void handleStatistics(UUID controlLoopElementId) { + ControlLoopElement clElement = DcaeHandler.getInstance().getDcaeProvider() + .getIntermediaryApi().getControlLoopElement(controlLoopElementId); + if (clElement != null) { + ClElementStatistics clElementStatistics = new ClElementStatistics(); + clElementStatistics.setControlLoopState(clElement.getState()); + clElementStatistics.setTimeStamp(Instant.now()); + DcaeHandler.getInstance().getDcaeProvider().getIntermediaryApi() + .updateControlLoopElementStatistics(controlLoopElementId, clElementStatistics); + } + } + + @Override + public void close() throws IOException { + clampClient.close(); + consulClient.close(); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeHandler.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeHandler.java new file mode 100644 index 000000000..1963e38b1 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeHandler.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.handler; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import javax.ws.rs.core.Response; +import lombok.Getter; +import org.onap.policy.clamp.controlloop.common.handler.ControlLoopHandler; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.base.PfModelRuntimeException; + +/** + * This class handles dcae of participants and control loop elements. + * + * </p> + * It is effectively a singleton that is started at system start. + */ +public class DcaeHandler extends ControlLoopHandler { + + private final ParticipantDcaeParameters parameters; + @Getter + private DcaeProvider dcaeProvider; + + /** + * Create a handler. + * + * @param parameters the parameters for access to the database + */ + public DcaeHandler(ParticipantDcaeParameters parameters) { + super(parameters.getDatabaseProviderParameters()); + this.parameters = parameters; + } + + public static DcaeHandler getInstance() { + return Registry.get(DcaeHandler.class.getName()); + } + + @Override + public Set<Class<?>> getProviderClasses() { + return Collections.emptySet(); + } + + @Override + public void startProviders() { + dcaeProvider = new DcaeProvider(parameters); + } + + @Override + public void stopProviders() { + try { + dcaeProvider.close(); + } catch (IOException e) { + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } finally { + dcaeProvider = null; + } + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeProvider.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeProvider.java new file mode 100644 index 000000000..afaf1c754 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/handler/DcaeProvider.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.handler; + +import java.io.Closeable; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import lombok.Getter; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; +import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi; +import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryFactory; + +/** + * This provider class dcae of participants and control loop elements. + */ +public class DcaeProvider implements Closeable { + @Getter + private final ParticipantIntermediaryApi intermediaryApi; + + private final ControlLoopElementHandler clElementHandler; + + /** + * Create a participant dcae provider. + * + * @throws ControlLoopRuntimeException on errors creating the provider + */ + public DcaeProvider(ParticipantDcaeParameters parameters) throws ControlLoopRuntimeException { + intermediaryApi = new ParticipantIntermediaryFactory().createApiImplementation(); + intermediaryApi.init(parameters.getIntermediaryParameters()); + clElementHandler = new ControlLoopElementHandler(parameters.getClampClientParameters(), + parameters.getConsulClientParameters()); + intermediaryApi.registerControlLoopElementListener(clElementHandler); + } + + @Override + public void close() throws IOException { + intermediaryApi.close(); + clElementHandler.close(); + } + + /** + * Get the control loops. + * + * @param name the controlLoop, null to get all + * @param version the controlLoop, null to get all + * @return the control loops + * @throws ControlLoopException on errors getting the control loops + */ + public ControlLoops getControlLoops(String name, String version) throws ControlLoopException { + return intermediaryApi.getControlLoops(name, version); + } + + /** + * Get the dcae control loop elements. + * + * @param name the controlLoopElement, null to get all + * @param version the controlLoopElement, null to get all + * @return the control loop elements + * @throws ControlLoopException on errors getting the control loop elements + */ + public Map<UUID, ControlLoopElement> getControlLoopElements(String name, String version) + throws ControlLoopException { + return intermediaryApi.getControlLoopElements(name, version); + } + + /** + * Update the given control loop element in the dcae. + * + * @param element the control loop element to update + * @return response simple response returned + * @throws ControlLoopException on errors updating the control loop element + */ + public TypedSimpleResponse<ControlLoopElement> updateControlLoopElement(ControlLoopElement element) + throws ControlLoopException { + TypedSimpleResponse<ControlLoopElement> response = new TypedSimpleResponse<>(); + response.setResponse(intermediaryApi.updateControlLoopElementState(element.getId(), + element.getOrderedState(), element.getState())); + return response; + } + + /** + * Get the current dcae participants. + * + * @param name the participant, null to get all + * @param version the participant, null to get all + * @return the list of participants + * @throws ControlLoopException on errors getting the participants + */ + public List<Participant> getParticipants(String name, String version) throws ControlLoopException { + return intermediaryApi.getParticipants(name, version); + } + + /** + * Update a dcae participant. + * + * @param participant the participant to update + * @return TypedSimpleResponse simple response + * @throws ControlLoopException on errors updating the participant + */ + + public TypedSimpleResponse<Participant> updateParticipant(Participant participant) throws ControlLoopException { + TypedSimpleResponse<Participant> response = new TypedSimpleResponse<>(); + response.setResponse( + intermediaryApi.updateParticipantState(participant.getDefinition(), participant.getParticipantState())); + return response; + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameterHandler.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameterHandler.java new file mode 100644 index 000000000..8d9bef98c --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameterHandler.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.parameters; + +import java.io.File; +import javax.ws.rs.core.Response; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.participant.dcae.main.startstop.ParticipantDcaeCommandLineArguments; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; + +/** + * This class handles reading, parsing and validating of control loop runtime parameters from JSON files. + */ +public class ParticipantDcaeParameterHandler { + + private static final Coder CODER = new StandardCoder(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to dcae + * @return the parameters read from the configuration file + * @throws ControlLoopException on parameter exceptions + */ + public ParticipantDcaeParameters getParameters(final ParticipantDcaeCommandLineArguments arguments) + throws ControlLoopException { + ParticipantDcaeParameters parameters = null; + + // Read the parameters + try { + // Read the parameters from JSON + File file = new File(arguments.getFullConfigurationFilePath()); + parameters = CODER.decode(file, ParticipantDcaeParameters.class); + } catch (final CoderException e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + ")"; + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (parameters == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, errorMessage); + } + + // validate the parameters + final ValidationResult validationResult = parameters.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, returnMessage); + } + + return parameters; + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameters.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameters.java new file mode 100644 index 000000000..beb273086 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/ParticipantDcaeParameters.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.parameters; + +import javax.validation.constraints.NotBlank; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; +import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantIntermediaryParameters; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.common.parameters.annotations.Valid; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; + +/** + * Class to hold all parameters needed for the participant dcae. + * + */ +@NotNull +@NotBlank +@Getter +public class ParticipantDcaeParameters extends ParameterGroupImpl { + @Valid + private RestServerParameters clampClientParameters; + + @Valid + private RestServerParameters consulClientParameters; + + private ParticipantIntermediaryParameters intermediaryParameters; + private PolicyModelsProviderParameters databaseProviderParameters; + + /** + * Create the participant dcae parameter group. + * + * @param name the parameter group name + */ + public ParticipantDcaeParameters(final String name) { + super(name); + } + + /** + * {@inheritDoc}. + */ + @Override + public BeanValidationResult validate() { + BeanValidationResult result = super.validate(); + if (result.isValid()) { + result.addResult(checkMissingMandatoryParams(clampClientParameters)); + result.addResult(checkMissingMandatoryParams(consulClientParameters)); + } + return result; + } + + private BeanValidationResult checkMissingMandatoryParams(RestServerParameters clientParameters) { + BeanValidationResult result = new BeanValidationResult(clientParameters.getName(), clientParameters); + if (StringUtils.isBlank(clientParameters.getHost())) { + result.addResult("Host", clientParameters.getHost(), ValidationStatus.INVALID, "is blank"); + } + if (StringUtils.isBlank(clientParameters.getName())) { + result.addResult("Name", clientParameters.getName(), ValidationStatus.INVALID, "is blank"); + } + if (StringUtils.isBlank(clientParameters.getPassword())) { + result.addResult("Password", clientParameters.getPassword(), ValidationStatus.INVALID, "is blank"); + } + if (StringUtils.isBlank(clientParameters.getUserName())) { + result.addResult("UserName", clientParameters.getUserName(), ValidationStatus.INVALID, "is blank"); + } + if (clientParameters.getPort() <= 0 || clientParameters.getPort() >= 65535) { + result.addResult("Port", clientParameters.getPort(), ValidationStatus.INVALID, "is not valid"); + } + return result; + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/Main.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/Main.java new file mode 100644 index 000000000..2b47a2c13 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/Main.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.startstop; + +import java.util.Arrays; +import javax.ws.rs.core.Response; +import lombok.Getter; +import org.onap.policy.clamp.controlloop.common.ControlLoopConstants; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameterHandler; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.common.utils.resources.MessageConstants; +import org.onap.policy.common.utils.services.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class initiates ONAP Policy Framework Control Loop participant component. + */ +public class Main { + + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + + private ParticipantDcaeActivator activator; + + @Getter + private ParticipantDcaeParameters parameterGroup; + + /** + * Instantiates the control loop participant service. + * + * @param args the command line arguments + */ + public Main(final String[] args) { + final String argumentString = Arrays.toString(args); + LOGGER.info("Starting the control loop participant service with arguments - {}", argumentString); + + // Check the arguments + final ParticipantDcaeCommandLineArguments arguments = new ParticipantDcaeCommandLineArguments(); + try { + // The arguments return a string if there is a message to print and we should exit + final String argumentMessage = arguments.parse(args); + if (argumentMessage != null) { + LOGGER.info(argumentMessage); + return; + } + // Validate that the arguments are sane + arguments.validate(); + + // Read the parameters + parameterGroup = new ParticipantDcaeParameterHandler().getParameters(arguments); + + // Now, create the activator for the service + activator = new ParticipantDcaeActivator(parameterGroup); + Registry.register(ControlLoopConstants.REG_CLRUNTIME_ACTIVATOR, activator); + + // Start the activator + activator.start(); + } catch (Exception exp) { + if (null != activator) { + Registry.unregister(ControlLoopConstants.REG_CLRUNTIME_ACTIVATOR); + } + throw new ControlLoopRuntimeException(Response.Status.BAD_REQUEST, + String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_CLAMP), exp); + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new ClRuntimeShutdownHookClass()); + String successMsg = String.format(MessageConstants.START_SUCCESS_MSG, MessageConstants.POLICY_CLAMP); + LOGGER.info(successMsg); + } + + /** + * Check if main is running. + */ + public boolean isRunning() { + return activator != null && activator.isAlive(); + } + + /** + * Shut down Execution. + * + * @throws ControlLoopException on shutdown errors + */ + public void shutdown() throws ControlLoopException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the cl participant activator + if (activator != null) { + activator.stop(); + } + } + + /** + * The Class ClRuntimeShutdownHookClass terminates the control loop participant service + * when its run method is called. + */ + private class ClRuntimeShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + if (!activator.isAlive()) { + return; + } + + try { + // Shutdown the control loop participant service and wait for everything to stop + activator.stop(); + } catch (final RuntimeException e) { + LOGGER.warn("error occured during shut down of the control loop participant service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { // NOSONAR + /* + * NOTE: arguments are validated by the constructor, thus sonar is disabled. + */ + + new Main(args); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeActivator.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeActivator.java new file mode 100644 index 000000000..d485895cf --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeActivator.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.startstop; + +import java.util.concurrent.atomic.AtomicReference; +import lombok.Getter; +import org.onap.policy.clamp.controlloop.participant.dcae.main.handler.DcaeHandler; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.common.utils.services.ServiceManagerContainer; + +/** + * This class activates the control loop runtime component as a complete service together with all its controllers, + * listeners & handlers. + */ +public class ParticipantDcaeActivator extends ServiceManagerContainer { + @Getter + private final ParticipantDcaeParameters parameters; + + /** + * Instantiate the activator for the dcae as a complete service. + * + * @param parameters the parameters for the control loop runtime service + */ + public ParticipantDcaeActivator(final ParticipantDcaeParameters parameters) { + this.parameters = parameters; + + final AtomicReference<DcaeHandler> dcaeHandler = new AtomicReference<>(); + + // @formatter:off + addAction("Dcae Handler", + () -> dcaeHandler.set(new DcaeHandler(parameters)), + () -> dcaeHandler.get().close()); + + addAction("Dcae Providers", + () -> dcaeHandler.get().startProviders(), + () -> dcaeHandler.get().stopProviders()); + + // @formatter:on + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeCommandLineArguments.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeCommandLineArguments.java new file mode 100644 index 000000000..0bf382ab1 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/ParticipantDcaeCommandLineArguments.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.main.startstop; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URL; +import java.util.Arrays; +import javax.ws.rs.core.Response; +import lombok.Getter; +import lombok.Setter; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.lang3.StringUtils; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.clamp.controlloop.common.startstop.CommonCommandLineArguments; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * This class reads and handles command line parameters for the control loop runtime service. + * + */ +public class ParticipantDcaeCommandLineArguments { + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + private final Options options; + private final CommonCommandLineArguments commonCommandLineArguments; + + @Getter() + @Setter() + private String configurationFilePath = null; + + /** + * Construct the options for the dcae participant. + */ + public ParticipantDcaeCommandLineArguments() { + options = new Options(); + commonCommandLineArguments = new CommonCommandLineArguments(options); + } + + /** + * Construct the options for the CLI editor and parse in the given arguments. + * + * @param args The command line arguments + */ + public ParticipantDcaeCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final ControlLoopException e) { + throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE, + "parse error on dcae participant parameters", e); + } + } + + /** + * Parse the command line options. + * + * @param args The command line arguments + * @return a string with a message for help and version, or null if there is no message + * @throws ControlLoopException on command argument errors + */ + public String parse(final String[] args) throws ControlLoopException { + // Clear all our arguments + setConfigurationFilePath(null); + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, + "invalid command line arguments specified : " + e.getMessage()); + } + + // Arguments left over after Commons CLI does its stuff + final String[] remainingArgs = commandLine.getArgs(); + + if (remainingArgs.length > 0) { + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, + "too many command line arguments specified : " + Arrays.toString(args)); + } + + if (commandLine.hasOption('h')) { + return commonCommandLineArguments.help(Main.class.getName(), options); + } + + if (commandLine.hasOption('v')) { + return commonCommandLineArguments.version(); + } + + if (commandLine.hasOption('c')) { + setConfigurationFilePath(commandLine.getOptionValue('c')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws ControlLoopException on command argument validation errors + */ + public void validate() throws ControlLoopException { + commonCommandLineArguments.validate(configurationFilePath); + } + + /** + * Gets the full expanded configuration file path. + * + * @return the configuration file path + */ + public String getFullConfigurationFilePath() { + return ResourceUtils.getFilePath4Resource(getConfigurationFilePath()); + } + + /** + * Check set configuration file path. + * + * @return true, if check set configuration file path + */ + public boolean checkSetConfigurationFilePath() { + return !StringUtils.isEmpty(configurationFilePath); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponent.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponent.java new file mode 100644 index 000000000..01a514f43 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponent.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.model; + +import java.io.Serializable; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ExternalComponent implements Serializable { + + private static final long serialVersionUID = -10; + + private ExternalComponentState componentState; + +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponentState.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponentState.java new file mode 100644 index 000000000..da7360a9b --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/ExternalComponentState.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.model; + +import java.io.Serializable; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ExternalComponentState implements Serializable { + + private static final long serialVersionUID = -10; + + private String stateName; +} diff --git a/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/Loop.java b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/Loop.java new file mode 100644 index 000000000..d84270500 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/main/java/org/onap/policy/clamp/controlloop/participant/dcae/model/Loop.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.controlloop.participant.dcae.model; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class Loop implements Serializable { + + private static final long serialVersionUID = -10; + + private Map<String, ExternalComponent> components = new HashMap<>(); +} |