diff options
Diffstat (limited to 'models-interactions/model-actors/actor.vfc')
13 files changed, 1121 insertions, 52 deletions
diff --git a/models-interactions/model-actors/actor.vfc/pom.xml b/models-interactions/model-actors/actor.vfc/pom.xml index 7f6cc6e9e..bf38df57a 100644 --- a/models-interactions/model-actors/actor.vfc/pom.xml +++ b/models-interactions/model-actors/actor.vfc/pom.xml @@ -18,58 +18,87 @@ ============LICENSE_END========================================================= --> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> - <artifactId>model-actors</artifactId> - <version>2.2.1-SNAPSHOT</version> - </parent> + <parent> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>model-actors</artifactId> + <version>2.2.1-SNAPSHOT</version> + </parent> - <artifactId>actor.vfc</artifactId> + <artifactId>actor.vfc</artifactId> - <dependencies> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> - <artifactId>actorServiceProvider</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> - <artifactId>vfc</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> - <artifactId>events</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> - <artifactId>aai</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.common</groupId> - <artifactId>policy-endpoints</artifactId> - <version>${policy.common.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions</groupId> - <artifactId>simulators</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - </dependencies> + <dependencies> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> + <artifactId>aai</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> + <artifactId>events</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> + <artifactId>vfc</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>actor.aai</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>policy-endpoints</artifactId> + <version>${policy.common.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>actor.test</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions</groupId> + <artifactId>simulators</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito2</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> + </dependencies> </project> diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/Restart.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/Restart.java new file mode 100644 index 000000000..2c5cf8eda --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/Restart.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import java.util.concurrent.CompletableFuture; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.vfc.VfcRequest; + +public class Restart extends VfcOperation { + public static final String NAME = "VF Module Create"; + + public Restart(ControlLoopOperationParams params, HttpConfig config) { + super(params, config); + } + + @Override + protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) { + + // starting a whole new attempt - reset the count + resetGetCount(); + + Pair<String, VfcRequest> pair = makeRequest(); + Entity<VfcRequest> entity = Entity.entity(pair.getRight(), MediaType.APPLICATION_JSON); + String path = getPath() + pair.getLeft(); + String url = getClient().getBaseUrl() + path; + + return handleResponse(outcome, url, callback -> getClient().post(callback, path, entity, null)); + } + + /** + * Makes a request. + * + * @return a pair containing the request URL and the new request + */ + protected Pair<String, VfcRequest> makeRequest() { + + VfcRequest request = super.constructVfcRequest(); + String requestUrl = "/ns/" + request.getNsInstanceId() + "/heal"; + return Pair.of(requestUrl, request); + } +} diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java index 8d560ef3c..b7a41ddf0 100644 --- a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java @@ -37,6 +37,8 @@ import org.onap.policy.vfc.VfcRequest; public class VfcActorServiceProvider extends ActorImpl { private static final String GENERIC_VNF_ID = "generic-vnf.vnf-id"; + // TODO old code: remove lines down to **HERE** + // Strings for VFC Actor private static final String VFC_ACTOR = "VFC"; @@ -50,10 +52,19 @@ public class VfcActorServiceProvider extends ActorImpl { private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).build(); + // **HERE** + + /** + * Constructor. + */ public VfcActorServiceProvider() { super(VFC_ACTOR); + + addOperator(new VfcOperator(VFC_ACTOR, Restart.NAME, Restart::new)); } + // TODO old code: remove lines down to **HERE** + @Override public String actor() { return VFC_ACTOR; @@ -90,7 +101,7 @@ public class VfcActorServiceProvider extends ActorImpl { VfcRequest request = new VfcRequest(); String serviceInstance = onset.getAai().get("service-instance.service-instance-id"); if (serviceInstance == null || "".equals(serviceInstance)) { - // get service isntance from AaiCqResponse + // get service instance from AaiCqResponse if (aaiCqResponse == null) { return null; } @@ -120,4 +131,7 @@ public class VfcActorServiceProvider extends ActorImpl { } return request; } + + // **HERE** + } diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcConfig.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcConfig.java new file mode 100644 index 000000000..4b5088a3a --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcConfig.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import java.util.concurrent.Executor; +import lombok.Getter; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; + +@Getter +public class VfcConfig extends HttpConfig { + + /** + * Path to use for the "get" request. A trailing "/" is added, if it is missing. + */ + private String pathGet; + + /** + * Maximum number of "get" requests permitted, after the initial request, to retrieve + * the response. + */ + private int maxGets; + + /** + * Time, in seconds, to wait between issuing "get" requests. + */ + private int waitSecGet; + + /** + * Constructor. + * + * @param blockingExecutor executor to be used for tasks that may perform blocking I/O + * @param params operator parameters + * @param clientFactory factory from which to obtain the {@link HttpClient} + */ + public VfcConfig(Executor blockingExecutor, VfcParams params, HttpClientFactory clientFactory) { + super(blockingExecutor, params, clientFactory); + + this.pathGet = params.getPathGet() + (params.getPathGet().endsWith("/") ? "" : "/"); + this.maxGets = params.getMaxGets(); + this.waitSecGet = params.getWaitSecGet(); + } + +} diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperation.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperation.java new file mode 100644 index 000000000..827109d10 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperation.java @@ -0,0 +1,245 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import javax.ws.rs.core.Response; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.vfc.VfcHealActionVmInfo; +import org.onap.policy.vfc.VfcHealAdditionalParams; +import org.onap.policy.vfc.VfcHealRequest; +import org.onap.policy.vfc.VfcRequest; +import org.onap.policy.vfc.VfcResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class VfcOperation extends HttpOperation<VfcResponse> { + private static final Logger logger = LoggerFactory.getLogger(VfcOperation.class); + + public static final String FAILED = "FAILED"; + public static final String COMPLETE = "COMPLETE"; + public static final int VFC_RESPONSE_CODE = 999; + public static final String GENERIC_VNF_ID = "generic-vnf.vnf-id"; + + public static final String REQ_PARAM_NM = "requestParameters"; + public static final String CONFIG_PARAM_NM = "configurationParameters"; + + private final VfcConfig config; + + /** + * Number of "get" requests issued so far, on the current operation attempt. + */ + @Getter + private int getCount; + + /** + * Constructs the object. + * + * @param params operation parameters + * @param config configuration for this operation + */ + public VfcOperation(ControlLoopOperationParams params, HttpConfig config) { + super(params, config, VfcResponse.class); + this.config = (VfcConfig) config; + } + + /** + * Subclasses should invoke this before issuing their first HTTP request. + */ + protected void resetGetCount() { + getCount = 0; + } + + /** + * Starts the GUARD. + */ + @Override + protected CompletableFuture<OperationOutcome> startPreprocessorAsync() { + return startGuardAsync(); + } + + /** + * If the response does not indicate that the request has been completed, then sleep a + * bit and issue a "get". + */ + @Override + protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url, + Response rawResponse, VfcResponse response) { + // Determine if the request has "completed" and determine if it was successful + if (rawResponse.getStatus() == 200) { + String requestState = getRequestState(response); + if ("finished".equalsIgnoreCase(requestState)) { + return CompletableFuture + .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response)); + } + + if ("error".equalsIgnoreCase(requestState)) { + return CompletableFuture + .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response)); + } + } + + // still incomplete + + // need a request ID with which to query + if (response == null || response.getJobId() == null) { + throw new IllegalArgumentException("missing job ID in response"); + } + + // see if the limit for the number of "gets" has been reached + if (getCount++ >= getMaxGets()) { + logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId()); + setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT); + outcome.setMessage(VFC_RESPONSE_CODE + " " + outcome.getMessage()); + return CompletableFuture.completedFuture(outcome); + } + + // sleep and then perform a "get" operation + Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response); + return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet); + } + + /** + * Issues a "get" request to see if the original request is complete yet. + * + * @param outcome outcome to be populated with the response + * @param response previous response + * @return a future that can be used to cancel the "get" request or await its response + */ + private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, VfcResponse response) { + String path = getPathGet() + response.getJobId(); + String url = getClient().getBaseUrl() + path; + + logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId()); + + logMessage(EventType.OUT, CommInfrastructure.REST, url, null); + + return handleResponse(outcome, url, callback -> getClient().get(callback, path, null)); + } + + /** + * Gets the request state of a response. + * + * @param response response from which to get the state + * @return the request state of the response, or {@code null} if it does not exist + */ + protected String getRequestState(VfcResponse response) { + if (response == null || response.getResponseDescriptor() == null + || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) { + return null; + } + return response.getResponseDescriptor().getStatus(); + } + + /** + * Treats everything as a success, so we always go into + * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}. + */ + @Override + protected boolean isSuccess(Response rawResponse, VfcResponse response) { + return true; + } + + /** + * Prepends the message with the http status code. + */ + @Override + public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse, + VfcResponse response) { + + // set default result and message + setOutcome(outcome, result); + + outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage()); + return outcome; + } + + /** + * Construct VfcRequestObject from the ControlLoopOperationParams. + * + * @return request + */ + protected VfcRequest constructVfcRequest() { + ControlLoopEventContext context = params.getContext(); + String serviceInstance = context.getEnrichment().get("service-instance.service-instance-id"); + String vmId = context.getEnrichment().get("vserver.vserver-id"); + String vmName = context.getEnrichment().get("vserver.vserver-name"); + + if (StringUtils.isBlank(serviceInstance) || StringUtils.isBlank(vmId) || StringUtils.isBlank(vmName)) { + throw new IllegalArgumentException( + "Cannot extract enrichment data for service instance, server id, or server name."); + } + + VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo(); + vmActionInfo.setVmid(vmId); + vmActionInfo.setVmname(vmName); + + VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams(); + additionalParams.setAction(getName()); + additionalParams.setActionInfo(vmActionInfo); + + VfcHealRequest healRequest = new VfcHealRequest(); + healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID)); + healRequest.setCause(getName()); + healRequest.setAdditionalParams(additionalParams); + + VfcRequest request = new VfcRequest(); + request.setHealRequest(healRequest); + request.setNsInstanceId(serviceInstance); + request.setRequestId(context.getEvent().getRequestId()); + + return request; + } + + // These may be overridden by jUnit tests + + /** + * Gets the wait time, in milliseconds, between "get" requests. + * + * @return the wait time, in milliseconds, between "get" requests + */ + public long getWaitMsGet() { + return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS); + } + + public int getMaxGets() { + return config.getMaxGets(); + } + + public String getPathGet() { + return config.getPathGet(); + } + + public int getWaitSecGet() { + return config.getWaitSecGet(); + } +} diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperator.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperator.java new file mode 100644 index 000000000..4e70d6550 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcOperator.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import java.util.Map; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator; +import org.onap.policy.controlloop.actorserviceprovider.impl.OperationMaker; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +public class VfcOperator extends HttpOperator { + + public VfcOperator(String actorName, String name, + @SuppressWarnings("rawtypes") OperationMaker<HttpConfig, HttpOperation> operationMaker) { + super(actorName, name, operationMaker); + } + + @Override + protected HttpConfig makeConfiguration(Map<String, Object> parameters) { + VfcParams params = Util.translate(getFullName(), parameters, VfcParams.class); + ValidationResult result = params.validate(getFullName()); + if (!result.isValid()) { + throw new ParameterValidationRuntimeException("invalid parameters", result); + } + + return new VfcConfig(getBlockingExecutor(), params, getClientFactory()); + } +} diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcParams.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcParams.java new file mode 100644 index 000000000..31c2a9441 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcParams.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.SuperBuilder; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; + +@NotNull +@NotBlank +@Data +@EqualsAndHashCode(callSuper = true) +@SuperBuilder(toBuilder = true) +public class VfcParams extends HttpParams { + + /** + * Path to use for the "get" request. + */ + private String pathGet; + + /** + * Maximum number of "get" requests permitted, after the initial request, to retrieve + * the response. + */ + @Min(0) + private int maxGets; + + /** + * Time, in seconds, to wait between issuing "get" requests. + */ + @Min(1) + private int waitSecGet; +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/BasicVfcOperation.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/BasicVfcOperation.java new file mode 100644 index 000000000..be62bbb3f --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/BasicVfcOperation.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.mockito.Mockito.when; + +import org.mockito.Mock; +import org.onap.policy.controlloop.actor.test.BasicHttpOperation; +import org.onap.policy.vfc.VfcRequest; +import org.onap.policy.vfc.VfcResponse; + +public abstract class BasicVfcOperation extends BasicHttpOperation<VfcRequest> { + public static final String PATH_GET = "my-path-get/"; + public static final int MAX_GETS = 3; + public static final int WAIT_SEC_GETS = 20; + + @Mock + protected VfcConfig config; + + protected VfcResponse response; + + /** + * Constructs the object using a default actor and operation name. + */ + public BasicVfcOperation() { + super(); + } + + /** + * Constructs the object. + * + * @param actor actor name + * @param operation operation name + */ + public BasicVfcOperation(String actor, String operation) { + super(actor, operation); + } + + /** + * Initializes mocks and sets up. + */ + public void setUp() throws Exception { + super.setUpBasic(); + + response = new VfcResponse(); + + // PLD + + when(rawResponse.getStatus()).thenReturn(200); + when(rawResponse.readEntity(String.class)).thenReturn(coder.encode(response)); + + initConfig(); + } + + @Override + protected void initConfig() { + super.initConfig(); + when(config.getClient()).thenReturn(client); + when(config.getMaxGets()).thenReturn(MAX_GETS); + when(config.getPathGet()).thenReturn(PATH_GET); + when(config.getWaitSecGet()).thenReturn(WAIT_SEC_GETS); + } + +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/RestartTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/RestartTest.java new file mode 100644 index 000000000..dd6c4cf69 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/RestartTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.concurrent.CompletableFuture; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.vfc.VfcRequest; + +public class RestartTest extends BasicVfcOperation { + private Restart restartOper; + + /** + * setup restart operation. + */ + @Before + public void setup() throws Exception { + super.setUp(); + params.getContext().getEnrichment().put("service-instance.service-instance-id", "test-service-instance-id"); + params.getContext().getEnrichment().put("vserver.vserver-id", "test-vserver-id"); + params.getContext().getEnrichment().put("vserver.vserver-name", "test-vserver-name"); + restartOper = new Restart(params, config); + } + + @Test + public void testStartOperationAsync() { + CompletableFuture<OperationOutcome> futureRes = restartOper.startOperationAsync(1, outcome); + assertNotNull(futureRes); + assertEquals(0, restartOper.getGetCount()); + } + + @Test + public void testMakeRequest() { + Pair<String, VfcRequest> resultPair = restartOper.makeRequest(); + assertNotNull(resultPair.getLeft()); + assertNotNull(resultPair.getRight()); + } +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcConfigTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcConfigTest.java new file mode 100644 index 000000000..f03e32393 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcConfigTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.when; + +import java.util.concurrent.Executor; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; + +public class VfcConfigTest { + private static final String MY_CLIENT = "my-client"; + private static final String MY_PATH = "my-path"; + private static final String GET_PATH = "get-path"; + private static final int TIMEOUT_SEC = 10; + private static final int MAX_GETS = 20; + private static final int WAIT_SEC = 30; + + @Mock + private HttpClient client; + @Mock + private HttpClientFactory factory; + @Mock + private Executor executor; + + private VfcParams params; + private VfcConfig config; + + /** + * Setup. + * + * @throws Exception Exception + */ + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + when(factory.get(MY_CLIENT)).thenReturn(client); + + params = VfcParams.builder().maxGets(MAX_GETS).pathGet(GET_PATH).waitSecGet(WAIT_SEC).clientName(MY_CLIENT) + .path(MY_PATH).timeoutSec(TIMEOUT_SEC).build(); + config = new VfcConfig(executor, params, factory); + } + + @Test + public void test() { + assertEquals(GET_PATH + "/", config.getPathGet()); + assertEquals(MAX_GETS, config.getMaxGets()); + assertEquals(WAIT_SEC, config.getWaitSecGet()); + + // check value from superclass + assertSame(executor, config.getBlockingExecutor()); + assertSame(client, config.getClient()); + + // path with trailing "/" + params = params.toBuilder().pathGet(GET_PATH + "/").build(); + config = new VfcConfig(executor, params, factory); + assertEquals(GET_PATH + "/", config.getPathGet()); + } + +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperationTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperationTest.java new file mode 100644 index 000000000..4fe0cd4a6 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperationTest.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.vfc.VfcResponse; +import org.onap.policy.vfc.VfcResponseDescriptor; + +public class VfcOperationTest extends BasicVfcOperation { + + private VfcOperation oper; + + /** + * setUp. + */ + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + initConfig(); + + oper = new VfcOperation(params, config) {}; + } + + @Test + public void testConstructor_testGetWaitMsGet() { + assertEquals(DEFAULT_ACTOR, oper.getActorName()); + assertEquals(DEFAULT_OPERATION, oper.getName()); + assertSame(config, oper.getConfig()); + assertEquals(1000 * WAIT_SEC_GETS, oper.getWaitMsGet()); + } + + @Test + public void testStartPreprocessorAsync() { + assertNotNull(oper.startPreprocessorAsync()); + } + + @Test + public void testResetGetCount() { + oper.resetGetCount(); + assertEquals(0, oper.getGetCount()); + } + + @Test + public void testPostProcess() throws Exception { + + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + oper.postProcessResponse(outcome, PATH, rawResponse, response); + }); + + response.setResponseDescriptor(new VfcResponseDescriptor()); + response.setJobId("sampleJobId"); + CompletableFuture<OperationOutcome> future2 = oper.postProcessResponse(outcome, PATH, rawResponse, response); + assertFalse(future2.isDone()); + //assertSame(outcome, future2.get()); TODO Hanging + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + + response.getResponseDescriptor().setStatus("FinisHeD"); + future2 = oper.postProcessResponse(outcome, PATH, rawResponse, response); + assertTrue(future2.isDone()); + assertSame(outcome, future2.get()); + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + + response.getResponseDescriptor().setStatus("eRRor"); + future2 = oper.postProcessResponse(outcome, PATH, rawResponse, response); + assertTrue(future2.isDone()); + assertSame(outcome, future2.get()); + assertEquals(PolicyResult.FAILURE, outcome.getResult()); + + // failed + /*response.getResponseDescriptor().setStatus("anything but finished"); + future2 = oper.postProcessResponse(outcome, PATH, rawResponse, response); + assertTrue(future2.isDone()); + assertSame(outcome, future2.get()); + assertEquals(PolicyResult.FAILURE, outcome.getResult());*/ + } + + @Test + public void testGetRequestState() { + VfcResponse mockResponse = Mockito.mock(VfcResponse.class); + Mockito.when(mockResponse.getResponseDescriptor()).thenReturn(null); + assertNull(oper.getRequestState(mockResponse)); + + VfcResponseDescriptor mockDescriptor = Mockito.mock(VfcResponseDescriptor.class); + Mockito.when(mockResponse.getResponseDescriptor()).thenReturn(mockDescriptor); + Mockito.when(mockDescriptor.getStatus()).thenReturn("COMPLETE"); // TODO use actual request state value + assertNotNull(oper.getRequestState(mockResponse)); + } + + @Test + public void testIsSuccess() { + assertTrue(oper.isSuccess(rawResponse, response)); + } + +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperatorTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperatorTest.java new file mode 100644 index 000000000..d469d5a74 --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcOperatorTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +public class VfcOperatorTest { + private static final String ACTOR = "my-actor"; + private static final String OPERATION = "my-name"; + private static final String CLIENT = "my-client"; + private static final String PATH = "/my-path"; + private static final String PATH_GET = "my-path-get/"; + private static final int MAX_GETS = 3; + private static final int WAIT_SEC_GETS = 20; + private static final int TIMEOUT = 100; + + private VfcOperator oper; + + @Mock + private HttpClient client; + + @Mock + private HttpClientFactory factory; + + /** + * setUp. + * + * @throws Exception exception + */ + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + when(factory.get(CLIENT)).thenReturn(client); + + oper = new MyOperator(); + + VfcParams params = VfcParams.builder().pathGet(PATH_GET).maxGets(MAX_GETS).waitSecGet(WAIT_SEC_GETS) + .clientName(CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + Map<String, Object> paramMap = Util.translateToMap(OPERATION, params); + oper.configure(paramMap); + } + + @Test + public void testConstructor() { + assertEquals(ACTOR, oper.getActorName()); + assertEquals(OPERATION, oper.getName()); + assertEquals(ACTOR + "." + OPERATION, oper.getFullName()); + } + + @Test + public void testDoConfigure_testGetters() { + assertTrue(oper.getCurrentConfig() instanceof VfcConfig); + + // test invalid parameters + Map<String, Object> paramMap2 = Util.translateToMap(OPERATION, VfcParams.builder().build()); + assertThatThrownBy(() -> oper.configure(paramMap2)).isInstanceOf(ParameterValidationRuntimeException.class); + } + + private class MyOperator extends VfcOperator { + + public MyOperator() { + super(ACTOR, OPERATION, null); + } + + @Override + protected HttpClientFactory getClientFactory() { + return factory; + } + } +} diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcParamsTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcParamsTest.java new file mode 100644 index 000000000..5e324463f --- /dev/null +++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcParamsTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 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.policy.controlloop.actor.vfc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.function.Function; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actor.vfc.VfcParams.VfcParamsBuilder; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams.HttpParamsBuilder; + +public class VfcParamsTest { + private static final String CONTAINER = "my-container"; + private static final String CLIENT = "my-client"; + private static final String PATH = "my-path"; + private static final String PATH_GET = "my-path-get"; + private static final int MAX_GETS = 3; + private static final int WAIT_SEC_GETS = 20; + private static final int TIMEOUT = 10; + + private VfcParams params; + + @Before + public void setUp() throws Exception { + params = VfcParams.builder().pathGet(PATH_GET).maxGets(MAX_GETS).waitSecGet(WAIT_SEC_GETS).clientName(CLIENT) + .path(PATH).timeoutSec(TIMEOUT).build(); + } + + @Test + public void testValidate() { + assertTrue(params.validate(CONTAINER).isValid()); + + testValidateField("pathGet", "null", bldr -> bldr.pathGet(null)); + testValidateField("maxGets", "minimum", bldr -> bldr.maxGets(-1)); + testValidateField("waitSecGet", "minimum", bldr -> bldr.waitSecGet(-1)); + + // validate one of the superclass fields + testValidateField("clientName", "null", bldr -> bldr.clientName(null)); + + // check edge cases + assertTrue(params.toBuilder().maxGets(0).build().validate(CONTAINER).isValid()); + assertFalse(params.toBuilder().waitSecGet(0).build().validate(CONTAINER).isValid()); + assertTrue(params.toBuilder().waitSecGet(1).build().validate(CONTAINER).isValid()); + } + + @Test + public void testBuilder_testToBuilder() { + assertEquals(CLIENT, params.getClientName()); + + assertEquals(PATH_GET, params.getPathGet()); + assertEquals(MAX_GETS, params.getMaxGets()); + assertEquals(WAIT_SEC_GETS, params.getWaitSecGet()); + + assertEquals(params, params.toBuilder().build()); + } + + private void testValidateField(String fieldName, String expected, + @SuppressWarnings("rawtypes") Function<VfcParamsBuilder, HttpParamsBuilder> makeInvalid) { + + // original params should be valid + ValidationResult result = params.validate(CONTAINER); + assertTrue(fieldName, result.isValid()); + + // make invalid params + result = makeInvalid.apply(params.toBuilder()).build().validate(CONTAINER); + assertFalse(fieldName, result.isValid()); + assertThat(result.getResult()).contains(fieldName).contains(expected); + } + +} |