diff options
Diffstat (limited to 'models-interactions/model-actors/actor.cds/src')
2 files changed, 0 insertions, 453 deletions
diff --git a/models-interactions/model-actors/actor.cds/src/main/java/org/onap/policy/controlloop/actor/cds/CdsActor.java b/models-interactions/model-actors/actor.cds/src/main/java/org/onap/policy/controlloop/actor/cds/CdsActor.java index d630d18ae..2a49c812d 100644 --- a/models-interactions/model-actors/actor.cds/src/main/java/org/onap/policy/controlloop/actor/cds/CdsActor.java +++ b/models-interactions/model-actors/actor.cds/src/main/java/org/onap/policy/controlloop/actor/cds/CdsActor.java @@ -19,40 +19,9 @@ package org.onap.policy.controlloop.actor.cds; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Struct; -import com.google.protobuf.Struct.Builder; -import com.google.protobuf.util.JsonFormat; -import io.grpc.Status; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; -import org.onap.policy.cds.CdsResponse; -import org.onap.policy.cds.api.CdsProcessorListener; -import org.onap.policy.cds.client.CdsProcessorGrpcClient; -import org.onap.policy.cds.properties.CdsServerProperties; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants; -import org.onap.policy.controlloop.actor.cds.request.CdsActionRequest; import org.onap.policy.controlloop.actorserviceprovider.Operator; import org.onap.policy.controlloop.actorserviceprovider.impl.ActorImpl; -import org.onap.policy.controlloop.policy.Policy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * CDS is an unusual actor in that it uses a single, generic operator to initiate all @@ -61,8 +30,6 @@ import org.slf4j.LoggerFactory; public class CdsActor extends ActorImpl { public static final String NAME = CdsActorConstants.CDS_ACTOR; - private static final Logger LOGGER = LoggerFactory.getLogger(CdsActor.class); - /** * Constructs the object. */ @@ -79,210 +46,4 @@ public class CdsActor extends ActorImpl { */ return super.getOperator(GrpcOperation.NAME); } - - // TODO old code: remove lines down to **HERE** - - /** - * {@inheritDoc}. - */ - @Override - public String actor() { - return CdsActorConstants.CDS_ACTOR; - } - - /** - * {@inheritDoc}. Note: This is a placeholder for now. - */ - @Override - public List<String> recipes() { - return new ArrayList<>(); - } - - /** - * {@inheritDoc}. Note: This is a placeholder for now. - */ - @Override - public List<String> recipeTargets(final String recipe) { - return new ArrayList<>(); - } - - /** - * {@inheritDoc}. Note: This is a placeholder for now. - */ - @Override - public List<String> recipePayloads(final String recipe) { - return new ArrayList<>(); - } - - /** - * Build the CDS ExecutionServiceInput request from the policy object and the AAI - * enriched parameters. TO-DO: Avoid leaking Exceptions to the Kie Session thread. TBD - * item for Frankfurt release. - * - * @param onset the event that is reporting the alert for policy to perform an action. - * @param operation the control loop operation specifying the actor, operation, - * target, etc. - * @param policy the policy specified from the yaml generated by CLAMP or through - * Policy API. - * @param aaiParams Map of enriched AAI attributes in node.attribute notation. - * @return an Optional ExecutionServiceInput instance if valid else an Optional empty - * object is returned. - */ - public Optional<ExecutionServiceInput> constructRequest(VirtualControlLoopEvent onset, - ControlLoopOperation operation, Policy policy, Map<String, String> aaiParams) { - - // For the current operational TOSCA policy model (yaml) CBA name and version are - // embedded in the payload - // section, with the new policy type model being proposed in Frankfurt we will be - // able to move it out. - Map<String, String> payload = policy.getPayload(); - if (!validateCdsMandatoryParams(policy)) { - return Optional.empty(); - } - String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME); - String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION); - - // Retain only the payload by removing CBA name and version once they are - // extracted - // to be put in CDS request header. - payload.remove(CdsActorConstants.KEY_CBA_NAME); - payload.remove(CdsActorConstants.KEY_CBA_VERSION); - - // Embed payload from policy to ConfigDeployRequest object, serialize and inject - // into grpc request. - String cbaActionName = policy.getRecipe(); - CdsActionRequest request = new CdsActionRequest(); - request.setPolicyPayload(payload); - request.setActionName(cbaActionName); - request.setResolutionKey(UUID.randomUUID().toString()); - - // Inject AAI properties into payload map. Offer flexibility to the usecase - // implementation to inject whatever AAI parameters are of interest to them. - // E.g. For vFW usecase El-Alto inject service-instance-id, generic-vnf-id as - // needed by CDS. - request.setAaiProperties(aaiParams); - - // Inject any additional event parameters that may be present in the onset event - if (onset.getAdditionalEventParams() != null) { - request.setAdditionalEventParams(onset.getAdditionalEventParams()); - } - - Builder struct = Struct.newBuilder(); - try { - String requestStr = request.generateCdsPayload(); - Preconditions.checkState(!Strings.isNullOrEmpty(requestStr), - "Unable to build " + "config-deploy-request from payload parameters: {}", payload); - JsonFormat.parser().merge(requestStr, struct); - } catch (InvalidProtocolBufferException | CoderException e) { - LOGGER.error("Failed to embed CDS payload string into the input request. blueprint({}:{}) for action({})", - cbaName, cbaVersion, cbaActionName, e); - return Optional.empty(); - } - - // Build CDS gRPC request common-header - CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(CdsActorConstants.ORIGINATOR_ID) - .setRequestId(onset.getRequestId().toString()).setSubRequestId(operation.getSubRequestId()) - .build(); - - // Build CDS gRPC request action-identifier - ActionIdentifiers actionIdentifiers = - ActionIdentifiers.newBuilder().setBlueprintName(cbaName).setBlueprintVersion(cbaVersion) - .setActionName(cbaActionName).setMode(CdsActorConstants.CDS_MODE).build(); - - // Finally build the ExecutionServiceInput gRPC request object. - ExecutionServiceInput executionServiceInput = ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader) - .setActionIdentifiers(actionIdentifiers).setPayload(struct.build()).build(); - return Optional.of(executionServiceInput); - } - - private boolean validateCdsMandatoryParams(Policy policy) { - if (policy == null || policy.getPayload() == null) { - return false; - } - Map<String, String> payload = policy.getPayload(); - String cbaName = payload.get(CdsActorConstants.KEY_CBA_NAME); - String cbaVersion = payload.get(CdsActorConstants.KEY_CBA_VERSION); - String cbaActionName = policy.getRecipe(); - return !Strings.isNullOrEmpty(cbaName) && !Strings.isNullOrEmpty(cbaVersion) - && !Strings.isNullOrEmpty(cbaActionName); - } - - public class CdsActorServiceManager implements CdsProcessorListener { - - private final AtomicReference<String> cdsStatus = new AtomicReference<>(); - - /** - * {@inheritDoc}. - */ - @Override - public void onMessage(final ExecutionServiceOutput message) { - LOGGER.info("Received notification from CDS: {}", message); - EventType eventType = message.getStatus().getEventType(); - switch (eventType) { - case EVENT_COMPONENT_FAILURE: - cdsStatus.compareAndSet(null, CdsActorConstants.FAILED); - break; - case EVENT_COMPONENT_PROCESSING: - cdsStatus.compareAndSet(null, CdsActorConstants.PROCESSING); - break; - case EVENT_COMPONENT_EXECUTED: - cdsStatus.compareAndSet(null, CdsActorConstants.SUCCESS); - break; - default: - cdsStatus.compareAndSet(null, CdsActorConstants.FAILED); - break; - } - } - - /** - * {@inheritDoc}. - */ - @Override - public void onError(final Throwable throwable) { - Status status = Status.fromThrowable(throwable); - cdsStatus.compareAndSet(null, CdsActorConstants.ERROR); - LOGGER.error("Failed processing blueprint {}", status, throwable); - } - - /** - * Send gRPC request to CDS to execute the blueprint. - * - * @param cdsClient CDS grpc client object. - * @param cdsProps CDS properties. - * @param executionServiceInput a valid CDS grpc request object. - * @return the cds response. - */ - public CdsResponse sendRequestToCds(CdsProcessorGrpcClient cdsClient, CdsServerProperties cdsProps, - ExecutionServiceInput executionServiceInput) { - try { - LOGGER.trace("Start CdsActorServiceProvider.executeCdsBlueprintProcessor {}.", executionServiceInput); - // TO-DO: Handle requests asynchronously once the callback support is - // added to actors. - CountDownLatch countDownLatch = cdsClient.sendRequest(executionServiceInput); - boolean status = countDownLatch.await(cdsProps.getTimeout(), TimeUnit.SECONDS); - if (!status) { - cdsStatus.compareAndSet(null, CdsActorConstants.TIMED_OUT); - } - LOGGER.info("CDS status response {}", getCdsStatus()); - } catch (InterruptedException ex) { - LOGGER.error("Caught exception in executeCdsBlueprintProcessor in CdsActorServiceProvider: ", ex); - cdsStatus.compareAndSet(null, CdsActorConstants.INTERRUPTED); - Thread.currentThread().interrupt(); - } - LOGGER.info("Status of the CDS gRPC request is: {}", getCdsStatus()); - - CdsResponse response = new CdsResponse(); - response.setRequestId(executionServiceInput != null && executionServiceInput.getCommonHeader() != null - ? executionServiceInput.getCommonHeader().getRequestId() - : null); - response.setStatus(this.getCdsStatus()); - return response; - } - - String getCdsStatus() { - return cdsStatus.get(); - } - } - - // **HERE** } diff --git a/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/CdsActorTest.java b/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/CdsActorTest.java index 706f170fb..1d84e1c60 100644 --- a/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/CdsActorTest.java +++ b/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/CdsActorTest.java @@ -20,116 +20,16 @@ package org.onap.policy.controlloop.actor.cds; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import com.google.common.collect.ImmutableMap; -import com.google.protobuf.Struct; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import org.junit.Before; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType; -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; -import org.onap.policy.cds.CdsResponse; -import org.onap.policy.cds.client.CdsProcessorGrpcClient; -import org.onap.policy.cds.properties.CdsServerProperties; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.actor.cds.CdsActor.CdsActorServiceManager; import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants; import org.onap.policy.controlloop.actor.test.BasicActor; import org.onap.policy.controlloop.actorserviceprovider.Operator; -import org.onap.policy.controlloop.policy.Policy; public class CdsActorTest extends BasicActor { - private static final String CDS_BLUEPRINT_NAME = "vfw-cds"; - private static final String CDS_BLUEPRINT_VERSION = "1.0.0"; - private static final UUID REQUEST_ID = UUID.randomUUID(); - private static final String SUBREQUEST_ID = "123456"; - private static final String CDS_RECIPE = "test-cds-recipe"; - - @Mock - private CdsProcessorGrpcClient cdsClient; - private CdsActor cdsActor; - private Policy policy; - private CdsServerProperties cdsProps; - private Map<String, String> aaiParams; - private VirtualControlLoopEvent onset; - private ControlLoopOperation operation; - - /** - * Test setup. - */ - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - // Setup policy - policy = new Policy(); - Map<String, String> payloadMap = new HashMap<String, String>() { - private static final long serialVersionUID = 1L; - - { - put(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME); - put(CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION); - put("data", "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}"); - } - }; - policy.setPayload(payloadMap); - policy.setRecipe(CDS_RECIPE); - - // Setup the CDS properties - cdsProps = new CdsServerProperties(); - cdsProps.setHost("10.10.10.10"); - cdsProps.setPort(2000); - cdsProps.setUsername("testUser"); - cdsProps.setPassword("testPassword"); - cdsProps.setTimeout(1); - - // Setup aaiParams - aaiParams = ImmutableMap.of("service-instance-id", "1234", "generic-vnf-id", "5678"); - - // Setup cdsClient - when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class)); - - // Setup the cdsActor - cdsActor = new CdsActor(); - - // Setup onset event - onset = new VirtualControlLoopEvent(); - onset.setRequestId(REQUEST_ID); - - // Setup controlloop operation object - operation = new ControlLoopOperation(); - operation.setSubRequestId(SUBREQUEST_ID); - } - - @Test - public void testActor() { - assertEquals(CdsActorConstants.CDS_ACTOR, cdsActor.actor()); - } - @Test public void testActorService() { // verify that it all plugs into the ActorService @@ -145,118 +45,4 @@ public class CdsActorTest extends BasicActor { assertNotNull(oper); assertSame(oper, sp.getOperator("another")); } - - @Test - public void testConstructRequestWhenMissingCdsParamsInPolicyPayload() { - policy.setPayload(new HashMap<>()); - Optional<ExecutionServiceInput> cdsRequestOpt = cdsActor.constructRequest(onset, operation, policy, aaiParams); - - assertFalse(cdsRequestOpt.isPresent()); - } - - @Test - public void testConstructRequest() { - Optional<ExecutionServiceInput> cdsRequestOpt = cdsActor.constructRequest(onset, operation, policy, aaiParams); - - assertTrue(cdsRequestOpt.isPresent()); - final ExecutionServiceInput cdsRequest = cdsRequestOpt.get(); - - assertTrue(cdsRequest.hasCommonHeader()); - CommonHeader commonHeader = cdsRequest.getCommonHeader(); - assertEquals(commonHeader.getRequestId(), REQUEST_ID.toString()); - assertEquals(SUBREQUEST_ID, commonHeader.getSubRequestId()); - - assertTrue(cdsRequest.hasPayload()); - Struct cdsPayload = cdsRequest.getPayload(); - assertTrue(cdsPayload.containsFields(CDS_RECIPE + "-request")); - - assertTrue(cdsRequest.hasActionIdentifiers()); - ActionIdentifiers actionIdentifiers = cdsRequest.getActionIdentifiers(); - assertEquals(CDS_RECIPE, actionIdentifiers.getActionName()); - assertEquals(CDS_BLUEPRINT_NAME, actionIdentifiers.getBlueprintName()); - assertEquals(CDS_BLUEPRINT_VERSION, actionIdentifiers.getBlueprintVersion()); - } - - @Test - public void testRecipePayloads() { - assertEquals(0, cdsActor.recipePayloads("").size()); - } - - @Test - public void testRecipes() { - assertEquals(0, cdsActor.recipes().size()); - } - - @Test - public void testRecipeTargets() { - assertEquals(0, cdsActor.recipeTargets("").size()); - } - - @Test - public void testSendRequestToCdsSuccess() { - sendRequestToCds(); - verify(cdsClient).sendRequest(any(ExecutionServiceInput.class)); - } - - @Test - public void testSendRequestToCdsLatchInterrupted() throws InterruptedException { - // Reset cdsClient - CountDownLatch countDownLatch = mock(CountDownLatch.class); - doThrow(new InterruptedException("Test latch interrupted failure")).when(countDownLatch).await(anyLong(), - any(TimeUnit.class)); - when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(countDownLatch); - - CdsActor.CdsActorServiceManager cdsActorSvcMgr = cdsActor.new CdsActorServiceManager(); - CdsResponse response = - cdsActorSvcMgr.sendRequestToCds(cdsClient, cdsProps, ExecutionServiceInput.newBuilder().build()); - assertTrue(Thread.interrupted()); - assertNotNull(response); - assertEquals(CdsActorConstants.INTERRUPTED, response.getStatus()); - } - - @Test - public void testSendRequestToCdsLatchTimedOut() { - CdsActor.CdsActorServiceManager cdsActorSvcMgr = cdsActor.new CdsActorServiceManager(); - CdsResponse response = - cdsActorSvcMgr.sendRequestToCds(cdsClient, cdsProps, ExecutionServiceInput.newBuilder().build()); - assertNotNull(response); - assertEquals(CdsActorConstants.TIMED_OUT, response.getStatus()); - } - - @Test - public void testOnMessage() throws InterruptedException { - ExecutionServiceOutput message = ExecutionServiceOutput.newBuilder() - .setStatus(Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_FAILURE).build()).build(); - - // Test "no timeout" scenarios - CountDownLatch latch = mock(CountDownLatch.class); - when(latch.await(anyLong(), any(TimeUnit.class))).thenReturn(true); - when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(latch); - - CdsActorServiceManager cdsActorSvcMgr = sendRequestToCds(); - - // #1: Failure test - cdsActorSvcMgr.onMessage(message); - assertEquals(CdsActorConstants.FAILED, cdsActorSvcMgr.getCdsStatus()); - - // #2: Success test - cdsActorSvcMgr = sendRequestToCds(); - message = ExecutionServiceOutput.newBuilder() - .setStatus(Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_EXECUTED).build()).build(); - cdsActorSvcMgr.onMessage(message); - assertEquals(CdsActorConstants.SUCCESS, cdsActorSvcMgr.getCdsStatus()); - - // #3: Processing test - cdsActorSvcMgr = sendRequestToCds(); - message = ExecutionServiceOutput.newBuilder() - .setStatus(Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_PROCESSING).build()).build(); - cdsActorSvcMgr.onMessage(message); - assertEquals(CdsActorConstants.PROCESSING, cdsActorSvcMgr.getCdsStatus()); - } - - private CdsActorServiceManager sendRequestToCds() { - CdsActorServiceManager cdsActorSvcMgr = cdsActor.new CdsActorServiceManager(); - cdsActorSvcMgr.sendRequestToCds(cdsClient, cdsProps, ExecutionServiceInput.newBuilder().build()); - return cdsActorSvcMgr; - } } |