From af861a9d8e28d49d357ead4a4acad82554510b6f Mon Sep 17 00:00:00 2001 From: mmis Date: Wed, 21 Mar 2018 15:22:10 +0000 Subject: Removed checkstyle warnings Removed checkstyle warnings in: policy/drools-applications/controlloop/common/actors policy/drools-applications/controlloop/common/eventmanager policy/drools-applications/controlloop/common/feature-controlloop-utils Issue-ID: POLICY-705 Change-Id: Iccf99b291bc62bc3ba2082ccdb4c1f9e12107896 Signed-off-by: mmis --- .../actor/appc/APPCActorServiceProvider.java | 189 +- .../actor/appc/AppcServiceProviderTest.java | 49 +- .../actor/appclcm/AppcLcmActorServiceProvider.java | 582 +++--- .../actor/appclcm/AppcLcmServiceProviderTest.java | 116 +- .../actor/so/SOActorServiceProvider.java | 719 ++++---- .../actor/so/TestSOActorServiceProvider.java | 149 +- .../actor/vfc/VFCActorServiceProvider.java | 225 +-- .../actor/vfc/TestVFCActorServiceProvider.java | 132 +- .../actorserviceprovider/ActorService.java | 71 +- .../actorserviceprovider/spi/Actor.java | 18 +- .../actorserviceprovider/TestActor.java | 62 +- .../TestActorServiceProvider.java | 47 +- .../policy/controlloop/ControlLoopException.java | 36 +- .../onap/policy/controlloop/ControlLoopLogger.java | 49 +- .../policy/controlloop/ControlLoopPublisher.java | 42 +- .../eventmanager/ControlLoopEventManager.java | 1431 ++++++++------- .../eventmanager/ControlLoopOperationManager.java | 1504 +++++++-------- .../eventmanager/OperationsHistoryDbEntry.java | 195 +- .../impl/ControlLoopLoggerStdOutImpl.java | 36 +- .../impl/ControlLoopPublisherJUnitImpl.java | 11 +- .../processor/ControlLoopProcessor.java | 152 +- .../java/org/onap/policy/drools/PolicyEngine.java | 5 +- .../onap/policy/drools/PolicyEngineListener.java | 11 +- .../policy/drools/impl/PolicyEngineJUnitImpl.java | 203 ++- .../controlloop/ControlLoopExceptionTest.java | 18 +- .../policy/controlloop/ControlLoopLoggerTest.java | 32 +- .../controlloop/ControlLoopPublisherTest.java | 39 +- .../java/org/onap/policy/controlloop/Util.java | 62 +- .../eventmanager/ControlLoopEventManagerTest.java | 1915 ++++++++++---------- .../ControlLoopOperationManagerTest.java | 1353 +++++++------- .../eventmanager/OperationsHistoryDbEntryTest.java | 98 +- .../processor/ControlLoopProcessorTest.java | 254 +-- .../onap/policy/drools/DroolsPolicyEngineTest.java | 68 +- .../feature/utils/ControlLoopUtilsFeature.java | 49 +- .../feature/utils/ControlLoopUtilsFeatureTest.java | 27 +- 35 files changed, 5151 insertions(+), 4798 deletions(-) diff --git a/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java b/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java index ef897b9c9..e9cd70c42 100644 --- a/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java +++ b/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * APPCActorServiceProvider * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,118 +20,107 @@ package org.onap.policy.controlloop.actor.appc; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + import java.util.Collections; import java.util.List; -import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.appc.CommonHeader; import org.onap.policy.appc.Request; import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.vnf.trafficgenerator.PGRequest; import org.onap.policy.vnf.trafficgenerator.PGStream; import org.onap.policy.vnf.trafficgenerator.PGStreams; -import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; public class APPCActorServiceProvider implements Actor { - // Strings for targets - private static final String TARGET_VM = "VM"; - private static final String TARGET_VNF = "VNF"; - - // Strings for recipes - private static final String RECIPE_RESTART = "Restart"; - private static final String RECIPE_REBUILD = "Rebuild"; - private static final String RECIPE_MIGRATE = "Migrate"; - private static final String RECIPE_MODIFY = "ModifyConfig"; - - private static final ImmutableList recipes = ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); - private static final ImmutableMap> targets = new ImmutableMap.Builder>() - .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)) - .put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM)) - .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)) - .put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)) - .build(); - private static final ImmutableMap> payloads = new ImmutableMap.Builder>() - .put(RECIPE_MODIFY, ImmutableList.of("generic-vnf.vnf-id")) - .build(); - - @Override - public String actor() { - return "APPC"; - } - - @Override - public List recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List recipePayloads(String recipe) { - return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList())); - } - - /** - * Constructs an APPC request conforming to the legacy API. - * The legacy API will be deprecated in future releases as - * all legacy functionality is moved into the LCM API. - * - * @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 the was specified from the yaml generated - * by CLAMP or through the Policy GUI/API - * @return an APPC request conforming to the legacy API - * @throws AAIException - */ - public static Request constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, - Policy policy, String targetVnf) { - /* - * Construct an APPC request - */ - Request request = new Request(); - request.setCommonHeader(new CommonHeader()); - request.getCommonHeader().setRequestID(onset.getRequestID()); - request.getCommonHeader().setSubRequestID(operation.getSubRequestId()); - request.setAction(policy.getRecipe().substring(0, 1).toUpperCase() - + policy.getRecipe().substring(1)); - - /* - * For now Policy generates the PG Streams as a demo, in the - * future the payload can be provided by CLAMP - */ - request.getPayload().put("generic-vnf.vnf-id", targetVnf); - - PGRequest pgRequest = new PGRequest(); - pgRequest.pgStreams = new PGStreams(); - - PGStream pgStream; - for (int i = 0; i < 5; i++) { - pgStream = new PGStream(); - pgStream.streamId = "fw_udp"+(i+1); - pgStream.isEnabled = "true"; - pgRequest.pgStreams.pgStream.add(pgStream); - } - request.getPayload().put("pg-streams", pgRequest.pgStreams); - - /* - * Return the request - */ - - return request; - } + // Strings for targets + private static final String TARGET_VM = "VM"; + private static final String TARGET_VNF = "VNF"; + + // Strings for recipes + private static final String RECIPE_RESTART = "Restart"; + private static final String RECIPE_REBUILD = "Rebuild"; + private static final String RECIPE_MIGRATE = "Migrate"; + private static final String RECIPE_MODIFY = "ModifyConfig"; + + private static final ImmutableList recipes = + ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); + private static final ImmutableMap> targets = new ImmutableMap.Builder>() + .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM)) + .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build(); + private static final ImmutableMap> payloads = new ImmutableMap.Builder>() + .put(RECIPE_MODIFY, ImmutableList.of("generic-vnf.vnf-id")).build(); + + @Override + public String actor() { + return "APPC"; + } + + @Override + public List recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List recipePayloads(String recipe) { + return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList())); + } + + /** + * Constructs an APPC request conforming to the legacy API. The legacy API will be deprecated in + * future releases as all legacy functionality is moved into the LCM API. + * + * @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 the was specified from the yaml generated by CLAMP or through the + * Policy GUI/API + * @return an APPC request conforming to the legacy API + */ + public static Request constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy, + String targetVnf) { + /* + * Construct an APPC request + */ + Request request = new Request(); + request.setCommonHeader(new CommonHeader()); + request.getCommonHeader().setRequestID(onset.getRequestID()); + request.getCommonHeader().setSubRequestID(operation.getSubRequestId()); + request.setAction(policy.getRecipe().substring(0, 1).toUpperCase() + policy.getRecipe().substring(1)); + + /* + * For now Policy generates the PG Streams as a demo, in the future the payload can be + * provided by CLAMP + */ + request.getPayload().put("generic-vnf.vnf-id", targetVnf); + + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for (int i = 0; i < 5; i++) { + pgStream = new PGStream(); + pgStream.streamId = "fw_udp" + (i + 1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.getPayload().put("pg-streams", pgRequest.pgStreams); + + /* + * Return the request + */ + + return request; + } } diff --git a/controlloop/common/actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java b/controlloop/common/actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java index 58510ba8c..0670a2b15 100644 --- a/controlloop/common/actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java +++ b/controlloop/common/actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * AppcServiceProviderTest * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,7 +20,10 @@ package org.onap.policy.controlloop.actor.appc; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.time.Instant; import java.util.HashMap; @@ -49,15 +52,15 @@ import org.slf4j.LoggerFactory; public class AppcServiceProviderTest { private static final Logger logger = LoggerFactory.getLogger(AppcServiceProviderTest.class); - + private static VirtualControlLoopEvent onsetEvent; private static ControlLoopOperation operation; private static Policy policy; static { - /* - * Construct an onset with an AAI subtag containing - * generic-vnf.vnf-id and a target type of VM. + /* + * Construct an onset with an AAI subtag containing generic-vnf.vnf-id and a target type of + * VM. */ onsetEvent = new VirtualControlLoopEvent(); onsetEvent.setClosedLoopControlName("closedLoopControlName-Test"); @@ -90,14 +93,17 @@ public class AppcServiceProviderTest { policy.setPayload(null); policy.setRetry(2); policy.setTimeout(300); - + /* Set environment properties */ PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - + } + /** + * Set up before test class. + */ @BeforeClass public static void setUpSimulator() { try { @@ -107,17 +113,20 @@ public class AppcServiceProviderTest { } } + /** + * Tear down after test class. + */ @AfterClass public static void tearDownSimulator() { HttpServletServer.factory.destroy(); } - + @Test public void constructModifyConfigRequestTest() { - + Request appcRequest = null; appcRequest = APPCActorServiceProvider.constructRequest(onsetEvent, operation, policy, "vnf01"); - + /* The service provider must return a non null APPC request */ assertNotNull(appcRequest); @@ -136,11 +145,11 @@ public class AppcServiceProviderTest { assertTrue(appcRequest.getPayload().containsKey("pg-streams")); logger.debug("APPC Request: \n" + appcRequest.toString()); - + /* Print out request as json to make sure serialization works */ String jsonRequest = Serialization.gsonPretty.toJson(appcRequest); logger.debug("JSON Output: \n" + jsonRequest); - + /* The JSON string must contain the following fields */ assertTrue(jsonRequest.contains("commonHeader")); assertTrue(jsonRequest.contains("action")); @@ -148,7 +157,7 @@ public class AppcServiceProviderTest { assertTrue(jsonRequest.contains("payload")); assertTrue(jsonRequest.contains("generic-vnf.vnf-id")); assertTrue(jsonRequest.contains("pg-streams")); - + Response appcResponse = new Response(appcRequest); appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue()); appcResponse.getStatus().setDescription("AppC success"); @@ -159,11 +168,11 @@ public class AppcServiceProviderTest { @Test public void testMethods() { - APPCActorServiceProvider sp = new APPCActorServiceProvider(); - - assertEquals("APPC", sp.actor()); - assertEquals(4, sp.recipes().size()); - assertEquals("VM", sp.recipeTargets("Restart").get(0)); - assertEquals(0, sp.recipePayloads("Restart").size()); + APPCActorServiceProvider sp = new APPCActorServiceProvider(); + + assertEquals("APPC", sp.actor()); + assertEquals(4, sp.recipes().size()); + assertEquals("VM", sp.recipeTargets("Restart").get(0)); + assertEquals(0, sp.recipePayloads("Restart").size()); } } diff --git a/controlloop/common/actors/actor.appclcm/src/main/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProvider.java b/controlloop/common/actors/actor.appclcm/src/main/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProvider.java index 1635094f9..f2d0991e2 100644 --- a/controlloop/common/actors/actor.appclcm/src/main/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProvider.java +++ b/controlloop/common/actors/actor.appclcm/src/main/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * AppcLcmActorServiceProvider * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -31,9 +31,9 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import org.onap.policy.aai.AAIManager; import org.onap.policy.aai.AAINQInstanceFilters; import org.onap.policy.aai.AAINQInventoryResponseItem; -import org.onap.policy.aai.AAIManager; import org.onap.policy.aai.AAINQNamedQuery; import org.onap.policy.aai.AAINQQueryParameters; import org.onap.policy.aai.AAINQRequest; @@ -57,302 +57,284 @@ import org.slf4j.LoggerFactory; public class AppcLcmActorServiceProvider implements Actor { - private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class); - - /* To be used in future releases to restart a single vm */ - private static final String APPC_VM_ID = "vm-id"; - - // Strings for targets - private static final String TARGET_VM = "VM"; - private static final String TARGET_VNF = "VNF"; - - // Strings for recipes - private static final String RECIPE_RESTART = "Restart"; - private static final String RECIPE_REBUILD = "Rebuild"; - private static final String RECIPE_MIGRATE = "Migrate"; - private static final String RECIPE_MODIFY = "ConfigModify"; - - /* To be used in future releases when LCM ConfigModify is used */ - private static final String APPC_REQUEST_PARAMS = "request-parameters"; - private static final String APPC_CONFIG_PARAMS = "configuration-parameters"; - - private static final ImmutableList recipes = ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); - private static final ImmutableMap> targets = new ImmutableMap.Builder>() - .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM)) - .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build(); - private static final ImmutableMap> payloads = new ImmutableMap.Builder>() - .put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID)) - .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build(); - - @Override - public String actor() { - return "APPC"; - } - - @Override - public List recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List recipePayloads(String recipe) { - return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList())); - } - - /** - * This method recursively traverses the A&AI named query response - * to find the generic-vnf object that contains a model-invariant-id - * that matches the resourceId of the policy. Once this match is found - * the generic-vnf object's vnf-id is returned. - * - * @param items - * the list of items related to the vnf returned by A&AI - * @param resourceId - * the id of the target from the sdc catalog - * - * @return the vnf-id of the target vnf to act upon or null if not found - */ - private static String parseAAIResponse(List items, String resourceId) { - String vnfId = null; - for (AAINQInventoryResponseItem item: items) { - if ((item.getGenericVNF() != null) - && (item.getGenericVNF().getModelInvariantId() != null) - && (resourceId.equals(item.getGenericVNF().getModelInvariantId()))) { - vnfId = item.getGenericVNF().getVnfID(); - break; - } - else { - if((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) { - vnfId = parseAAIResponse(item.getItems().getInventoryResponseItems(), resourceId); - } - } - } - return vnfId; - } - - /** - * Constructs an A&AI Named Query using a source vnf-id to determine - * the vnf-id of the target entity specified in the policy to act upon. - * - * @param resourceId - * the id of the target from the sdc catalog - * - * @param sourceVnfId - * the vnf id of the source entity reporting the alert - * - * @return the target entities vnf id to act upon - * @throws AAIException - */ - public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AAIException { - - //TODO: This request id should not be hard coded in future releases - UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087"); - - AAINQRequest aaiRequest = new AAINQRequest(); - aaiRequest.setQueryParameters(new AAINQQueryParameters()); - aaiRequest.getQueryParameters().setNamedQuery(new AAINQNamedQuery()); - aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUUID(requestId); - - Map> filter = new HashMap<>(); - Map filterItem = new HashMap<>(); - - filterItem.put("vnf-id", sourceVnfId); - filter.put("generic-vnf", filterItem); - - aaiRequest.setInstanceFilters(new AAINQInstanceFilters()); - aaiRequest.getInstanceFilters().getInstanceFilter().add(filter); - - AAINQResponse aaiResponse = new AAIManager(new RESTManager()).postQuery( - getPEManagerEnvProperty("aai.url"), getPEManagerEnvProperty("aai.username"), getPEManagerEnvProperty("aai.password"), - aaiRequest, requestId); - - if (aaiResponse == null) { - throw new AAIException("The named query response was null"); - } - - String targetVnfId = parseAAIResponse(aaiResponse.getInventoryResponseItems(), resourceId); - if (targetVnfId == null) { - throw new AAIException("Target vnf-id could not be found"); - } - - return targetVnfId; - } - - /** - * Constructs an APPC request conforming to the lcm API. - * The actual request is constructed and then placed in a - * wrapper object used to send through DMAAP. - * - * @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 the was specified from the yaml generated - * by CLAMP or through the Policy GUI/API - * @return an APPC request conforming to the lcm API using the DMAAP wrapper - */ - public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, - ControlLoopOperation operation, Policy policy, String targetVnf) { - - /* Construct an APPC request using LCM Model */ - - /* - * The actual LCM request is placed in a wrapper used to send - * through dmaap. The current version is 2.0 as of R1. - */ - LCMRequestWrapper dmaapRequest = new LCMRequestWrapper(); - dmaapRequest.setVersion("2.0"); - dmaapRequest.setCorrelationId(onset.getRequestID() + "-" + operation.getSubRequestId()); - dmaapRequest.setRpcName(policy.getRecipe().toLowerCase()); - dmaapRequest.setType("request"); - - /* This is the actual request that is placed in the dmaap wrapper. */ - LCMRequest appcRequest = new LCMRequest(); - - /* The common header is a required field for all APPC requests. */ - LCMCommonHeader requestCommonHeader = new LCMCommonHeader(); - requestCommonHeader.setOriginatorId(onset.getRequestID().toString()); - requestCommonHeader.setRequestId(onset.getRequestID()); - requestCommonHeader.setSubRequestId(operation.getSubRequestId()); - - appcRequest.setCommonHeader(requestCommonHeader); - - /* - * Action Identifiers are required for APPC LCM requests. - * For R1, the recipes supported by Policy only require - * a vnf-id. - */ - HashMap requestActionIdentifiers = new HashMap<>(); - requestActionIdentifiers.put("vnf-id", targetVnf); - - appcRequest.setActionIdentifiers(requestActionIdentifiers); - - /* - * An action is required for all APPC requests, this will - * be the recipe specified in the policy. - */ - appcRequest.setAction(policy.getRecipe().substring(0, 1).toUpperCase() - + policy.getRecipe().substring(1).toLowerCase()); - - /* - * For R1, the payloads will not be required for the Restart, - * Rebuild, or Migrate recipes. APPC will populate the payload - * based on A&AI look up of the vnd-id provided in the action - * identifiers. - */ - if (RECIPE_RESTART.equalsIgnoreCase(policy.getRecipe()) || RECIPE_REBUILD.equalsIgnoreCase(policy.getRecipe()) - || RECIPE_MIGRATE.equalsIgnoreCase(policy.getRecipe())) { - appcRequest.setPayload(null); - } - - /* - * Once the LCM request is constructed, add it into the - * body of the dmaap wrapper. - */ - dmaapRequest.setBody(appcRequest); - - /* Return the request to be sent through dmaap. */ - return dmaapRequest; - } - - /** - * Parses the operation attempt using the subRequestId - * of APPC response. - * - * @param subRequestId - * the sub id used to send to APPC, Policy sets - * this using the operation attempt - * - * @return the current operation attempt - */ - public static Integer parseOperationAttempt(String subRequestId) { - Integer operationAttempt; - try { - operationAttempt = Integer.parseInt(subRequestId); - } catch (NumberFormatException e) { - logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt"); - return null; - } - return operationAttempt; - } - - /** - * Processes the APPC LCM response sent from APPC. Determines - * if the APPC operation was successful/unsuccessful and maps - * this to the corresponding Policy result. - * - * @param dmaapResponse - * the dmaap wrapper message that contains the - * actual APPC reponse inside the body field - * - * @return an key-value pair that contains the Policy result - * and APPC response message - */ - public static SimpleEntry processResponse(LCMResponseWrapper dmaapResponse) { - /* The actual APPC response is inside the wrapper's body field. */ - LCMResponse appcResponse = dmaapResponse.getBody(); - - /* The message returned in the APPC response. */ - String message; - - /* The Policy result determined from the APPC Response. */ - PolicyResult result; - - /* If there is no status, Policy cannot determine if the request was successful. */ - if (appcResponse.getStatus() == null) { - message = "Policy was unable to parse APP-C response status field (it was null)."; - return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message); - } - - /* If there is no code, Policy cannot determine if the request was successful. */ - String responseValue = LCMResponseCode.toResponseValue(appcResponse.getStatus().getCode()); - if (responseValue == null) { - message = "Policy was unable to parse APP-C response status code field."; - return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message); - } - - /* Save the APPC response's message for Policy noticiation message. */ - message = appcResponse.getStatus().getMessage(); - - /* Maps the APPC response result to a Policy result. */ - switch (responseValue) { - case LCMResponseCode.ACCEPTED: - /* Nothing to do if code is accept, continue processing */ - result = null; - break; - case LCMResponseCode.SUCCESS: - result = PolicyResult.SUCCESS; - break; - case LCMResponseCode.FAILURE: - result = PolicyResult.FAILURE; - break; - case LCMResponseCode.REJECT: - case LCMResponseCode.ERROR: - default: - result = PolicyResult.FAILURE_EXCEPTION; - } - return new AbstractMap.SimpleEntry<>(result, message); - } - - /** - * This method reads and validates environmental properties coming from the policy engine. Null properties cause - * an {@link IllegalArgumentException} runtime exception to be thrown - * @param string the name of the parameter to retrieve - * @return the property value - */ - private static String getPEManagerEnvProperty(String enginePropertyName) { - String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName); - if (enginePropertyValue == null) { - throw new IllegalArgumentException("The value of policy engine manager environment property \"" + enginePropertyName + "\" may not be null"); - } - return enginePropertyValue; - } + private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class); + + /* To be used in future releases to restart a single vm */ + private static final String APPC_VM_ID = "vm-id"; + + // Strings for targets + private static final String TARGET_VM = "VM"; + private static final String TARGET_VNF = "VNF"; + + // Strings for recipes + private static final String RECIPE_RESTART = "Restart"; + private static final String RECIPE_REBUILD = "Rebuild"; + private static final String RECIPE_MIGRATE = "Migrate"; + private static final String RECIPE_MODIFY = "ConfigModify"; + + /* To be used in future releases when LCM ConfigModify is used */ + private static final String APPC_REQUEST_PARAMS = "request-parameters"; + private static final String APPC_CONFIG_PARAMS = "configuration-parameters"; + + private static final ImmutableList recipes = + ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); + private static final ImmutableMap> targets = new ImmutableMap.Builder>() + .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM)) + .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build(); + private static final ImmutableMap> payloads = + new ImmutableMap.Builder>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID)) + .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build(); + + @Override + public String actor() { + return "APPC"; + } + + @Override + public List recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List recipePayloads(String recipe) { + return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList())); + } + + /** + * This method recursively traverses the A&AI named query response to find the generic-vnf + * object that contains a model-invariant-id that matches the resourceId of the policy. Once + * this match is found the generic-vnf object's vnf-id is returned. + * + * @param items the list of items related to the vnf returned by A&AI + * @param resourceId the id of the target from the sdc catalog + * + * @return the vnf-id of the target vnf to act upon or null if not found + */ + private static String parseAaiResponse(List items, String resourceId) { + String vnfId = null; + for (AAINQInventoryResponseItem item : items) { + if ((item.getGenericVNF() != null) && (item.getGenericVNF().getModelInvariantId() != null) + && (resourceId.equals(item.getGenericVNF().getModelInvariantId()))) { + vnfId = item.getGenericVNF().getVnfID(); + break; + } else { + if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) { + vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId); + } + } + } + return vnfId; + } + + /** + * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target + * entity specified in the policy to act upon. + * + * @param resourceId the id of the target from the sdc catalog + * + * @param sourceVnfId the vnf id of the source entity reporting the alert + * + * @return the target entities vnf id to act upon + * @throws AAIException it an error occurs + */ + public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AAIException { + + // TODO: This request id should not be hard coded in future releases + UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087"); + + AAINQRequest aaiRequest = new AAINQRequest(); + aaiRequest.setQueryParameters(new AAINQQueryParameters()); + aaiRequest.getQueryParameters().setNamedQuery(new AAINQNamedQuery()); + aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUUID(requestId); + + Map> filter = new HashMap<>(); + Map filterItem = new HashMap<>(); + + filterItem.put("vnf-id", sourceVnfId); + filter.put("generic-vnf", filterItem); + + aaiRequest.setInstanceFilters(new AAINQInstanceFilters()); + aaiRequest.getInstanceFilters().getInstanceFilter().add(filter); + + AAINQResponse aaiResponse = new AAIManager(new RESTManager()).postQuery(getPeManagerEnvProperty("aai.url"), + getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiRequest, + requestId); + + if (aaiResponse == null) { + throw new AAIException("The named query response was null"); + } + + String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId); + if (targetVnfId == null) { + throw new AAIException("Target vnf-id could not be found"); + } + + return targetVnfId; + } + + /** + * Constructs an APPC request conforming to the lcm API. The actual request is constructed and + * then placed in a wrapper object used to send through DMAAP. + * + * @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 the was specified from the yaml generated by CLAMP or through the + * Policy GUI/API + * @return an APPC request conforming to the lcm API using the DMAAP wrapper + */ + public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, + Policy policy, String targetVnf) { + + /* Construct an APPC request using LCM Model */ + + /* + * The actual LCM request is placed in a wrapper used to send through dmaap. The current + * version is 2.0 as of R1. + */ + LCMRequestWrapper dmaapRequest = new LCMRequestWrapper(); + dmaapRequest.setVersion("2.0"); + dmaapRequest.setCorrelationId(onset.getRequestID() + "-" + operation.getSubRequestId()); + dmaapRequest.setRpcName(policy.getRecipe().toLowerCase()); + dmaapRequest.setType("request"); + + /* This is the actual request that is placed in the dmaap wrapper. */ + final LCMRequest appcRequest = new LCMRequest(); + + /* The common header is a required field for all APPC requests. */ + LCMCommonHeader requestCommonHeader = new LCMCommonHeader(); + requestCommonHeader.setOriginatorId(onset.getRequestID().toString()); + requestCommonHeader.setRequestId(onset.getRequestID()); + requestCommonHeader.setSubRequestId(operation.getSubRequestId()); + + appcRequest.setCommonHeader(requestCommonHeader); + + /* + * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by + * Policy only require a vnf-id. + */ + HashMap requestActionIdentifiers = new HashMap<>(); + requestActionIdentifiers.put("vnf-id", targetVnf); + + appcRequest.setActionIdentifiers(requestActionIdentifiers); + + /* + * An action is required for all APPC requests, this will be the recipe specified in the + * policy. + */ + appcRequest.setAction( + policy.getRecipe().substring(0, 1).toUpperCase() + policy.getRecipe().substring(1).toLowerCase()); + + /* + * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes. + * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action + * identifiers. + */ + if (RECIPE_RESTART.equalsIgnoreCase(policy.getRecipe()) || RECIPE_REBUILD.equalsIgnoreCase(policy.getRecipe()) + || RECIPE_MIGRATE.equalsIgnoreCase(policy.getRecipe())) { + appcRequest.setPayload(null); + } + + /* + * Once the LCM request is constructed, add it into the body of the dmaap wrapper. + */ + dmaapRequest.setBody(appcRequest); + + /* Return the request to be sent through dmaap. */ + return dmaapRequest; + } + + /** + * Parses the operation attempt using the subRequestId of APPC response. + * + * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation + * attempt + * + * @return the current operation attempt + */ + public static Integer parseOperationAttempt(String subRequestId) { + Integer operationAttempt; + try { + operationAttempt = Integer.parseInt(subRequestId); + } catch (NumberFormatException e) { + logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt"); + return null; + } + return operationAttempt; + } + + /** + * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was + * successful/unsuccessful and maps this to the corresponding Policy result. + * + * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside + * the body field + * + * @return an key-value pair that contains the Policy result and APPC response message + */ + public static SimpleEntry processResponse(LCMResponseWrapper dmaapResponse) { + /* The actual APPC response is inside the wrapper's body field. */ + LCMResponse appcResponse = dmaapResponse.getBody(); + + /* The message returned in the APPC response. */ + String message; + + /* The Policy result determined from the APPC Response. */ + PolicyResult result; + + /* If there is no status, Policy cannot determine if the request was successful. */ + if (appcResponse.getStatus() == null) { + message = "Policy was unable to parse APP-C response status field (it was null)."; + return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message); + } + + /* If there is no code, Policy cannot determine if the request was successful. */ + String responseValue = LCMResponseCode.toResponseValue(appcResponse.getStatus().getCode()); + if (responseValue == null) { + message = "Policy was unable to parse APP-C response status code field."; + return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message); + } + + /* Save the APPC response's message for Policy noticiation message. */ + message = appcResponse.getStatus().getMessage(); + + /* Maps the APPC response result to a Policy result. */ + switch (responseValue) { + case LCMResponseCode.ACCEPTED: + /* Nothing to do if code is accept, continue processing */ + result = null; + break; + case LCMResponseCode.SUCCESS: + result = PolicyResult.SUCCESS; + break; + case LCMResponseCode.FAILURE: + result = PolicyResult.FAILURE; + break; + case LCMResponseCode.REJECT: + case LCMResponseCode.ERROR: + default: + result = PolicyResult.FAILURE_EXCEPTION; + } + return new AbstractMap.SimpleEntry<>(result, message); + } + + /** + * This method reads and validates environmental properties coming from the policy engine. Null + * properties cause an {@link IllegalArgumentException} runtime exception to be thrown + * + * @param string the name of the parameter to retrieve + * @return the property value + */ + private static String getPeManagerEnvProperty(String enginePropertyName) { + String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName); + if (enginePropertyValue == null) { + throw new IllegalArgumentException("The value of policy engine manager environment property \"" + + enginePropertyName + "\" may not be null"); + } + return enginePropertyValue; + } } diff --git a/controlloop/common/actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmServiceProviderTest.java b/controlloop/common/actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmServiceProviderTest.java index cf5360202..50b03c6b4 100644 --- a/controlloop/common/actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmServiceProviderTest.java +++ b/controlloop/common/actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmServiceProviderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * AppcServiceProviderTest * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,7 +20,9 @@ package org.onap.policy.controlloop.actor.appclcm; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import java.time.Instant; import java.util.AbstractMap; @@ -51,9 +53,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AppcLcmServiceProviderTest { - + private static final Logger logger = LoggerFactory.getLogger(AppcLcmServiceProviderTest.class); - + private static VirtualControlLoopEvent onsetEvent; private static ControlLoopOperation operation; private static Policy policy; @@ -61,9 +63,9 @@ public class AppcLcmServiceProviderTest { private static LCMResponseWrapper dmaapResponse; static { - /* - * Construct an onset with an AAI subtag containing - * generic-vnf.vnf-id and a target type of VM. + /* + * Construct an onset with an AAI subtag containing generic-vnf.vnf-id and a target type of + * VM. */ onsetEvent = new VirtualControlLoopEvent(); onsetEvent.setClosedLoopControlName("closedLoopControlName-Test"); @@ -84,7 +86,7 @@ public class AppcLcmServiceProviderTest { operation.setTarget("VM"); operation.setEnd(Instant.now()); operation.setSubRequestId("1"); - + /* Construct a policy specifying to restart vm. */ policy = new Policy(); policy.setName("Restart the VM"); @@ -107,30 +109,30 @@ public class AppcLcmServiceProviderTest { dmaapResponse.setCorrelationId(onsetEvent.getRequestID().toString() + "-" + "1"); dmaapResponse.setRpcName(policy.getRecipe().toLowerCase()); dmaapResponse.setType("response"); - + /* Set environment properties */ PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - + /* A sample APPC LCM request. */ LCMRequest appcRequest = new LCMRequest(); - + /* The following code constructs a sample APPC LCM Request */ appcRequest.setAction("restart"); - + HashMap actionIdentifiers = new HashMap<>(); actionIdentifiers.put("vnf-id", "trial-vnf-003"); - + appcRequest.setActionIdentifiers(actionIdentifiers); - + LCMCommonHeader commonHeader = new LCMCommonHeader(); commonHeader.setRequestId(onsetEvent.getRequestID()); commonHeader.setSubRequestId("1"); commonHeader.setOriginatorId(onsetEvent.getRequestID().toString()); - + appcRequest.setCommonHeader(commonHeader); - + appcRequest.setPayload(null); dmaapRequest.setBody(appcRequest); @@ -142,7 +144,10 @@ public class AppcLcmServiceProviderTest { dmaapResponse.setBody(appcResponse); } - + + /** + * Set up before test class. + */ @BeforeClass public static void setUpSimulator() { try { @@ -152,30 +157,34 @@ public class AppcLcmServiceProviderTest { } } + /** + * Tear down after test class. + */ @AfterClass public static void tearDownSimulator() { HttpServletServer.factory.destroy(); } - + /** * A test to construct an APPC LCM restart request. */ @Test public void constructRestartRequestTest() { - - LCMRequestWrapper dmaapRequest = AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, policy, "vnf01"); + + LCMRequestWrapper dmaapRequest = + AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, policy, "vnf01"); /* The service provider must return a non null DMAAP request wrapper */ assertNotNull(dmaapRequest); /* The DMAAP wrapper's type field must be request */ assertEquals("request", dmaapRequest.getType()); - + /* The DMAAP wrapper's body field cannot be null */ assertNotNull(dmaapRequest.getBody()); LCMRequest appcRequest = dmaapRequest.getBody(); - + /* A common header is required and cannot be null */ assertNotNull(appcRequest.getCommonHeader()); assertEquals(appcRequest.getCommonHeader().getRequestId(), onsetEvent.getRequestID()); @@ -188,7 +197,7 @@ public class AppcLcmServiceProviderTest { assertNotNull(appcRequest.getActionIdentifiers()); assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id")); assertEquals("vnf01", appcRequest.getActionIdentifiers().get("vnf-id")); - + logger.debug("APPC Request: \n" + appcRequest.toString()); } @@ -197,106 +206,105 @@ public class AppcLcmServiceProviderTest { */ @Test public void processRestartResponseSuccessTest() { - AbstractMap.SimpleEntry result = AppcLcmActorServiceProvider - .processResponse(dmaapResponse); + AbstractMap.SimpleEntry result = + AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.SUCCESS, result.getKey()); assertEquals("Restart Successful", result.getValue()); } - + /** - * A test to map APPC response results to corresponding Policy results + * A test to map APPC response results to corresponding Policy results. */ @Test public void appcToPolicyResultTest() { - + AbstractMap.SimpleEntry result; - + /* If APPC accepts, PolicyResult is null */ dmaapResponse.getBody().getStatus().setCode(100); dmaapResponse.getBody().getStatus().setMessage("ACCEPTED"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(null, result.getKey()); - + /* If APPC is successful, PolicyResult is success */ dmaapResponse.getBody().getStatus().setCode(400); dmaapResponse.getBody().getStatus().setMessage("SUCCESS"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.SUCCESS, result.getKey()); - + /* If APPC returns an error, PolicyResult is failure exception */ dmaapResponse.getBody().getStatus().setCode(200); dmaapResponse.getBody().getStatus().setMessage("ERROR"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* If APPC rejects, PolicyResult is failure exception */ dmaapResponse.getBody().getStatus().setCode(300); dmaapResponse.getBody().getStatus().setMessage("REJECT"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* Test multiple reject codes */ dmaapResponse.getBody().getStatus().setCode(306); dmaapResponse.getBody().getStatus().setMessage("REJECT"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + dmaapResponse.getBody().getStatus().setCode(313); dmaapResponse.getBody().getStatus().setMessage("REJECT"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* If APPC returns failure, PolicyResult is failure */ dmaapResponse.getBody().getStatus().setCode(401); dmaapResponse.getBody().getStatus().setMessage("FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE, result.getKey()); - + /* Test multiple failure codes */ dmaapResponse.getBody().getStatus().setCode(406); dmaapResponse.getBody().getStatus().setMessage("FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE, result.getKey()); - + dmaapResponse.getBody().getStatus().setCode(450); dmaapResponse.getBody().getStatus().setMessage("FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE, result.getKey()); - + /* If APPC returns partial success, PolicyResult is failure exception */ dmaapResponse.getBody().getStatus().setCode(500); dmaapResponse.getBody().getStatus().setMessage("PARTIAL SUCCESS"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* If APPC returns partial failure, PolicyResult is failure exception */ dmaapResponse.getBody().getStatus().setCode(501); dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* Test multiple partial failure codes */ dmaapResponse.getBody().getStatus().setCode(599); dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + dmaapResponse.getBody().getStatus().setCode(550); dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); - + /* If APPC code is unknown to Policy, PolicyResult is failure exception */ dmaapResponse.getBody().getStatus().setCode(700); dmaapResponse.getBody().getStatus().setMessage("UNKNOWN"); result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey()); } - + /** - * This test ensures that that if the the source entity - * is also the target entity, the source will be used for - * the APPC request + * This test ensures that that if the the source entity is also the target entity, the source + * will be used for the APPC request. */ @Test public void sourceIsTargetTest() { @@ -311,17 +319,17 @@ public class AppcLcmServiceProviderTest { assertNotNull(targetVnfId); assertEquals("vnf01", targetVnfId); } - + /** - * THis test exercises getters not exercised in other tests + * THis test exercises getters not exercised in other tests. */ @Test public void testMethods() { - AppcLcmActorServiceProvider sp = new AppcLcmActorServiceProvider(); - - assertEquals("APPC", sp.actor()); - assertEquals(4, sp.recipes().size()); - assertEquals("VM", sp.recipeTargets("Restart").get(0)); - assertEquals("vm-id", sp.recipePayloads("Restart").get(0)); + AppcLcmActorServiceProvider sp = new AppcLcmActorServiceProvider(); + + assertEquals("APPC", sp.actor()); + assertEquals(4, sp.recipes().size()); + assertEquals("VM", sp.recipeTargets("Restart").get(0)); + assertEquals("vm-id", sp.recipePayloads("Restart").get(0)); } } diff --git a/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java b/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java index 69a266e6b..738cf3d04 100644 --- a/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java +++ b/controlloop/common/actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SOActorServiceProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * SOActorServiceProvider * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,6 +20,9 @@ package org.onap.policy.controlloop.actor.so; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -28,7 +31,6 @@ import java.util.UUID; import org.drools.core.WorkingMemory; import org.onap.policy.aai.AAIManager; -import org.onap.policy.aai.AAINQExtraProperties; import org.onap.policy.aai.AAINQExtraProperty; import org.onap.policy.aai.AAINQInstanceFilters; import org.onap.policy.aai.AAINQInventoryResponseItem; @@ -56,358 +58,365 @@ import org.onap.policy.so.util.Serialization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - public class SOActorServiceProvider implements Actor { - private static final Logger logger = LoggerFactory.getLogger(SOActorServiceProvider.class); - - // Strings for SO Actor - private static final String SO_ACTOR = "SO"; - - // Strings for targets - private static final String TARGET_VFC = "VFC"; - - // Strings for recipes - private static final String RECIPE_VF_MODULE_CREATE = "VF Module Create"; - - private static final ImmutableList recipes = ImmutableList.of(RECIPE_VF_MODULE_CREATE); - private static final ImmutableMap> targets = new ImmutableMap.Builder>() - .put(RECIPE_VF_MODULE_CREATE, ImmutableList.of(TARGET_VFC)) - .build(); - - // Static variables required to hold the IDs of the last service item and VNF item. Note that in a multithreaded deployment this WILL break - private static String lastVNFItemVnfId; - private static String lastServiceItemServiceInstanceId; - - @Override - public String actor() { - return SO_ACTOR; - } - - @Override - public List recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List recipePayloads(String recipe) { - return Collections.emptyList(); - } - - /** - * Constructs a SO request conforming to the lcm API. - * The actual request is constructed and then placed in a - * wrapper object used to send through DMAAP. - * - * @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 the was specified from the yaml generated - * by CLAMP or through the Policy GUI/API - * @return a SO request conforming to the lcm API using the DMAAP wrapper - */ - public SORequest constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy) { - String modelNamePropertyKey = "model-ver.model-name"; - String modelVersionPropertyKey = "model-ver.model-version"; - String modelVersionIdPropertyKey = "model-ver.model-version-id"; - - - if (!SO_ACTOR.equals(policy.getActor()) || !RECIPE_VF_MODULE_CREATE.equals(policy.getRecipe())) { - // for future extension - return null; - } - - // Perform named query request and handle response - AAINQResponseWrapper aaiResponseWrapper = performAaiNamedQueryRequest(onset); - if (aaiResponseWrapper == null) { - // Tracing and error handling handied in the "performAaiNamedQueryRequest()" method - return null; - } - - AAINQInventoryResponseItem vnfItem; - AAINQInventoryResponseItem vnfServiceItem; - AAINQInventoryResponseItem tenantItem; - - // Extract the items we're interested in from the response - try { - vnfItem = aaiResponseWrapper.getAainqresponse().getInventoryResponseItems().get(0).getItems().getInventoryResponseItems().get(0); - } - catch (Exception e) { - logger.error("VNF Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiResponseWrapper), e); - return null; - } - - try { - vnfServiceItem = vnfItem.getItems().getInventoryResponseItems().get(0); - } - catch (Exception e) { - logger.error("VNF Service Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiResponseWrapper), e); - return null; - } - - try { - tenantItem = aaiResponseWrapper.getAainqresponse().getInventoryResponseItems().get(0).getItems().getInventoryResponseItems().get(1); - } - catch (Exception e) { - logger.error("Tenant Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiResponseWrapper), e); - return null; - } - - // Find the index for base vf module and non-base vf module - int baseIndex = findIndex(vnfItem.getItems().getInventoryResponseItems(), true); - int nonBaseIndex = findIndex(vnfItem.getItems().getInventoryResponseItems(), false); - - // Report the error if either base vf module or non-base vf module is not found - if (baseIndex == -1 || nonBaseIndex == -1) { - logger.error("Either base or non-base vf module is not found from AAI response."); - return null; - } - - - // Construct SO Request - SORequest request = new SORequest(); - request.setRequestId(onset.getRequestID()); - request.setRequestDetails(new SORequestDetails()); - request.getRequestDetails().setModelInfo(new SOModelInfo()); - request.getRequestDetails().setCloudConfiguration(new SOCloudConfiguration()); - request.getRequestDetails().setRequestInfo(new SORequestInfo()); - request.getRequestDetails().setRequestParameters(new SORequestParameters()); - request.getRequestDetails().getRequestParameters().setUserParams(null); - - // - // cloudConfiguration - // - request.getRequestDetails().getCloudConfiguration().setTenantId(tenantItem.getTenant().getTenantId()); - request.getRequestDetails().getCloudConfiguration().setLcpCloudRegionId(tenantItem.getItems().getInventoryResponseItems().get(0).getCloudRegion().getCloudRegionId()); - - // - // modelInfo - // - AAINQInventoryResponseItem vfModuleItem = vnfItem.getItems().getInventoryResponseItems().get(nonBaseIndex); - - request.getRequestDetails().getModelInfo().setModelType("vfModule"); - request.getRequestDetails().getModelInfo().setModelInvariantId(vfModuleItem.getVfModule().getModelInvariantId()); - request.getRequestDetails().getModelInfo().setModelVersionId(vfModuleItem.getVfModule().getModelVersionId()); - - for (AAINQExtraProperty prop : vfModuleItem.getExtraProperties().getExtraProperty()) { - if (prop.getPropertyName().equals(modelNamePropertyKey)) { - request.getRequestDetails().getModelInfo().setModelName(prop.getPropertyValue()); - } - else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { - request.getRequestDetails().getModelInfo().setModelVersion(prop.getPropertyValue()); - } - } - - // - // requestInfo - // - String instanceName = vnfItem.getItems().getInventoryResponseItems().get(baseIndex).getVfModule() - .getVfModuleName().replace("Vfmodule", "vDNS"); - int numberOfNonBaseModules = findNonBaseModules(vnfItem.getItems().getInventoryResponseItems()); - // Code to create unique VF Module names across the invocations. - if (numberOfNonBaseModules == 1) { - int instanceNumber = 1; - instanceName = instanceName.concat("-").concat(String.valueOf(instanceNumber)); - request.getRequestDetails().getRequestInfo().setInstanceName(instanceName); - } else if (numberOfNonBaseModules > 1) { - int instanceNumber = numberOfNonBaseModules + 1; - instanceName = instanceName.concat("-").concat(String.valueOf(instanceNumber)); - request.getRequestDetails().getRequestInfo().setInstanceName(instanceName); - } else { - request.getRequestDetails().getRequestInfo().setInstanceName(vnfItem.getItems().getInventoryResponseItems() - .get(baseIndex).getVfModule().getVfModuleName().replace("Vfmodule", "vDNS")); - } - request.getRequestDetails().getRequestInfo().setSource("POLICY"); - request.getRequestDetails().getRequestInfo().setSuppressRollback(false); - request.getRequestDetails().getRequestInfo().setRequestorId("policy"); - - // - // relatedInstanceList - // - SORelatedInstanceListElement relatedInstanceListElement1 = new SORelatedInstanceListElement(); - SORelatedInstanceListElement relatedInstanceListElement2 = new SORelatedInstanceListElement(); - relatedInstanceListElement1.setRelatedInstance(new SORelatedInstance()); - relatedInstanceListElement2.setRelatedInstance(new SORelatedInstance()); - - // Service Item - relatedInstanceListElement1.getRelatedInstance().setInstanceId(vnfServiceItem.getServiceInstance().getServiceInstanceID()); - relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SOModelInfo()); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service"); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelInvariantId(vnfServiceItem.getServiceInstance().getModelInvariantId()); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersionId(vnfServiceItem.getServiceInstance().getModelVersionId()); - for (AAINQExtraProperty prop : vnfServiceItem.getExtraProperties().getExtraProperty()) { - if (prop.getPropertyName().equals(modelNamePropertyKey)) { - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue()); - } - else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersion(prop.getPropertyValue()); - } - } - - // VNF Item - relatedInstanceListElement2.getRelatedInstance().setInstanceId(vnfItem.getGenericVNF().getVnfID()); - relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SOModelInfo()); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelInvariantId(vnfItem.getGenericVNF().getModelInvariantId()); - for (AAINQExtraProperty prop : vnfItem.getExtraProperties().getExtraProperty()) { - if (prop.getPropertyName().equals(modelNamePropertyKey)) { - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue()); - } - else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersion(prop.getPropertyValue()); - } - else if (prop.getPropertyName().equals(modelVersionIdPropertyKey)) { - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersionId(prop.getPropertyValue()); - } - } - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelCustomizationName(vnfItem.getGenericVNF().getVnfType().substring(vnfItem.getGenericVNF().getVnfType().lastIndexOf('/') + 1)); - - // Insert the Service Item and VNF Item - request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1); - request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2); - - // Save the instance IDs for the VNF and service to static fields - preserveInstanceIDs(vnfItem.getGenericVNF().getVnfID(), vnfServiceItem.getServiceInstance().getServiceInstanceID()); - - if (logger.isDebugEnabled()) { - logger.debug("SO request sent: {}", Serialization.gsonPretty.toJson(request)); - } - - return request; - } - - /** - * This method is needed to get the serviceInstanceId and vnfInstanceId which is used - * in the asyncSORestCall - * - * @param wm - * @param request - */ - public static void sendRequest(String requestID, WorkingMemory wm, Object request) { - SOManager soManager = new SOManager(); - soManager.asyncSORestCall(requestID, wm, lastServiceItemServiceInstanceId, lastVNFItemVnfId, (SORequest)request); - } - - /** - * Constructs and sends an AAI vserver Named Query - * - * @param onset - * @returns the response to the AAI Named Query - */ - private AAINQResponseWrapper performAaiNamedQueryRequest(VirtualControlLoopEvent onset) { - - // create AAI named-query request with UUID started with "" - AAINQRequest aainqrequest = new AAINQRequest(); - AAINQQueryParameters aainqqueryparam = new AAINQQueryParameters(); - AAINQNamedQuery aainqnamedquery = new AAINQNamedQuery(); - AAINQInstanceFilters aainqinstancefilter = new AAINQInstanceFilters(); - - // queryParameters - aainqnamedquery.setNamedQueryUUID(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469")); // UUID.fromString($params.getAaiNamedQueryUUID()) TO DO: AaiNamedQueryUUID - aainqqueryparam.setNamedQuery(aainqnamedquery); - aainqrequest.setQueryParameters(aainqqueryparam); - // - // instanceFilters - // - Map> aainqinstancefiltermap = new HashMap<>(); - Map aainqinstancefiltermapitem = new HashMap<>(); - aainqinstancefiltermapitem.put("vserver-name", onset.getAAI().get("vserver.vserver-name")); // TO DO: get vserver.vname from dcae onset.AAI.get("vserver.vserver-name") - aainqinstancefiltermap.put("vserver", aainqinstancefiltermapitem); - aainqinstancefilter.getInstanceFilter().add(aainqinstancefiltermap); - aainqrequest.setInstanceFilters(aainqinstancefilter); - - if (logger.isDebugEnabled()) { - logger.debug("AAI Request sent: {}", Serialization.gsonPretty.toJson(aainqrequest)); - } - - AAINQResponse aainqresponse = new AAIManager(new RESTManager()).postQuery( - getPEManagerEnvProperty("aai.url"), - getPEManagerEnvProperty("aai.username"), - getPEManagerEnvProperty("aai.password"), - aainqrequest, onset.getRequestID()); - - // Check AAI response - if (aainqresponse == null) { - logger.warn("No response received from AAI for request {}", aainqrequest); - return null; - } - - // Create AAINQResponseWrapper - AAINQResponseWrapper aainqResponseWrapper = new AAINQResponseWrapper(onset.getRequestID(), aainqresponse); - - if (logger.isDebugEnabled()) { - logger.debug("AAI Named Query Response: "); - logger.debug(Serialization.gsonPretty.toJson(aainqResponseWrapper.getAainqresponse())); - } - - return aainqResponseWrapper; - } - - /** - * Find the base index or non base index in a list of inventory response items - * @param inventoryResponseItems - * @param baseIndexFlag true if we are searching for the base index, false if we are searching for hte non base index - * @return the base or non base index or -1 if the index was not found - */ - private int findIndex(List inventoryResponseItems, boolean baseIndexFlag) { - for (AAINQInventoryResponseItem invenoryResponseItem : inventoryResponseItems) { - if (invenoryResponseItem.getVfModule() != null && baseIndexFlag == invenoryResponseItem.getVfModule().getIsBaseVfModule()) { - return inventoryResponseItems.indexOf(invenoryResponseItem); - } - } - - return -1; - } - - /** - * Find the number of non base modules present in API response object. - * - * @param inventoryResponseItems - * @return number of non base index modules - */ - - private int findNonBaseModules(List inventoryResponseItems) { - int nonBaseModuleCount = 0; - for (AAINQInventoryResponseItem invenoryResponseItem : inventoryResponseItems) { - if (invenoryResponseItem.getVfModule() != null - && (!invenoryResponseItem.getVfModule().getIsBaseVfModule())) { - nonBaseModuleCount++; - } - } - return nonBaseModuleCount; - } - - /** - * This method is called to remember the last service instance ID and VNF Item VNF ID. Note these fields are static, beware for multithreaded deployments - * @param vnfInstanceID update the last VNF instance ID to this value - * @param serviceInstanceID update the last service instance ID to this value - */ - private static void preserveInstanceIDs(final String vnfInstanceID, final String serviceInstanceID) { - lastVNFItemVnfId = vnfInstanceID; - lastServiceItemServiceInstanceId = serviceInstanceID; - } - - /** - * This method reads and validates environmental properties coming from the policy engine. Null properties cause - * an {@link IllegalArgumentException} runtime exception to be thrown - * @param string the name of the parameter to retrieve - * @return the property value - */ - private static String getPEManagerEnvProperty(String enginePropertyName) { - String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName); - if (enginePropertyValue == null) { - throw new IllegalArgumentException("The value of policy engine manager environment property \"" + enginePropertyName + "\" may not be null"); - } - return enginePropertyValue; - } + private static final Logger logger = LoggerFactory.getLogger(SOActorServiceProvider.class); + + // Strings for SO Actor + private static final String SO_ACTOR = "SO"; + + // Strings for targets + private static final String TARGET_VFC = "VFC"; + + // Strings for recipes + private static final String RECIPE_VF_MODULE_CREATE = "VF Module Create"; + + private static final ImmutableList recipes = ImmutableList.of(RECIPE_VF_MODULE_CREATE); + private static final ImmutableMap> targets = new ImmutableMap.Builder>() + .put(RECIPE_VF_MODULE_CREATE, ImmutableList.of(TARGET_VFC)).build(); + + // Static variables required to hold the IDs of the last service item and VNF item. Note that in + // a multithreaded deployment this WILL break + private static String lastVNFItemVnfId; + private static String lastServiceItemServiceInstanceId; + + @Override + public String actor() { + return SO_ACTOR; + } + + @Override + public List recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List recipePayloads(String recipe) { + return Collections.emptyList(); + } + + /** + * Constructs a SO request conforming to the lcm API. The actual request is constructed and then + * placed in a wrapper object used to send through DMAAP. + * + * @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 the was specified from the yaml generated by CLAMP or through the + * Policy GUI/API + * @return a SO request conforming to the lcm API using the DMAAP wrapper + */ + public SORequest constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy) { + String modelNamePropertyKey = "model-ver.model-name"; + String modelVersionPropertyKey = "model-ver.model-version"; + String modelVersionIdPropertyKey = "model-ver.model-version-id"; + + + if (!SO_ACTOR.equals(policy.getActor()) || !RECIPE_VF_MODULE_CREATE.equals(policy.getRecipe())) { + // for future extension + return null; + } + + // Perform named query request and handle response + AAINQResponseWrapper aaiResponseWrapper = performAaiNamedQueryRequest(onset); + if (aaiResponseWrapper == null) { + // Tracing and error handling handied in the "performAaiNamedQueryRequest()" method + return null; + } + + AAINQInventoryResponseItem vnfItem; + AAINQInventoryResponseItem vnfServiceItem; + AAINQInventoryResponseItem tenantItem; + + // Extract the items we're interested in from the response + try { + vnfItem = aaiResponseWrapper.getAainqresponse().getInventoryResponseItems().get(0).getItems() + .getInventoryResponseItems().get(0); + } catch (Exception e) { + logger.error("VNF Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiResponseWrapper), + e); + return null; + } + + try { + vnfServiceItem = vnfItem.getItems().getInventoryResponseItems().get(0); + } catch (Exception e) { + logger.error("VNF Service Item not found in AAI response {}", + Serialization.gsonPretty.toJson(aaiResponseWrapper), e); + return null; + } + + try { + tenantItem = aaiResponseWrapper.getAainqresponse().getInventoryResponseItems().get(0).getItems() + .getInventoryResponseItems().get(1); + } catch (Exception e) { + logger.error("Tenant Item not found in AAI response {}", + Serialization.gsonPretty.toJson(aaiResponseWrapper), e); + return null; + } + + // Find the index for base vf module and non-base vf module + int baseIndex = findIndex(vnfItem.getItems().getInventoryResponseItems(), true); + int nonBaseIndex = findIndex(vnfItem.getItems().getInventoryResponseItems(), false); + + // Report the error if either base vf module or non-base vf module is not found + if (baseIndex == -1 || nonBaseIndex == -1) { + logger.error("Either base or non-base vf module is not found from AAI response."); + return null; + } + + + // Construct SO Request + SORequest request = new SORequest(); + request.setRequestId(onset.getRequestID()); + request.setRequestDetails(new SORequestDetails()); + request.getRequestDetails().setModelInfo(new SOModelInfo()); + request.getRequestDetails().setCloudConfiguration(new SOCloudConfiguration()); + request.getRequestDetails().setRequestInfo(new SORequestInfo()); + request.getRequestDetails().setRequestParameters(new SORequestParameters()); + request.getRequestDetails().getRequestParameters().setUserParams(null); + + // + // cloudConfiguration + // + request.getRequestDetails().getCloudConfiguration().setTenantId(tenantItem.getTenant().getTenantId()); + request.getRequestDetails().getCloudConfiguration().setLcpCloudRegionId( + tenantItem.getItems().getInventoryResponseItems().get(0).getCloudRegion().getCloudRegionId()); + + // + // modelInfo + // + AAINQInventoryResponseItem vfModuleItem = vnfItem.getItems().getInventoryResponseItems().get(nonBaseIndex); + + request.getRequestDetails().getModelInfo().setModelType("vfModule"); + request.getRequestDetails().getModelInfo() + .setModelInvariantId(vfModuleItem.getVfModule().getModelInvariantId()); + request.getRequestDetails().getModelInfo().setModelVersionId(vfModuleItem.getVfModule().getModelVersionId()); + + for (AAINQExtraProperty prop : vfModuleItem.getExtraProperties().getExtraProperty()) { + if (prop.getPropertyName().equals(modelNamePropertyKey)) { + request.getRequestDetails().getModelInfo().setModelName(prop.getPropertyValue()); + } else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { + request.getRequestDetails().getModelInfo().setModelVersion(prop.getPropertyValue()); + } + } + + // + // requestInfo + // + String instanceName = vnfItem.getItems().getInventoryResponseItems().get(baseIndex).getVfModule() + .getVfModuleName().replace("Vfmodule", "vDNS"); + int numberOfNonBaseModules = findNonBaseModules(vnfItem.getItems().getInventoryResponseItems()); + // Code to create unique VF Module names across the invocations. + if (numberOfNonBaseModules == 1) { + int instanceNumber = 1; + instanceName = instanceName.concat("-").concat(String.valueOf(instanceNumber)); + request.getRequestDetails().getRequestInfo().setInstanceName(instanceName); + } else if (numberOfNonBaseModules > 1) { + int instanceNumber = numberOfNonBaseModules + 1; + instanceName = instanceName.concat("-").concat(String.valueOf(instanceNumber)); + request.getRequestDetails().getRequestInfo().setInstanceName(instanceName); + } else { + request.getRequestDetails().getRequestInfo().setInstanceName(vnfItem.getItems().getInventoryResponseItems() + .get(baseIndex).getVfModule().getVfModuleName().replace("Vfmodule", "vDNS")); + } + request.getRequestDetails().getRequestInfo().setSource("POLICY"); + request.getRequestDetails().getRequestInfo().setSuppressRollback(false); + request.getRequestDetails().getRequestInfo().setRequestorId("policy"); + + // + // relatedInstanceList + // + SORelatedInstanceListElement relatedInstanceListElement1 = new SORelatedInstanceListElement(); + SORelatedInstanceListElement relatedInstanceListElement2 = new SORelatedInstanceListElement(); + relatedInstanceListElement1.setRelatedInstance(new SORelatedInstance()); + relatedInstanceListElement2.setRelatedInstance(new SORelatedInstance()); + + // Service Item + relatedInstanceListElement1.getRelatedInstance() + .setInstanceId(vnfServiceItem.getServiceInstance().getServiceInstanceID()); + relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SOModelInfo()); + relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service"); + relatedInstanceListElement1.getRelatedInstance().getModelInfo() + .setModelInvariantId(vnfServiceItem.getServiceInstance().getModelInvariantId()); + for (AAINQExtraProperty prop : vnfServiceItem.getExtraProperties().getExtraProperty()) { + if (prop.getPropertyName().equals(modelNamePropertyKey)) { + relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue()); + } else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { + relatedInstanceListElement1.getRelatedInstance().getModelInfo() + .setModelVersion(prop.getPropertyValue()); + } + } + + // VNF Item + relatedInstanceListElement2.getRelatedInstance().setInstanceId(vnfItem.getGenericVNF().getVnfID()); + relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SOModelInfo()); + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelInvariantId(vnfItem.getGenericVNF().getModelInvariantId()); + for (AAINQExtraProperty prop : vnfItem.getExtraProperties().getExtraProperty()) { + if (prop.getPropertyName().equals(modelNamePropertyKey)) { + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue()); + } else if (prop.getPropertyName().equals(modelVersionPropertyKey)) { + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelVersion(prop.getPropertyValue()); + } else if (prop.getPropertyName().equals(modelVersionIdPropertyKey)) { + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelVersionId(prop.getPropertyValue()); + } + } + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelCustomizationName(vnfItem + .getGenericVNF().getVnfType().substring(vnfItem.getGenericVNF().getVnfType().lastIndexOf('/') + 1)); + + // Insert the Service Item and VNF Item + request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1); + request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2); + + // Save the instance IDs for the VNF and service to static fields + preserveInstanceIds(vnfItem.getGenericVNF().getVnfID(), + vnfServiceItem.getServiceInstance().getServiceInstanceID()); + + if (logger.isDebugEnabled()) { + logger.debug("SO request sent: {}", Serialization.gsonPretty.toJson(request)); + } + + return request; + } + + /** + * This method is needed to get the serviceInstanceId and vnfInstanceId which is used in the + * asyncSORestCall. + * + * @param requestId the request Id + * @param wm the working memory + * @param request the request + */ + public static void sendRequest(String requestId, WorkingMemory wm, Object request) { + SOManager soManager = new SOManager(); + soManager.asyncSORestCall(requestId, wm, lastServiceItemServiceInstanceId, lastVNFItemVnfId, + (SORequest) request); + } + + /** + * Constructs and sends an AAI vserver Named Query. + * + * @param onset the virtial control loop event + * @returns the response to the AAI Named Query + */ + private AAINQResponseWrapper performAaiNamedQueryRequest(VirtualControlLoopEvent onset) { + + // create AAI named-query request with UUID started with "" + AAINQRequest aaiNqRequest = new AAINQRequest(); + AAINQQueryParameters aaiNqQueryParam = new AAINQQueryParameters(); + AAINQNamedQuery aaiNqNamedQuery = new AAINQNamedQuery(); + final AAINQInstanceFilters aaiNqInstanceFilter = new AAINQInstanceFilters(); + + // queryParameters + // UUID.fromString($params.getAaiNamedQueryUUID()) TO DO: AaiNamedQueryUUID + aaiNqNamedQuery.setNamedQueryUUID(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469")); + aaiNqQueryParam.setNamedQuery(aaiNqNamedQuery); + aaiNqRequest.setQueryParameters(aaiNqQueryParam); + // + // instanceFilters + // + Map> aaiNqInstanceFilterMap = new HashMap<>(); + Map aaiNqInstanceFilterMapItem = new HashMap<>(); + // TO DO: get vserver.vname from dcae onset.AAI.get("vserver.vserver-name") + aaiNqInstanceFilterMapItem.put("vserver-name", onset.getAAI().get("vserver.vserver-name")); + aaiNqInstanceFilterMap.put("vserver", aaiNqInstanceFilterMapItem); + aaiNqInstanceFilter.getInstanceFilter().add(aaiNqInstanceFilterMap); + aaiNqRequest.setInstanceFilters(aaiNqInstanceFilter); + + if (logger.isDebugEnabled()) { + logger.debug("AAI Request sent: {}", Serialization.gsonPretty.toJson(aaiNqRequest)); + } + + AAINQResponse aaiNqResponse = new AAIManager(new RESTManager()).postQuery(getPeManagerEnvProperty("aai.url"), + getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiNqRequest, + onset.getRequestID()); + + // Check AAI response + if (aaiNqResponse == null) { + logger.warn("No response received from AAI for request {}", aaiNqRequest); + return null; + } + + // Create AAINQResponseWrapper + AAINQResponseWrapper aaiNqResponseWrapper = new AAINQResponseWrapper(onset.getRequestID(), aaiNqResponse); + + if (logger.isDebugEnabled()) { + logger.debug("AAI Named Query Response: "); + logger.debug(Serialization.gsonPretty.toJson(aaiNqResponseWrapper.getAainqresponse())); + } + + return aaiNqResponseWrapper; + } + + /** + * Find the base index or non base index in a list of inventory response items. + * + * @param inventoryResponseItems the list of inventory response items + * @param baseIndexFlag true if we are searching for the base index, false if we are searching + * for the non base index + * @return the base or non base index or -1 if the index was not found + */ + private int findIndex(List inventoryResponseItems, boolean baseIndexFlag) { + for (AAINQInventoryResponseItem invenoryResponseItem : inventoryResponseItems) { + if (invenoryResponseItem.getVfModule() != null + && baseIndexFlag == invenoryResponseItem.getVfModule().getIsBaseVfModule()) { + return inventoryResponseItems.indexOf(invenoryResponseItem); + } + } + + return -1; + } + + /** + * Find the number of non base modules present in API response object. + * + * @param inventoryResponseItems the list of inventory response items + * @return number of non base index modules + */ + + private int findNonBaseModules(List inventoryResponseItems) { + int nonBaseModuleCount = 0; + for (AAINQInventoryResponseItem invenoryResponseItem : inventoryResponseItems) { + if (invenoryResponseItem.getVfModule() != null + && (!invenoryResponseItem.getVfModule().getIsBaseVfModule())) { + nonBaseModuleCount++; + } + } + return nonBaseModuleCount; + } + + /** + * This method is called to remember the last service instance ID and VNF Item VNF ID. Note + * these fields are static, beware for multithreaded deployments + * + * @param vnfInstanceId update the last VNF instance ID to this value + * @param serviceInstanceId update the last service instance ID to this value + */ + private static void preserveInstanceIds(final String vnfInstanceId, final String serviceInstanceId) { + lastVNFItemVnfId = vnfInstanceId; + lastServiceItemServiceInstanceId = serviceInstanceId; + } + + /** + * This method reads and validates environmental properties coming from the policy engine. Null + * properties cause an {@link IllegalArgumentException} runtime exception to be thrown + * + * @param string the name of the parameter to retrieve + * @return the property value + */ + private static String getPeManagerEnvProperty(String enginePropertyName) { + String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName); + if (enginePropertyValue == null) { + throw new IllegalArgumentException("The value of policy engine manager environment property \"" + + enginePropertyName + "\" may not be null"); + } + return enginePropertyValue; + } } diff --git a/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java b/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java index 5d2134ec1..108962c22 100644 --- a/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java +++ b/controlloop/common/actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/TestSOActorServiceProvider.java @@ -20,7 +20,10 @@ package org.onap.policy.controlloop.actor.so; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import java.util.UUID; @@ -36,73 +39,79 @@ import org.onap.policy.simulators.Util; import org.onap.policy.so.SORequest; public class TestSOActorServiceProvider { - @BeforeClass - public static void setUpSimulator() { - try { - Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testConstructRequest() { - VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); - ControlLoopOperation operation = new ControlLoopOperation(); - - UUID requestID = UUID.randomUUID(); - onset.setRequestID(requestID); - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - - Policy policy = new Policy(); - policy.setActor("Dorothy"); - policy.setRecipe("GoToOz"); - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); - - policy.setActor("SO"); - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); - - policy.setRecipe("VF Module Create"); - assertNotNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:999999"); - assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - assertNotNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); - - SORequest request = new SOActorServiceProvider().constructRequest(onset, operation, policy); - - assertEquals(requestID, request.getRequestId()); - assertEquals("policy", request.getRequestDetails().getRequestInfo().getRequestorId()); - assertEquals("RegionOne", request.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId()); - } - - @Test - public void testSendRequest() { - try { - SOActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null); - } - catch (Exception e) { - fail("Test should not throw an exception"); - } - } - - @Test - public void testMethods() { - SOActorServiceProvider sp = new SOActorServiceProvider(); - - assertEquals("SO", sp.actor()); - assertEquals(1, sp.recipes().size()); - assertEquals("VF Module Create", sp.recipes().get(0)); - assertEquals(0, sp.recipePayloads("VF Module Create").size()); - } + + /** + * Set up for test class. + */ + @BeforeClass + public static void setUpSimulator() { + try { + Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + /** + * Tear down after test class. + */ + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testConstructRequest() { + VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); + final ControlLoopOperation operation = new ControlLoopOperation(); + + final UUID requestId = UUID.randomUUID(); + onset.setRequestID(requestId); + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + + Policy policy = new Policy(); + policy.setActor("Dorothy"); + policy.setRecipe("GoToOz"); + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); + + policy.setActor("SO"); + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); + + policy.setRecipe("VF Module Create"); + assertNotNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:999999"); + assertNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + assertNotNull(new SOActorServiceProvider().constructRequest(onset, operation, policy)); + + SORequest request = new SOActorServiceProvider().constructRequest(onset, operation, policy); + + assertEquals(requestId, request.getRequestId()); + assertEquals("policy", request.getRequestDetails().getRequestInfo().getRequestorId()); + assertEquals("RegionOne", request.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId()); + } + + @Test + public void testSendRequest() { + try { + SOActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null); + } catch (Exception e) { + fail("Test should not throw an exception"); + } + } + + @Test + public void testMethods() { + SOActorServiceProvider sp = new SOActorServiceProvider(); + + assertEquals("SO", sp.actor()); + assertEquals(1, sp.recipes().size()); + assertEquals("VF Module Create", sp.recipes().get(0)); + assertEquals(0, sp.recipePayloads("VF Module Create").size()); + } } diff --git a/controlloop/common/actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VFCActorServiceProvider.java b/controlloop/common/actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VFCActorServiceProvider.java index c2de78c2c..839b07e2b 100644 --- a/controlloop/common/actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VFCActorServiceProvider.java +++ b/controlloop/common/actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VFCActorServiceProvider.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2017 Intel Corp. All rights reserved. + * Copyright (C) 2017-2018 Intel Corp. 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. @@ -18,120 +18,133 @@ package org.onap.policy.controlloop.actor.vfc; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + import java.util.Collections; import java.util.List; import java.util.UUID; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.vfc.VFCRequest; -import org.onap.policy.vfc.VFCHealRequest; -import org.onap.policy.vfc.VFCHealAdditionalParams; -import org.onap.policy.vfc.VFCHealActionVmInfo; + +import org.onap.policy.aai.AAIGETVnfResponse; +import org.onap.policy.aai.AAIManager; import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.rest.RESTManager; -import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import org.onap.policy.aai.AAIManager; -import org.onap.policy.aai.AAIGETVnfResponse; +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.slf4j.Logger; import org.slf4j.LoggerFactory; public class VFCActorServiceProvider implements Actor { - private static final Logger logger = LoggerFactory.getLogger(VFCActorServiceProvider.class); - - // Strings for VFC Actor - private static final String VFC_ACTOR = "VFC"; - - // Strings for targets - private static final String TARGET_VM = "VM"; - - // Strings for recipes - private static final String RECIPE_RESTART = "Restart"; - - private static final ImmutableList recipes = ImmutableList.of(RECIPE_RESTART); - private static final ImmutableMap> targets = new ImmutableMap.Builder>() - .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).build(); - - @Override - public String actor() { - return VFC_ACTOR; - } - - @Override - public List recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List recipePayloads(String recipe) { - return Collections.emptyList(); - } - - public static VFCRequest constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, - Policy policy, AAIGETVnfResponse vnfResponse) { - - // Construct an VFC request - VFCRequest request = new VFCRequest(); - String serviceInstance = onset.getAAI().get("service-instance.service-instance-id"); - if (serviceInstance == null || "".equals(serviceInstance)) - { - AAIGETVnfResponse tempVnfResp = vnfResponse; - if(tempVnfResp == null) //if the response is null, we haven't queried - { - tempVnfResp = getAAIServiceInstance(onset); //This does the AAI query since we haven't already - if (tempVnfResp == null) - return null; - } - serviceInstance = tempVnfResp.getServiceId(); - } - request.setNSInstanceId(serviceInstance); - request.setRequestId(onset.getRequestID()); - request.setHealRequest(new VFCHealRequest()); - request.getHealRequest().setVnfInstanceId(onset.getAAI().get("generic-vnf.vnf-id")); - request.getHealRequest().setCause(operation.getMessage()); - request.getHealRequest().setAdditionalParams(new VFCHealAdditionalParams()); - - if (policy.getRecipe().toLowerCase().equalsIgnoreCase(RECIPE_RESTART)) { - request.getHealRequest().getAdditionalParams().setAction("restartvm"); - request.getHealRequest().getAdditionalParams().setActionInfo(new VFCHealActionVmInfo()); - request.getHealRequest().getAdditionalParams().getActionInfo().setVmid(onset.getAAI().get("vserver.vserver-id")); - request.getHealRequest().getAdditionalParams().getActionInfo().setVmname(onset.getAAI().get("vserver.vserver-name")); - } - else { - return null; - } - return request; - } - - private static AAIGETVnfResponse getAAIServiceInstance(VirtualControlLoopEvent event) { - AAIGETVnfResponse response = null; - UUID requestID = event.getRequestID(); - String vnfName = event.getAAI().get("generic-vnf.vnf-name"); - String vnfID = event.getAAI().get("generic-vnf.vnf-id"); - String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url"); - String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username"); - String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); - try { - if (vnfName != null) { - String url = aaiUrl + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; - response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUsername, aaiPassword, requestID, vnfName); - } else if (vnfID != null) { - String url = aaiUrl + "/aai/v11/network/generic-vnfs/generic-vnf/"; - response = new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUsername, aaiPassword, requestID, vnfID); - } else { - logger.error("getAAIServiceInstance failed"); - } - } catch (Exception e) { - logger.error("getAAIServiceInstance exception: ", e); - } - return response; - } + private static final Logger logger = LoggerFactory.getLogger(VFCActorServiceProvider.class); + + // Strings for VFC Actor + private static final String VFC_ACTOR = "VFC"; + + // Strings for targets + private static final String TARGET_VM = "VM"; + + // Strings for recipes + private static final String RECIPE_RESTART = "Restart"; + + private static final ImmutableList recipes = ImmutableList.of(RECIPE_RESTART); + private static final ImmutableMap> targets = + new ImmutableMap.Builder>().put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).build(); + + @Override + public String actor() { + return VFC_ACTOR; + } + + @Override + public List recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List recipePayloads(String recipe) { + return Collections.emptyList(); + } + + /** + * Construct a request. + * + * @param onset the onset event + * @param operation the control loop operation + * @param policy the policy + * @param vnfResponse the VNF response + * @return the constructed request + */ + public static VFCRequest constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, + Policy policy, AAIGETVnfResponse vnfResponse) { + + // Construct an VFC request + VFCRequest request = new VFCRequest(); + String serviceInstance = onset.getAAI().get("service-instance.service-instance-id"); + if (serviceInstance == null || "".equals(serviceInstance)) { + AAIGETVnfResponse tempVnfResp = vnfResponse; + if (tempVnfResp == null) { // if the response is null, we haven't queried + // This does the AAI query since we haven't already + tempVnfResp = getAaiServiceInstance(onset); + if (tempVnfResp == null) { + return null; + } + } + serviceInstance = tempVnfResp.getServiceId(); + } + request.setNSInstanceId(serviceInstance); + request.setRequestId(onset.getRequestID()); + request.setHealRequest(new VFCHealRequest()); + request.getHealRequest().setVnfInstanceId(onset.getAAI().get("generic-vnf.vnf-id")); + request.getHealRequest().setCause(operation.getMessage()); + request.getHealRequest().setAdditionalParams(new VFCHealAdditionalParams()); + + if (policy.getRecipe().toLowerCase().equalsIgnoreCase(RECIPE_RESTART)) { + request.getHealRequest().getAdditionalParams().setAction("restartvm"); + request.getHealRequest().getAdditionalParams().setActionInfo(new VFCHealActionVmInfo()); + request.getHealRequest().getAdditionalParams().getActionInfo() + .setVmid(onset.getAAI().get("vserver.vserver-id")); + request.getHealRequest().getAdditionalParams().getActionInfo() + .setVmname(onset.getAAI().get("vserver.vserver-name")); + } else { + return null; + } + return request; + } + + private static AAIGETVnfResponse getAaiServiceInstance(VirtualControlLoopEvent event) { + AAIGETVnfResponse response = null; + UUID requestId = event.getRequestID(); + String vnfName = event.getAAI().get("generic-vnf.vnf-name"); + String vnfId = event.getAAI().get("generic-vnf.vnf-id"); + String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username"); + String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); + try { + if (vnfName != null) { + String url = aaiUrl + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; + response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUsername, aaiPassword, requestId, + vnfName); + } else if (vnfId != null) { + String url = aaiUrl + "/aai/v11/network/generic-vnfs/generic-vnf/"; + response = new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUsername, aaiPassword, requestId, + vnfId); + } else { + logger.error("getAAIServiceInstance failed"); + } + } catch (Exception e) { + logger.error("getAAIServiceInstance exception: ", e); + } + return response; + } } diff --git a/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java b/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java index 7919af446..39be472ae 100644 --- a/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java +++ b/controlloop/common/actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/TestVFCActorServiceProvider.java @@ -20,7 +20,10 @@ package org.onap.policy.controlloop.actor.vfc; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import java.util.UUID; @@ -37,72 +40,77 @@ import org.onap.policy.simulators.Util; import org.onap.policy.vfc.VFCRequest; public class TestVFCActorServiceProvider { - @BeforeClass - public static void setUpSimulator() { - try { - Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testConstructRequest() { - VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); - ControlLoopOperation operation = new ControlLoopOperation(); - - Policy policy = new Policy(); - policy.setRecipe("GoToOz"); - - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAAI().put("generic-vnf.vnf-id", "dorothy.gale.1939"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + + /** + * Set up for test class. + */ + @BeforeClass + public static void setUpSimulator() { + try { + Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testConstructRequest() { + VirtualControlLoopEvent onset = new VirtualControlLoopEvent(); + ControlLoopOperation operation = new ControlLoopOperation(); + + Policy policy = new Policy(); + policy.setRecipe("GoToOz"); + + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAAI().put("generic-vnf.vnf-id", "dorothy.gale.1939"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - UUID requestID = UUID.randomUUID(); - onset.setRequestID(requestID); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAAI().put("generic-vnf.vnf-name", "Dorothy"); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + UUID requestId = UUID.randomUUID(); + onset.setRequestID(requestId); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAAI().put("generic-vnf.vnf-name", "Dorothy"); PolicyEngine.manager.getEnvironment().remove("aai.password"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - onset.getAAI().put("service-instance.service-instance-id", ""); - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); - - assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse())); - - policy.setRecipe("Restart"); - assertNotNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse())); - - VFCRequest request = VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse()); - - assertEquals(requestID, request.getRequestId()); - assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId()); - assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction()); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + onset.getAAI().put("service-instance.service-instance-id", ""); + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, null)); + + assertNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse())); + + policy.setRecipe("Restart"); + assertNotNull(VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse())); + + VFCRequest request = + VFCActorServiceProvider.constructRequest(onset, operation, policy, new AAIGETVnfResponse()); + + assertEquals(requestId, request.getRequestId()); + assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId()); + assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction()); } - @Test - public void testMethods() { - VFCActorServiceProvider sp = new VFCActorServiceProvider(); + @Test + public void testMethods() { + VFCActorServiceProvider sp = new VFCActorServiceProvider(); - assertEquals("VFC", sp.actor()); - assertEquals(1, sp.recipes().size()); - assertEquals("Restart", sp.recipes().get(0)); - assertEquals("VM", sp.recipeTargets("Restart").get(0)); - assertEquals(0, sp.recipePayloads("Restart").size()); - } + assertEquals("VFC", sp.actor()); + assertEquals(1, sp.recipes().size()); + assertEquals("Restart", sp.recipes().get(0)); + assertEquals("VM", sp.recipeTargets("Restart").get(0)); + assertEquals(0, sp.recipePayloads("Restart").size()); + } } diff --git a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/ActorService.java b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/ActorService.java index 45bb9f265..b0b7eb566 100644 --- a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/ActorService.java +++ b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/ActorService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ActorService * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,42 +20,53 @@ package org.onap.policy.controlloop.actorserviceprovider; +import com.google.common.collect.ImmutableList; + import java.util.Iterator; import java.util.ServiceLoader; import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableList; public class ActorService { - private static final Logger logger = LoggerFactory.getLogger(ActorService.class); - private static ActorService service; - - // USed to load actors - private ServiceLoader loader; - - private ActorService() { - loader = ServiceLoader.load(Actor.class); - } - - public static synchronized ActorService getInstance() { - if (service == null) { - service = new ActorService(); - } - return service; - } - - public ImmutableList actors() { - Iterator iter = loader.iterator(); - logger.debug("returning actors"); - while (iter.hasNext()) { - if (logger.isDebugEnabled()) { - logger.debug("Got {}", iter.next().actor()); - } - } - - return ImmutableList.copyOf(loader.iterator()); - } + private static final Logger logger = LoggerFactory.getLogger(ActorService.class); + private static ActorService service; + + // USed to load actors + private ServiceLoader loader; + + private ActorService() { + loader = ServiceLoader.load(Actor.class); + } + + /** + * Get the single instance. + * + * @return the instance + */ + public static synchronized ActorService getInstance() { + if (service == null) { + service = new ActorService(); + } + return service; + } + + /** + * Get the actors. + * + * @return the actors + */ + public ImmutableList actors() { + Iterator iter = loader.iterator(); + logger.debug("returning actors"); + while (iter.hasNext()) { + if (logger.isDebugEnabled()) { + logger.debug("Got {}", iter.next().actor()); + } + } + + return ImmutableList.copyOf(loader.iterator()); + } } diff --git a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/spi/Actor.java b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/spi/Actor.java index b8e310d61..46cc6f643 100644 --- a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/spi/Actor.java +++ b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/spi/Actor.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Actor * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -23,13 +23,13 @@ package org.onap.policy.controlloop.actorserviceprovider.spi; import java.util.List; public interface Actor { - - public String actor(); - - public List recipes(); - - public List recipeTargets(String recipe); - - public List recipePayloads(String recipe); + + public String actor(); + + public List recipes(); + + public List recipeTargets(String recipe); + + public List recipePayloads(String recipe); } diff --git a/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActor.java b/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActor.java index 5bf66bc21..0fd00e12a 100644 --- a/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActor.java +++ b/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActor.java @@ -26,35 +26,35 @@ import java.util.List; import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; public class TestActor implements Actor { - @Override - public String actor() { - return this.getClass().getSimpleName(); - } - - @Override - public List recipes() { - List recipieList = new ArrayList<>(); - recipieList.add("Dorothy"); - recipieList.add("Wizard"); - - return recipieList; - } - - @Override - public List recipeTargets(String recipe) { - List recipieTargetList = new ArrayList<>(); - recipieTargetList.add("Wicked Witch"); - recipieTargetList.add("Wizard of Oz"); - - return recipieTargetList; - } - - @Override - public List recipePayloads(String recipe) { - List recipiePayloadList = new ArrayList<>(); - recipiePayloadList.add("Dorothy"); - recipiePayloadList.add("Toto"); - - return recipiePayloadList; - } + @Override + public String actor() { + return this.getClass().getSimpleName(); + } + + @Override + public List recipes() { + List recipieList = new ArrayList<>(); + recipieList.add("Dorothy"); + recipieList.add("Wizard"); + + return recipieList; + } + + @Override + public List recipeTargets(String recipe) { + List recipieTargetList = new ArrayList<>(); + recipieTargetList.add("Wicked Witch"); + recipieTargetList.add("Wizard of Oz"); + + return recipieTargetList; + } + + @Override + public List recipePayloads(String recipe) { + List recipiePayloadList = new ArrayList<>(); + recipiePayloadList.add("Dorothy"); + recipiePayloadList.add("Toto"); + + return recipiePayloadList; + } } diff --git a/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActorServiceProvider.java b/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActorServiceProvider.java index 14c2d8297..1544e1ab4 100644 --- a/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActorServiceProvider.java +++ b/controlloop/common/actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/TestActorServiceProvider.java @@ -24,31 +24,30 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.onap.policy.controlloop.actorserviceprovider.ActorService; import org.onap.policy.controlloop.actorserviceprovider.spi.Actor; public class TestActorServiceProvider { - - @Test - public void testActorServiceProvider() { - ActorService actorService = ActorService.getInstance(); - assertNotNull(actorService); - - assertEquals(1, actorService.actors().size()); - - actorService = ActorService.getInstance(); - assertNotNull(actorService); - - Actor testActor = ActorService.getInstance().actors().get(0); - assertNotNull(testActor); - - assertEquals("TestActor", testActor.actor()); - - assertEquals(2, testActor.recipes().size()); - assertEquals("Dorothy", testActor.recipes().get(0)); - assertEquals("Wizard", testActor.recipes().get(1)); - - assertEquals(2, testActor.recipeTargets("Dorothy").size()); - assertEquals(2, testActor.recipePayloads("Dorothy").size()); - } + + @Test + public void testActorServiceProvider() { + ActorService actorService = ActorService.getInstance(); + assertNotNull(actorService); + + assertEquals(1, actorService.actors().size()); + + actorService = ActorService.getInstance(); + assertNotNull(actorService); + + Actor testActor = ActorService.getInstance().actors().get(0); + assertNotNull(testActor); + + assertEquals("TestActor", testActor.actor()); + + assertEquals(2, testActor.recipes().size()); + assertEquals("Dorothy", testActor.recipes().get(0)); + assertEquals("Wizard", testActor.recipes().get(1)); + + assertEquals(2, testActor.recipeTargets("Dorothy").size()); + assertEquals(2, testActor.recipePayloads("Dorothy").size()); + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java index 3f19fdcaf..e6ccc18af 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -21,26 +21,26 @@ package org.onap.policy.controlloop; public class ControlLoopException extends Exception { - private static final long serialVersionUID = 6400725747325923701L; + private static final long serialVersionUID = 6400725747325923701L; - public ControlLoopException() { - super(); - } + public ControlLoopException() { + super(); + } - public ControlLoopException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public ControlLoopException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } - public ControlLoopException(String message, Throwable cause) { - super(message, cause); - } + public ControlLoopException(String message, Throwable cause) { + super(message, cause); + } - public ControlLoopException(String message) { - super(message); - } + public ControlLoopException(String message) { + super(message); + } - public ControlLoopException(Throwable cause) { - super(cause); - } + public ControlLoopException(Throwable cause) { + super(cause); + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java index 437920cfb..4bf500704 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -26,24 +26,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public interface ControlLoopLogger { - - public void info(String... parameters); - - public void metrics(String... msgs); - - public void metrics(Object obj); - - public static class Factory { - private static final Logger logger = LoggerFactory.getLogger(Factory.class); - - public ControlLoopLogger buildLogger(String className) throws ControlLoopException { - try { - Constructor constr = Class.forName(className).getConstructor(); - return (ControlLoopLogger) constr.newInstance(); - } catch (Exception e) { - logger.error("buildLogger threw: ", e); - throw new ControlLoopException("Cannot load class " + className + " as a control loop logger"); - } - } - } + + public void info(String... parameters); + + public void metrics(String... msgs); + + public void metrics(Object obj); + + public static class Factory { + private static final Logger logger = LoggerFactory.getLogger(Factory.class); + + /** + * Construct an instance. + * + * @param className name of the class + * @return the instance + * @throws ControlLoopException if an error occurs + */ + public ControlLoopLogger buildLogger(String className) throws ControlLoopException { + try { + Constructor constr = Class.forName(className).getConstructor(); + return (ControlLoopLogger) constr.newInstance(); + } catch (Exception e) { + logger.error("buildLogger threw: ", e); + throw new ControlLoopException("Cannot load class " + className + " as a control loop logger"); + } + } + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java index 3d31c413b..2b1fbefc7 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -26,21 +26,27 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public interface ControlLoopPublisher { - - public void publish(Object object); - - public static class Factory { - private static final Logger logger = LoggerFactory.getLogger(Factory.class); - - - public ControlLoopPublisher buildLogger(String className) throws ControlLoopException { - try { - Constructor constr = Class.forName(className).getConstructor(); - return (ControlLoopPublisher) constr.newInstance(); - } catch (Exception e) { - logger.error("ControlLoopPublisher.buildLogger threw: ", e); - throw new ControlLoopException("Cannot load class " + className + " as a control loop publisher"); - } - } - } + + public void publish(Object object); + + public static class Factory { + private static final Logger logger = LoggerFactory.getLogger(Factory.class); + + /** + * Construct an instance. + * + * @param className name of the class + * @return the instance + * @throws ControlLoopException if an error occurs + */ + public ControlLoopPublisher buildLogger(String className) throws ControlLoopException { + try { + Constructor constr = Class.forName(className).getConstructor(); + return (ControlLoopPublisher) constr.newInstance(); + } catch (Exception e) { + logger.error("ControlLoopPublisher.buildLogger threw: ", e); + throw new ControlLoopException("Cannot load class " + className + " as a control loop publisher"); + } + } + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java index 1d1451461..224e33559 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java @@ -41,682 +41,779 @@ import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.controlloop.policy.FinalResult; import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.controlloop.processor.ControlLoopProcessor; +import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.guard.GuardResult; import org.onap.policy.guard.LockCallback; import org.onap.policy.guard.PolicyGuard; import org.onap.policy.guard.PolicyGuard.LockResult; import org.onap.policy.guard.TargetLock; import org.onap.policy.rest.RESTManager; -import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopEventManager implements LockCallback, Serializable { - private static final String VM_NAME = "VM_NAME"; - private static final String VNF_NAME = "VNF_NAME"; - private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; - private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; - private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; - private static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled"; - private static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled"; - - private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class); - - private static final long serialVersionUID = -1216568161322872641L; - public final String closedLoopControlName; - public final UUID requestID; - - private String controlLoopResult; - private transient ControlLoopProcessor processor = null; - private VirtualControlLoopEvent onset; - private Integer numOnsets = 0; - private Integer numAbatements = 0; - private VirtualControlLoopEvent abatement; - private FinalResult controlLoopTimedOut = null; - - private boolean isActivated = false; - private LinkedList controlLoopHistory = new LinkedList<>(); - private ControlLoopOperationManager currentOperation = null; - private transient TargetLock targetLock = null; - private AAIGETVnfResponse vnfResponse = null; - private AAIGETVserverResponse vserverResponse = null; - private static String aaiHostURL; - private static String aaiUser; - private static String aaiPassword; - - private static Collection requiredAAIKeys = new ArrayList<>(); - static { - requiredAAIKeys.add("AICVServerSelfLink"); - requiredAAIKeys.add("AICIdentity"); - requiredAAIKeys.add("is_closed_loop_disabled"); - requiredAAIKeys.add(VM_NAME); - } - - public ControlLoopEventManager(String closedLoopControlName, UUID requestID) { - this.closedLoopControlName = closedLoopControlName; - this.requestID = requestID; - } - - public String getControlLoopResult() { - return controlLoopResult; - } - - public void setControlLoopResult(String controlLoopResult) { - this.controlLoopResult = controlLoopResult; - } - - public Integer getNumOnsets() { - return numOnsets; - } - - public void setNumOnsets(Integer numOnsets) { - this.numOnsets = numOnsets; - } - - public Integer getNumAbatements() { - return numAbatements; - } - - public void setNumAbatements(Integer numAbatements) { - this.numAbatements = numAbatements; - } - - public boolean isActivated() { - return isActivated; - } - - public void setActivated(boolean isActivated) { - this.isActivated = isActivated; - } - - public VirtualControlLoopEvent getOnsetEvent() { - return this.onset; - } - - public VirtualControlLoopEvent getAbatementEvent() { - return this.abatement; - } - - public ControlLoopProcessor getProcessor() { - return this.processor; - } - - public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); - try { - // - // This method should ONLY be called ONCE - // - if (this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager has already been activated."); - } - // - // Syntax check the event - // - checkEventSyntax(event); - - // - // At this point we are good to go with this event - // - this.onset = event; - this.numOnsets = 1; - // - notification.setNotification(ControlLoopNotificationType.ACTIVE); - // - // Set ourselves as active - // - this.isActivated = true; - } catch (ControlLoopException e) { - logger.error("{}: activate by event threw: ", this, e); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage(e.getMessage()); - } - return notification; - } - - public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); - try { - // - // This method should ONLY be called ONCE - // - if (this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager has already been activated."); - } - // - // Syntax check the event - // - checkEventSyntax(event); - - // - // Check the YAML - // - if (yamlSpecification == null || yamlSpecification.length() < 1) { - throw new ControlLoopException("yaml specification is null or 0 length"); - } - } catch (ControlLoopException e) { - logger.error("{}: activate by YAML specification and event threw: ",this, e); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage(e.getMessage()); - return notification; - } - - String decodedYaml = null; - try { - decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); - if (decodedYaml != null && decodedYaml.length() > 0) { - yamlSpecification = decodedYaml; - } - } catch (UnsupportedEncodingException e) { - logger.error("{}: YAML decode in activate by YAML specification and event threw: ", this, e); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage(e.getMessage()); - return notification; - } - - try { - // - // Parse the YAML specification - // - this.processor = new ControlLoopProcessor(yamlSpecification); - - // - // At this point we are good to go with this event - // - this.onset = event; - this.numOnsets = 1; - // - // - // - notification.setNotification(ControlLoopNotificationType.ACTIVE); - // - // Set ourselves as active - // - this.isActivated = true; - } catch (ControlLoopException e) { - logger.error("{}: activate by YAML specification and event threw: ",this, e); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage(e.getMessage()); - } - return notification; - } - - public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { - // - // Check if they activated us - // - if (!this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); - } - // - // Make sure we are expecting this call. - // - if (this.onset == null) { - throw new ControlLoopException("No onset event for ControlLoopEventManager."); - } - // - // Ok, start creating the notification - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); - // - // Check if the overall control loop has timed out - // - if (this.isControlLoopTimedOut()) { - // - // Yes we have timed out - // - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Control Loop timed out"); - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - // - // Check if the current policy is Final - // - FinalResult result = this.processor.checkIsCurrentPolicyFinal(); - if (result == null) { - // - // we are not at a final result - // - return null; - } - - switch (result) { - case FINAL_FAILURE_EXCEPTION: - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Exception in processing closed loop"); - break; - case FINAL_FAILURE: - case FINAL_FAILURE_RETRIES: - case FINAL_FAILURE_TIMEOUT: - case FINAL_FAILURE_GUARD: - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - break; - case FINAL_OPENLOOP: - notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP); - break; - case FINAL_SUCCESS: - notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS); - break; - default: - return null; - } - // - // Be sure to add all the history - // - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - - public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException { - // - // Check if they activated us - // - if (!this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); - } - // - // Make sure we are expecting this call. - // - if (this.onset == null) { - throw new ControlLoopException("No onset event for ControlLoopEventManager."); - } - // - // Is there a current operation? - // - if (this.currentOperation != null) { - // - // Throw an exception, or simply return the current operation? - // - throw new ControlLoopException("Already working an Operation, do not call this method."); - } - // - // Ensure we are not FINAL - // - VirtualControlLoopNotification notification = this.isControlLoopFinal(); - if (notification != null) { - // - // This is weird, we require them to call the isControlLoopFinal() method first - // - // We should really abstract this and avoid throwing an exception, because it really - // isn't an exception. - // - throw new ControlLoopException("Control Loop is in FINAL state, do not call this method."); - } - // - // Not final so get the policy that needs to be worked on. - // - Policy policy = this.processor.getCurrentPolicy(); - if (policy == null) { - throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy."); - } - // - // And setup an operation - // - this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this); - // - // Return it - // - return this.currentOperation; - } - - public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException { - // - // Verify we have a current operation - // - if (this.currentOperation != null) { - // - // Validate they are finishing the current operation - // PLD - this is simply comparing the policy. Do we want to equals the whole object? - // - if (this.currentOperation.policy.equals(operation.policy)) { - logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(), this.currentOperation.getOperationResult()); - // - // Save history - // - this.controlLoopHistory.addAll(this.currentOperation.getHistory()); - // - // Move to the next Policy - // - this.processor.nextPolicyForResult(this.currentOperation.getOperationResult()); - // - // Just null this out - // - this.currentOperation = null; - // - // TODO: Release our lock - // - return; - } - logger.debug("Cannot finish current operation {} does not match given operation {}", this.currentOperation.policy, operation.policy); - return; - } - throw new ControlLoopException("No operation to finish."); - } - - public synchronized LockResult lockCurrentOperation() throws ControlLoopException { - // - // Sanity check - // - if (this.currentOperation == null) { - throw new ControlLoopException("Do not have a current operation."); - } - // - // Have we acquired it already? - // - if (this.targetLock != null) { - // - // TODO: Make sure the current lock is for the same target. - // Currently, it should be. But in the future it may not. - // - return new LockResult<>(GuardResult.LOCK_ACQUIRED, this.targetLock); - } else { - // - // Ask the Guard - // - LockResult lockResult = PolicyGuard.lockTarget( - this.currentOperation.policy.getTarget().getType(), - this.currentOperation.getTargetEntity(), - this.onset.getRequestID(), - this); - // - // Was it acquired? - // - if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) { - // - // Yes, let's save it - // - this.targetLock = lockResult.getB(); - } - return lockResult; - } - } - - public synchronized TargetLock unlockCurrentOperation() { - if (this.targetLock == null) { - return null; - } - if (PolicyGuard.unlockTarget(this.targetLock)) { - TargetLock returnLock = this.targetLock; - this.targetLock = null; - return returnLock; - } - return null; - } - - public enum NEW_EVENT_STATUS { - FIRST_ONSET, - SUBSEQUENT_ONSET, - FIRST_ABATEMENT, - SUBSEQUENT_ABATEMENT, - SYNTAX_ERROR - ; - } - - public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AAIException { - try { - this.checkEventSyntax(event); - if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) { - // - // Check if this is our original ONSET - // - if (event.equals(this.onset)) { - // - // Query A&AI if needed - // - queryAai(event); - - // - // DO NOT retract it - // - return NEW_EVENT_STATUS.FIRST_ONSET; - } - // - // Log that we got an onset - // - this.numOnsets++; - return NEW_EVENT_STATUS.SUBSEQUENT_ONSET; - } - else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { - // - // Have we already got an abatement? - // - if (this.abatement == null) { - // - // Save this - // - this.abatement = event; - // - // Keep track that we received another - // - this.numAbatements++; - // - // - // - return NEW_EVENT_STATUS.FIRST_ABATEMENT; - } - else { - // - // Keep track that we received another - // - this.numAbatements++; - // - // - // - return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT; - } - } - } - catch (ControlLoopException e) { - logger.error("{}: onNewEvent threw: ",this, e); - } - return NEW_EVENT_STATUS.SYNTAX_ERROR; - } - - public VirtualControlLoopNotification setControlLoopTimedOut() { - this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT; - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Control Loop timed out"); - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - - public boolean isControlLoopTimedOut() { - return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT); - } - - public int getControlLoopTimeout(Integer defaultTimeout) { - if (this.processor != null && this.processor.getControlLoop() != null) { - return this.processor.getControlLoop().getTimeout(); - } - if (defaultTimeout != null) { - return defaultTimeout; - } - return 0; - } - - public AAIGETVnfResponse getVnfResponse() { - return vnfResponse; - } - - public AAIGETVserverResponse getVserverResponse() { - return vserverResponse; - } - - public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { - if (event.getClosedLoopEventStatus() == null || - (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET && - event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) { - throw new ControlLoopException("Invalid value in closedLoopEventStatus"); - } - if (event.getClosedLoopControlName() == null || event.getClosedLoopControlName().length() < 1) { - throw new ControlLoopException("No control loop name"); - } - if (event.getRequestID() == null) { - throw new ControlLoopException("No request ID"); - } - if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { - return; - } - if (event.getTarget() == null || event.getTarget().length() < 1) { - throw new ControlLoopException("No target field"); - } else if (! VM_NAME.equalsIgnoreCase(event.getTarget()) && - ! VNF_NAME.equalsIgnoreCase(event.getTarget()) && - ! VSERVER_VSERVER_NAME.equalsIgnoreCase(event.getTarget()) && - ! GENERIC_VNF_VNF_ID.equalsIgnoreCase(event.getTarget()) && - ! GENERIC_VNF_VNF_NAME.equalsIgnoreCase(event.getTarget()) ) { - throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); - } - if (event.getAAI() == null) { - throw new ControlLoopException("AAI is null"); - } - if (event.getAAI().get(GENERIC_VNF_VNF_ID) == null && event.getAAI().get(VSERVER_VSERVER_NAME) == null && - event.getAAI().get(GENERIC_VNF_VNF_NAME) == null) { - throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing"); - } - } - - public void queryAai(VirtualControlLoopEvent event) throws AAIException { - if ((event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED) != null || event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED) != null) && isClosedLoopDisabled(event)) { - throw new AAIException("is-closed-loop-disabled is set to true on VServer or VNF"); - } - - try { - if (event.getAAI().get(GENERIC_VNF_VNF_ID) != null || event.getAAI().get(GENERIC_VNF_VNF_NAME) != null) { - vnfResponse = getAAIVnfInfo(event); - processVNFResponse(vnfResponse, event.getAAI().get(GENERIC_VNF_VNF_ID) != null); - } - else if (event.getAAI().get(VSERVER_VSERVER_NAME) != null) { - vserverResponse = getAAIVserverInfo(event); - processVServerResponse(vserverResponse); - } - } catch (Exception e) { - logger.error("Exception from queryAai: ", e); - throw new AAIException("Exception from queryAai: " + e.toString()); - } - } - - private static void processVNFResponse(AAIGETVnfResponse aaiResponse, boolean queryByVNFID) throws AAIException { - String queryTypeString = (queryByVNFID ? "vnf-id" : "vnf-name"); - - if (aaiResponse == null) { - throw new AAIException("AAI Response is null (query by " + queryTypeString + ")"); - } - if (aaiResponse.getRequestError() != null) { - throw new AAIException("AAI Responded with a request error (query by " + queryTypeString + ")"); - } - - if (aaiResponse.getIsClosedLoopDisabled() != null) { - String value = aaiResponse.getIsClosedLoopDisabled(); - if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || - "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { - throw new AAIException("is-closed-loop-disabled is set to true (query by " + queryTypeString + ")"); - } - } - } - - private static void processVServerResponse(AAIGETVserverResponse aaiResponse) throws AAIException { - if (aaiResponse == null) { - throw new AAIException("AAI Response is null (query by vserver-name)"); - } - if (aaiResponse.getRequestError() != null) { - throw new AAIException("AAI responded with a request error (query by vserver-name)"); - } - - if (aaiResponse.getIsClosedLoopDisabled() != null) { - String value = aaiResponse.getIsClosedLoopDisabled(); - if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || - "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) { - throw new AAIException("is-closed-loop-disabled is set to true (query by vserver-name)"); - } - } - } - - public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) { - if ("true".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || - "T".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || - "yes".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) || - "Y".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED))) { - return true; - } - return ("true".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || - "T".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || - "yes".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) || - "Y".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))); - } - - public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException { - UUID requestID = event.getRequestID(); - AAIGETVserverResponse response = null; - String vserverName = event.getAAI().get(VSERVER_VSERVER_NAME); - - try { - if (vserverName != null) { - aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); - aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); - aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); - String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name="; - String url = aaiHostURL + aaiGetQueryByVserver; - logger.info("AAI Host URL by VServer: {}", url); - response = new AAIManager(new RESTManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName); - } - } catch (Exception e) { - logger.error("getAAIVserverInfo exception: ", e); - throw new ControlLoopException("Exception in getAAIVserverInfo: ", e); - } - - return response; - } - - public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException { - UUID requestID = event.getRequestID(); - AAIGETVnfResponse response = null; - String vnfName = event.getAAI().get(GENERIC_VNF_VNF_NAME); - String vnfID = event.getAAI().get(GENERIC_VNF_VNF_ID); - - aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); - aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); - aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); - - try { - if (vnfName != null) { - String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; - String url = aaiHostURL + aaiGetQueryByVnfName; - logger.info("AAI Host URL by VNF name: {}", url); - response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName); - } else if (vnfID != null) { - String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/"; - String url = aaiHostURL + aaiGetQueryByVnfID; - logger.info("AAI Host URL by VNF ID: {}", url); - response = new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID); - } - } catch (Exception e) { - logger.error("getAAIVnfInfo exception: ", e); - throw new ControlLoopException("Exception in getAAIVnfInfo: ", e); - } - - return response; - } - - @Override - public boolean isActive() { - // TODO - return true; - } - - @Override - public boolean releaseLock() { - // TODO - return false; - } - - @Override - public String toString() { - return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID - + ", processor=" + processor + ", onset=" + (onset != null ? onset.getRequestID() : "null") + ", numOnsets=" + numOnsets + ", numAbatements=" - + numAbatements + ", isActivated=" - + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]"; - } + private static final String VM_NAME = "VM_NAME"; + private static final String VNF_NAME = "VNF_NAME"; + private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; + private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; + private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; + private static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled"; + private static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled"; + + private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class); + + private static final long serialVersionUID = -1216568161322872641L; + public final String closedLoopControlName; + public final UUID requestID; + + private String controlLoopResult; + private transient ControlLoopProcessor processor = null; + private VirtualControlLoopEvent onset; + private Integer numOnsets = 0; + private Integer numAbatements = 0; + private VirtualControlLoopEvent abatement; + private FinalResult controlLoopTimedOut = null; + + private boolean isActivated = false; + private LinkedList controlLoopHistory = new LinkedList<>(); + private ControlLoopOperationManager currentOperation = null; + private transient TargetLock targetLock = null; + private AAIGETVnfResponse vnfResponse = null; + private AAIGETVserverResponse vserverResponse = null; + private static String aaiHostURL; + private static String aaiUser; + private static String aaiPassword; + + private static Collection requiredAAIKeys = new ArrayList<>(); + + static { + requiredAAIKeys.add("AICVServerSelfLink"); + requiredAAIKeys.add("AICIdentity"); + requiredAAIKeys.add("is_closed_loop_disabled"); + requiredAAIKeys.add(VM_NAME); + } + + public ControlLoopEventManager(String closedLoopControlName, UUID requestID) { + this.closedLoopControlName = closedLoopControlName; + this.requestID = requestID; + } + + public String getControlLoopResult() { + return controlLoopResult; + } + + public void setControlLoopResult(String controlLoopResult) { + this.controlLoopResult = controlLoopResult; + } + + public Integer getNumOnsets() { + return numOnsets; + } + + public void setNumOnsets(Integer numOnsets) { + this.numOnsets = numOnsets; + } + + public Integer getNumAbatements() { + return numAbatements; + } + + public void setNumAbatements(Integer numAbatements) { + this.numAbatements = numAbatements; + } + + public boolean isActivated() { + return isActivated; + } + + public void setActivated(boolean isActivated) { + this.isActivated = isActivated; + } + + public VirtualControlLoopEvent getOnsetEvent() { + return this.onset; + } + + public VirtualControlLoopEvent getAbatementEvent() { + return this.abatement; + } + + public ControlLoopProcessor getProcessor() { + return this.processor; + } + + /** + * Activate a control loop event. + * + * @param event the event + * @return the VirtualControlLoopNotification + */ + public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); + try { + // + // This method should ONLY be called ONCE + // + if (this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager has already been activated."); + } + // + // Syntax check the event + // + checkEventSyntax(event); + + // + // At this point we are good to go with this event + // + this.onset = event; + this.numOnsets = 1; + // + notification.setNotification(ControlLoopNotificationType.ACTIVE); + // + // Set ourselves as active + // + this.isActivated = true; + } catch (ControlLoopException e) { + logger.error("{}: activate by event threw: ", this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + } + return notification; + } + + /** + * Activate a control loop event. + * + * @param yamlSpecification the yaml specification + * @param event the event + * @return the VirtualControlLoopNotification + */ + public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); + try { + // + // This method should ONLY be called ONCE + // + if (this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager has already been activated."); + } + // + // Syntax check the event + // + checkEventSyntax(event); + + // + // Check the YAML + // + if (yamlSpecification == null || yamlSpecification.length() < 1) { + throw new ControlLoopException("yaml specification is null or 0 length"); + } + } catch (ControlLoopException e) { + logger.error("{}: activate by YAML specification and event threw: ", this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + return notification; + } + + String decodedYaml = null; + try { + decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); + if (decodedYaml != null && decodedYaml.length() > 0) { + yamlSpecification = decodedYaml; + } + } catch (UnsupportedEncodingException e) { + logger.error("{}: YAML decode in activate by YAML specification and event threw: ", this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + return notification; + } + + try { + // + // Parse the YAML specification + // + this.processor = new ControlLoopProcessor(yamlSpecification); + + // + // At this point we are good to go with this event + // + this.onset = event; + this.numOnsets = 1; + // + // + // + notification.setNotification(ControlLoopNotificationType.ACTIVE); + // + // Set ourselves as active + // + this.isActivated = true; + } catch (ControlLoopException e) { + logger.error("{}: activate by YAML specification and event threw: ", this, e); + notification.setNotification(ControlLoopNotificationType.REJECTED); + notification.setMessage(e.getMessage()); + } + return notification; + } + + /** + * Check if the control loop is final. + * + * @return a VirtualControlLoopNotification if the control loop is final, otherwise + * null is returned + * @throws ControlLoopException if an error occurs + */ + public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { + // + // Check if they activated us + // + if (!this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); + } + // + // Make sure we are expecting this call. + // + if (this.onset == null) { + throw new ControlLoopException("No onset event for ControlLoopEventManager."); + } + // + // Ok, start creating the notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); + // + // Check if the overall control loop has timed out + // + if (this.isControlLoopTimedOut()) { + // + // Yes we have timed out + // + notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); + notification.setMessage("Control Loop timed out"); + notification.getHistory().addAll(this.controlLoopHistory); + return notification; + } + // + // Check if the current policy is Final + // + FinalResult result = this.processor.checkIsCurrentPolicyFinal(); + if (result == null) { + // + // we are not at a final result + // + return null; + } + + switch (result) { + case FINAL_FAILURE_EXCEPTION: + notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); + notification.setMessage("Exception in processing closed loop"); + break; + case FINAL_FAILURE: + case FINAL_FAILURE_RETRIES: + case FINAL_FAILURE_TIMEOUT: + case FINAL_FAILURE_GUARD: + notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); + break; + case FINAL_OPENLOOP: + notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP); + break; + case FINAL_SUCCESS: + notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS); + break; + default: + return null; + } + // + // Be sure to add all the history + // + notification.getHistory().addAll(this.controlLoopHistory); + return notification; + } + + /** + * Process the control loop. + * + * @return a ControlLoopOperationManager + * @throws ControlLoopException if an error occurs + * @throws AAIException if an error occurs retrieving information from A&AI + */ + public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException { + // + // Check if they activated us + // + if (!this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); + } + // + // Make sure we are expecting this call. + // + if (this.onset == null) { + throw new ControlLoopException("No onset event for ControlLoopEventManager."); + } + // + // Is there a current operation? + // + if (this.currentOperation != null) { + // + // Throw an exception, or simply return the current operation? + // + throw new ControlLoopException("Already working an Operation, do not call this method."); + } + // + // Ensure we are not FINAL + // + VirtualControlLoopNotification notification = this.isControlLoopFinal(); + if (notification != null) { + // + // This is weird, we require them to call the isControlLoopFinal() method first + // + // We should really abstract this and avoid throwing an exception, because it really + // isn't an exception. + // + throw new ControlLoopException("Control Loop is in FINAL state, do not call this method."); + } + // + // Not final so get the policy that needs to be worked on. + // + Policy policy = this.processor.getCurrentPolicy(); + if (policy == null) { + throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy."); + } + // + // And setup an operation + // + this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this); + // + // Return it + // + return this.currentOperation; + } + + /** + * Finish an operation. + * + * @param operation the operation + */ + public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException { + // + // Verify we have a current operation + // + if (this.currentOperation != null) { + // + // Validate they are finishing the current operation + // PLD - this is simply comparing the policy. Do we want to equals the whole object? + // + if (this.currentOperation.policy.equals(operation.policy)) { + logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(), + this.currentOperation.getOperationResult()); + // + // Save history + // + this.controlLoopHistory.addAll(this.currentOperation.getHistory()); + // + // Move to the next Policy + // + this.processor.nextPolicyForResult(this.currentOperation.getOperationResult()); + // + // Just null this out + // + this.currentOperation = null; + // + // TODO: Release our lock + // + return; + } + logger.debug("Cannot finish current operation {} does not match given operation {}", + this.currentOperation.policy, operation.policy); + return; + } + throw new ControlLoopException("No operation to finish."); + } + + /** + * Obtain a lock for the current operation. + * + * @return the lock result + * @throws ControlLoopException if an error occurs + */ + public synchronized LockResult lockCurrentOperation() throws ControlLoopException { + // + // Sanity check + // + if (this.currentOperation == null) { + throw new ControlLoopException("Do not have a current operation."); + } + // + // Have we acquired it already? + // + if (this.targetLock != null) { + // + // TODO: Make sure the current lock is for the same target. + // Currently, it should be. But in the future it may not. + // + return new LockResult<>(GuardResult.LOCK_ACQUIRED, this.targetLock); + } else { + // + // Ask the Guard + // + LockResult lockResult = + PolicyGuard.lockTarget(this.currentOperation.policy.getTarget().getType(), + this.currentOperation.getTargetEntity(), this.onset.getRequestID(), this); + // + // Was it acquired? + // + if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) { + // + // Yes, let's save it + // + this.targetLock = lockResult.getB(); + } + return lockResult; + } + } + + /** + * Release the lock for the current operation. + * + * @return the target lock + */ + public synchronized TargetLock unlockCurrentOperation() { + if (this.targetLock == null) { + return null; + } + if (PolicyGuard.unlockTarget(this.targetLock)) { + TargetLock returnLock = this.targetLock; + this.targetLock = null; + return returnLock; + } + return null; + } + + public enum NEW_EVENT_STATUS { + FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR; + } + + /** + * An event onset/abatement. + * + * @param event the event + * @return the status + * @throws AAIException if an error occurs retrieving information from A&AI + */ + public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AAIException { + try { + this.checkEventSyntax(event); + if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) { + // + // Check if this is our original ONSET + // + if (event.equals(this.onset)) { + // + // Query A&AI if needed + // + queryAai(event); + + // + // DO NOT retract it + // + return NEW_EVENT_STATUS.FIRST_ONSET; + } + // + // Log that we got an onset + // + this.numOnsets++; + return NEW_EVENT_STATUS.SUBSEQUENT_ONSET; + } else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { + // + // Have we already got an abatement? + // + if (this.abatement == null) { + // + // Save this + // + this.abatement = event; + // + // Keep track that we received another + // + this.numAbatements++; + // + // + // + return NEW_EVENT_STATUS.FIRST_ABATEMENT; + } else { + // + // Keep track that we received another + // + this.numAbatements++; + // + // + // + return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT; + } + } + } catch (ControlLoopException e) { + logger.error("{}: onNewEvent threw: ", this, e); + } + return NEW_EVENT_STATUS.SYNTAX_ERROR; + } + + /** + * Set the control loop time out. + * + * @return a VirtualControlLoopNotification + */ + public VirtualControlLoopNotification setControlLoopTimedOut() { + this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT; + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); + notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); + notification.setMessage("Control Loop timed out"); + notification.getHistory().addAll(this.controlLoopHistory); + return notification; + } + + public boolean isControlLoopTimedOut() { + return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT); + } + + /** + * Get the control loop timeout. + * + * @param defaultTimeout the default timeout + * @return the timeout + */ + public int getControlLoopTimeout(Integer defaultTimeout) { + if (this.processor != null && this.processor.getControlLoop() != null) { + return this.processor.getControlLoop().getTimeout(); + } + if (defaultTimeout != null) { + return defaultTimeout; + } + return 0; + } + + public AAIGETVnfResponse getVnfResponse() { + return vnfResponse; + } + + public AAIGETVserverResponse getVserverResponse() { + return vserverResponse; + } + + /** + * Check an event syntax. + * + * @param event the event syntax + * @throws ControlLoopException if an error occurs + */ + public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { + if (event.getClosedLoopEventStatus() == null + || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET + && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) { + throw new ControlLoopException("Invalid value in closedLoopEventStatus"); + } + if (event.getClosedLoopControlName() == null || event.getClosedLoopControlName().length() < 1) { + throw new ControlLoopException("No control loop name"); + } + if (event.getRequestID() == null) { + throw new ControlLoopException("No request ID"); + } + if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { + return; + } + if (event.getTarget() == null || event.getTarget().length() < 1) { + throw new ControlLoopException("No target field"); + } else if (!VM_NAME.equalsIgnoreCase(event.getTarget()) && !VNF_NAME.equalsIgnoreCase(event.getTarget()) + && !VSERVER_VSERVER_NAME.equalsIgnoreCase(event.getTarget()) + && !GENERIC_VNF_VNF_ID.equalsIgnoreCase(event.getTarget()) + && !GENERIC_VNF_VNF_NAME.equalsIgnoreCase(event.getTarget())) { + throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); + } + if (event.getAAI() == null) { + throw new ControlLoopException("AAI is null"); + } + if (event.getAAI().get(GENERIC_VNF_VNF_ID) == null && event.getAAI().get(VSERVER_VSERVER_NAME) == null + && event.getAAI().get(GENERIC_VNF_VNF_NAME) == null) { + throw new ControlLoopException( + "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing"); + } + } + + /** + * Query A&AI for an event. + * + * @param event the event + * @throws AAIException if an error occurs retrieving information from A&AI + */ + public void queryAai(VirtualControlLoopEvent event) throws AAIException { + if ((event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED) != null + || event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED) != null) && isClosedLoopDisabled(event)) { + throw new AAIException("is-closed-loop-disabled is set to true on VServer or VNF"); + } + + try { + if (event.getAAI().get(GENERIC_VNF_VNF_ID) != null || event.getAAI().get(GENERIC_VNF_VNF_NAME) != null) { + vnfResponse = getAAIVnfInfo(event); + processVNFResponse(vnfResponse, event.getAAI().get(GENERIC_VNF_VNF_ID) != null); + } else if (event.getAAI().get(VSERVER_VSERVER_NAME) != null) { + vserverResponse = getAAIVserverInfo(event); + processVServerResponse(vserverResponse); + } + } catch (Exception e) { + logger.error("Exception from queryAai: ", e); + throw new AAIException("Exception from queryAai: " + e.toString()); + } + } + + /** + * Process a response from A&AI for a VNF. + * + * @param aaiResponse the response from A&AI + * @param queryByVnfId true if the query was based on vnf-id, false if + * the query was based on vnf-name + * @throws AAIException if an error occurs processing the response + */ + private static void processVNFResponse(AAIGETVnfResponse aaiResponse, boolean queryByVNFID) throws AAIException { + String queryTypeString = (queryByVNFID ? "vnf-id" : "vnf-name"); + + if (aaiResponse == null) { + throw new AAIException("AAI Response is null (query by " + queryTypeString + ")"); + } + if (aaiResponse.getRequestError() != null) { + throw new AAIException("AAI Responded with a request error (query by " + queryTypeString + ")"); + } + + if (aaiResponse.getIsClosedLoopDisabled() != null) { + String value = aaiResponse.getIsClosedLoopDisabled(); + if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) + || "Y".equalsIgnoreCase(value)) { + throw new AAIException("is-closed-loop-disabled is set to true (query by " + queryTypeString + ")"); + } + } + } + + private static void processVServerResponse(AAIGETVserverResponse aaiResponse) throws AAIException { + if (aaiResponse == null) { + throw new AAIException("AAI Response is null (query by vserver-name)"); + } + if (aaiResponse.getRequestError() != null) { + throw new AAIException("AAI responded with a request error (query by vserver-name)"); + } + + if (aaiResponse.getIsClosedLoopDisabled() != null) { + String value = aaiResponse.getIsClosedLoopDisabled(); + if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) + || "Y".equalsIgnoreCase(value)) { + throw new AAIException("is-closed-loop-disabled is set to true (query by vserver-name)"); + } + } + } + + /** + * Is closed loop disabled for an event. + * + * @param event the event + * @return true if the contol loop is disabled, false otherwise + */ + public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) { + if ("true".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) + || "T".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) + || "yes".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED)) + || "Y".equalsIgnoreCase(event.getAAI().get(VSERVER_IS_CLOSED_LOOP_DISABLED))) { + return true; + } + return ("true".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) + || "T".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) + || "yes".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) + || "Y".equalsIgnoreCase(event.getAAI().get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))); + } + + /** + * Get the A&AI VService information for an event. + * + * @param event the event + * @return a AAIGETVserverResponse + * @throws ControlLoopException if an error occurs + */ + public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException { + UUID requestId = event.getRequestID(); + AAIGETVserverResponse response = null; + String vserverName = event.getAAI().get(VSERVER_VSERVER_NAME); + + try { + if (vserverName != null) { + aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); + aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); + String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name="; + String url = aaiHostURL + aaiGetQueryByVserver; + logger.info("AAI Host URL by VServer: {}", url); + response = new AAIManager(new RESTManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestId, + vserverName); + } + } catch (Exception e) { + logger.error("getAAIVserverInfo exception: ", e); + throw new ControlLoopException("Exception in getAAIVserverInfo: ", e); + } + + return response; + } + + /** + * Get A&AI VNF information for an event. + * + * @param event the event + * @return a AAIGETVnfResponse + * @throws ControlLoopException if an error occurs + */ + public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException { + UUID requestId = event.getRequestID(); + AAIGETVnfResponse response = null; + String vnfName = event.getAAI().get(GENERIC_VNF_VNF_NAME); + String vnfId = event.getAAI().get(GENERIC_VNF_VNF_ID); + + aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url"); + aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username"); + aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password"); + + try { + if (vnfName != null) { + String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name="; + String url = aaiHostURL + aaiGetQueryByVnfName; + logger.info("AAI Host URL by VNF name: {}", url); + response = new AAIManager(new RESTManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestId, + vnfName); + } else if (vnfId != null) { + String aaiGetQueryByVnfId = "/aai/v11/network/generic-vnfs/generic-vnf/"; + String url = aaiHostURL + aaiGetQueryByVnfId; + logger.info("AAI Host URL by VNF ID: {}", url); + response = + new AAIManager(new RESTManager()).getQueryByVnfID(url, aaiUser, aaiPassword, requestId, vnfId); + } + } catch (Exception e) { + logger.error("getAAIVnfInfo exception: ", e); + throw new ControlLoopException("Exception in getAAIVnfInfo: ", e); + } + + return response; + } + + @Override + public boolean isActive() { + // TODO + return true; + } + + @Override + public boolean releaseLock() { + // TODO + return false; + } + + @Override + public String toString() { + return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID + + ", processor=" + processor + ", onset=" + (onset != null ? onset.getRequestID() : "null") + + ", numOnsets=" + numOnsets + ", numAbatements=" + numAbatements + ", isActivated=" + isActivated + + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]"; + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java index ba2df3358..7c900249c 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop operation manager * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -54,715 +54,797 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManager implements Serializable { - private static final long serialVersionUID = -3773199283624595410L; - private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class); - - private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; - private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; - private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; - - @Override - public String toString() { - return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestID() : "null") + ", policy=" - + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts - + ", policyResult=" + policyResult - + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory - + "]"; - } - - // - // These properties are not changeable, but accessible - // for Drools Rule statements. - // - public final ControlLoopEvent onset; - public final transient Policy policy; - - // - // Properties used to track the Operation - // - private int attempts = 0; - private transient Operation currentOperation = null; - private LinkedList operationHistory = new LinkedList<>(); - private PolicyResult policyResult = null; - private ControlLoopEventManager eventManager = null; - private String targetEntity; - - public ControlLoopEventManager getEventManager() { - return eventManager; - } - - public void setEventManager(ControlLoopEventManager eventManager) { - this.eventManager = eventManager; - } - - public String getTargetEntity() { - return this.targetEntity; - } - - // - // Internal class used for tracking - // - private class Operation { - private ControlLoopOperation clOperation = new ControlLoopOperation(); - private PolicyResult policyResult = null; - private int attempt = 0; - - @Override - public String toString() { - return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation - + "]"; - } - } - - private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY" - private transient Object operationRequest; - - public Object getOperationRequest() { - return operationRequest; - } - - public String getGuardApprovalStatus() { - return guardApprovalStatus; - } - public void setGuardApprovalStatus(String guardApprovalStatus) { - this.guardApprovalStatus = guardApprovalStatus; - } - - public String getTarget(Policy policy) throws ControlLoopException, AAIException { - if (policy.getTarget() == null) { - throw new ControlLoopException("The target is null"); - } - - if (policy.getTarget().getType() == null) { - throw new ControlLoopException("The target type is null"); - } - - switch(policy.getTarget().getType()) { - case PNF: - throw new ControlLoopException("PNF target is not supported"); - case VM: - case VNF: - VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset; - if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { - return virtualOnset.getAAI().get(VSERVER_VSERVER_NAME); - } - else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { - return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); - } - else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { - /* - * If the onset is enriched with the vnf-id, - * we don't need an A&AI response - */ - if (virtualOnset.getAAI().containsKey(GENERIC_VNF_VNF_ID)) { - return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); - } - - /* - * If the vnf-name was retrieved from the onset then the vnf-id - * must be obtained from the event manager's A&AI GET query - */ - String vnfId = this.eventManager.getVnfResponse().getVnfID(); - if (vnfId == null) { - throw new AAIException("No vnf-id found"); - } - return vnfId; - } - throw new ControlLoopException("Target does not match target type"); - default: - throw new ControlLoopException("The target type is not supported"); - } - } - - public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException, AAIException { - this.onset = onset; - this.policy = policy; - this.guardApprovalStatus = "NONE"; - this.eventManager = em; - this.targetEntity = getTarget(policy); - - // - // Let's make a sanity check - // - switch (policy.getActor()) { - case "APPC": - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - /* - * The target vnf-id may not be the same as the source vnf-id - * specified in the yaml, the target vnf-id is retrieved by - * a named query to A&AI. - */ - String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery( policy.getTarget().getResourceID(), this.targetEntity); - this.targetEntity = targetVnf; - } - break; - case "SO": - break; - case "VFC": - break; - default: - throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor."); - } - } - - public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws ControlLoopException{ - verifyOperatonCanRun(); - - // - // Setup - // - this.policyResult = null; - Operation operation = new Operation(); - operation.attempt = ++this.attempts; - operation.clOperation.setActor(this.policy.getActor()); - operation.clOperation.setOperation(this.policy.getRecipe()); - operation.clOperation.setTarget(this.policy.getTarget().toString()); - operation.clOperation.setSubRequestId(Integer.toString(operation.attempt)); - // - // Now determine which actor we need to construct a request for - // - switch (policy.getActor()) { - case "APPC": - /* - * If the recipe is ModifyConfig, a legacy APPC - * request is constructed. Otherwise an LCMRequest - * is constructed. - */ - this.currentOperation = operation; - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.targetEntity); - } - else { - this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.targetEntity); - } - // - // Save the operation - // - - return operationRequest; - case "SO": - SOActorServiceProvider soActorSP = new SOActorServiceProvider(); - this.operationRequest = soActorSP.constructRequest((VirtualControlLoopEvent)onset, operation.clOperation, this.policy); - - // Save the operation - this.currentOperation = operation; - - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - - return operationRequest; - case "VFC": - this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.eventManager.getVnfResponse()); - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; - default: - throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy"); - } - } - - public PolicyResult onResponse(Object response) { - // - // Which response is it? - // - if (response instanceof Response) { - // - // Cast APPC response and handle it - // - return onResponse((Response) response); - } - else if (response instanceof LCMResponseWrapper) { - // - // Cast LCM response and handle it - // - return onResponse((LCMResponseWrapper) response); - } - else if (response instanceof SOResponseWrapper) { - // - // Cast SO response and handle it - // - return onResponse((SOResponseWrapper) response); - } - else if (response instanceof VFCResponse) { - // - // Cast VFC response and handle it - // - return onResponse((VFCResponse) response); - } - else { - return null; - } - } - - /** - * This method handles operation responses from APPC - * @param appcResponse the APPC response - * @return The result of the response handling - */ - private PolicyResult onResponse(Response appcResponse) { - // - // Determine which subrequestID (ie. attempt) - // - Integer operationAttempt = null; - try { - operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestID()); - } catch (NumberFormatException e) { - // - // We cannot tell what happened if this doesn't exist - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - // - // Sanity check the response message - // - if (appcResponse.getStatus() == null) { - // - // We cannot tell what happened if this doesn't exist - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - // - // Get the Response Code - // - ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode()); - if (code == null) { - // - // We are unaware of this code - // - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - // - // Ok, let's figure out what APP-C's response is - // - switch (code) { - case ACCEPT: - // - // This is good, they got our original message and - // acknowledged it. - // - // Is there any need to track this? - // - return null; - case ERROR: - case REJECT: - // - // We'll consider these two codes as exceptions - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE_EXCEPTION); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE_EXCEPTION; - case SUCCESS: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - case FAILURE: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; - default: - return null; - } - } - - /** - * This method handles operation responses from LCM - * @param dmaapResponse the LCM response - * @return The result of the response handling - */ - private PolicyResult onResponse(LCMResponseWrapper dmaapResponse) { - /* - * Parse out the operation attempt using the subrequestid - */ - Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId()); - if (operationAttempt == null) { - this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); - } - - /* - * Process the APPCLCM response to see what PolicyResult - * should be returned - */ - AbstractMap.SimpleEntry result = AppcLcmActorServiceProvider.processResponse(dmaapResponse); - - if (result.getKey() != null) { - this.completeOperation(operationAttempt, result.getValue(), result.getKey()); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - return result.getKey(); - } - return null; - } - - /** - * This method handles operation responses from SO - * @param msoResponse the SO response - * @return The result of the response handling - */ - private PolicyResult onResponse(SOResponseWrapper msoResponse) { - switch (msoResponse.getSoResponse().getHttpResponseCode()) { - case 200: - case 202: - // - // Consider it as success - // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - default: - // - // Consider it as failure - // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; - } - } - - /** - * This method handles operation responses from VFC - * @param vfcResponse the VFC response - * @return The result of the response handling - */ - private PolicyResult onResponse(VFCResponse vfcResponse) { - if (vfcResponse.getResponseDescriptor().getStatus().equalsIgnoreCase("finished")) { - // - // Consider it as success - // - this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; - } else { - // - // Consider it as failure - // - this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - // increment operation attempts for retries - this.attempts += 1; - return PolicyResult.FAILURE; - } - } - - public Integer getOperationTimeout() { - // - // Sanity check - // - if (this.policy == null) { - logger.debug("getOperationTimeout returning 0"); - return 0; - } - logger.debug("getOperationTimeout returning {}", this.policy.getTimeout()); - return this.policy.getTimeout(); - } - - public String getOperationTimeoutString(int defaultTimeout) { - Integer to = this.getOperationTimeout(); - if (to == null || to == 0) { - return Integer.toString(defaultTimeout) + "s"; - } - return to.toString() + "s"; - } - - public PolicyResult getOperationResult() { - return this.policyResult; - } - - public String getOperationMessage() { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toMessage(); - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toMessage(); - } - return null; - } - - public String getOperationMessage(String guardResult) { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toMessage()+ ", Guard result: " + guardResult; - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult; - } - return null; - } - - public String getOperationHistory() { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toHistory(); - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toHistory(); - } - return null; - } - - public List getHistory() { - LinkedList history = new LinkedList<>(); - for (Operation op : this.operationHistory) { - history.add(new ControlLoopOperation(op.clOperation)); - - } - return history; - } - - public void setOperationHasTimedOut() { - // - // - // - this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT); - } - - public void setOperationHasGuardDeny() { - // - // - // - this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD); - } - - public void setOperationHasException(String message) { - this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION); - } - - public boolean isOperationComplete() { - // - // Is there currently a result? - // - if (this.policyResult == null) { - // - // either we are in process or we - // haven't started - // - return false; - } - // - // We have some result, check if the operation failed - // - if (this.policyResult.equals(PolicyResult.FAILURE)) { - // - // Check if there were no retries specified - // - if (policy.getRetry() == null || policy.getRetry() == 0) { - // - // The result is the failure - // - return true; - } - // - // Check retries - // - if (this.isRetriesMaxedOut()) { - // - // No more attempts allowed, reset - // that our actual result is failure due to retries - // - this.policyResult = PolicyResult.FAILURE_RETRIES; - return true; - } else { - // - // There are more attempts available to try the - // policy recipe. - // - return false; - } - } - // - // Other results mean we are done - // - return true; - } - - public boolean isOperationRunning() { - return (this.currentOperation != null); - } - - /** - * This method verifies that the operation manager may run an operation. - * @return True if the operation can run, false otherwise - * @throws ControlLoopException if the operation cannot run - */ - private void verifyOperatonCanRun() throws ControlLoopException { - // - // They shouldn't call us if we currently running something - // - if (this.currentOperation != null) { - // - // what do we do if we are already running an operation? - // - throw new ControlLoopException("current operation is not null (an operation is already running)"); - } - // - // Check if we have maxed out on retries - // - if (this.policy.getRetry() == null || this.policy.getRetry() < 1) { - // - // No retries are allowed, so check have we even made - // one attempt to execute the operation? - // - if (this.attempts >= 1) { - // - // We have, let's ensure our PolicyResult is set - // - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - // - // - // - throw new ControlLoopException("current operation failed and retries are not allowed"); - } - } else { - // - // Have we maxed out on retries? - // - if (this.attempts > this.policy.getRetry()) { - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries"); - } - } - - return; - } - - private boolean isRetriesMaxedOut() { - if (policy.getRetry() == null || policy.getRetry() == 0) { - // - // There were NO retries specified, so declare - // this as completed. - // - return (this.attempts > 0); - } - return (this.attempts > policy.getRetry()); - } - - private void storeOperationInDataBase(){ - // Only store in DB if enabled - boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled")); - if( !guardEnabled ){ - return; - } - - - // DB Properties - Properties props = new Properties(); - if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null && - PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null && - PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){ - props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); - props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); - props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); - props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader()); - } - - - String opsHistPU = System.getProperty("OperationsHistoryPU"); - if(opsHistPU == null || !opsHistPU.equals("TestOperationsHistoryPU")){ - opsHistPU = "OperationsHistoryPU"; - } - else{ - props.clear(); - } - EntityManager em; - try{ - em = Persistence.createEntityManagerFactory(opsHistPU, props).createEntityManager(); - }catch(Exception e){ - logger.error("storeOperationInDataBase threw: ", e); - return; - } - - OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry(); - - newEntry.setClosedLoopName(this.onset.getClosedLoopControlName()); - newEntry.setRequestId(this.onset.getRequestID().toString()); - newEntry.setActor(this.currentOperation.clOperation.getActor()); - newEntry.setOperation(this.currentOperation.clOperation.getOperation()); - newEntry.setTarget(this.targetEntity); - newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart())); - newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId()); - newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli())); - newEntry.setMessage(this.currentOperation.clOperation.getMessage()); - newEntry.setOutcome(this.currentOperation.clOperation.getOutcome()); - - em.getTransaction().begin(); - em.persist(newEntry); - em.getTransaction().commit(); - - em.close(); - } - - private void completeOperation(Integer attempt, String message, PolicyResult result) { - if (attempt == null) { - logger.debug("attempt cannot be null (i.e. subRequestID)"); - return; - } - if (this.currentOperation != null) { - if (this.currentOperation.attempt == attempt.intValue()) { - this.currentOperation.clOperation.setEnd(Instant.now()); - this.currentOperation.clOperation.setMessage(message); - this.currentOperation.clOperation.setOutcome(result.toString()); - this.currentOperation.policyResult = result; - // - // Save it in history - // - this.operationHistory.add(this.currentOperation); - this.storeOperationInDataBase(); - // - // Set our last result - // - this.policyResult = result; - // - // Clear the current operation field - // - this.currentOperation = null; - return; - } - logger.debug("not current"); - } - for (Operation op : this.operationHistory) { - if (op.attempt == attempt.intValue()) { - op.clOperation.setEnd(Instant.now()); - op.clOperation.setMessage(message); - op.clOperation.setOutcome(result.toString()); - op.policyResult = result; - return; - } - } - logger.debug("Could not find associated operation"); - - } + private static final long serialVersionUID = -3773199283624595410L; + private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class); + + private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; + private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; + private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; + + @Override + public String toString() { + return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestID() : "null") + ", policy=" + + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult=" + + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory + + "]"; + } + + // + // These properties are not changeable, but accessible + // for Drools Rule statements. + // + public final ControlLoopEvent onset; + public final transient Policy policy; + + // + // Properties used to track the Operation + // + private int attempts = 0; + private transient Operation currentOperation = null; + private LinkedList operationHistory = new LinkedList<>(); + private PolicyResult policyResult = null; + private ControlLoopEventManager eventManager = null; + private String targetEntity; + + public ControlLoopEventManager getEventManager() { + return eventManager; + } + + public void setEventManager(ControlLoopEventManager eventManager) { + this.eventManager = eventManager; + } + + public String getTargetEntity() { + return this.targetEntity; + } + + // + // Internal class used for tracking + // + private class Operation { + private ControlLoopOperation clOperation = new ControlLoopOperation(); + private PolicyResult policyResult = null; + private int attempt = 0; + + @Override + public String toString() { + return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation + + "]"; + } + } + + private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY" + private transient Object operationRequest; + + public Object getOperationRequest() { + return operationRequest; + } + + public String getGuardApprovalStatus() { + return guardApprovalStatus; + } + + public void setGuardApprovalStatus(String guardApprovalStatus) { + this.guardApprovalStatus = guardApprovalStatus; + } + + /** + * Get the target for a policy. + * + * @param policy the policy + * @return the target + * @throws ControlLoopException if an error occurs + * @throws AAIException if an error occurs retrieving information from A&AI + */ + public String getTarget(Policy policy) throws ControlLoopException, AAIException { + if (policy.getTarget() == null) { + throw new ControlLoopException("The target is null"); + } + + if (policy.getTarget().getType() == null) { + throw new ControlLoopException("The target type is null"); + } + + switch (policy.getTarget().getType()) { + case PNF: + throw new ControlLoopException("PNF target is not supported"); + case VM: + case VNF: + VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset; + if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { + return virtualOnset.getAAI().get(VSERVER_VSERVER_NAME); + } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { + return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); + } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { + /* + * If the onset is enriched with the vnf-id, we don't need an A&AI response + */ + if (virtualOnset.getAAI().containsKey(GENERIC_VNF_VNF_ID)) { + return virtualOnset.getAAI().get(GENERIC_VNF_VNF_ID); + } + + /* + * If the vnf-name was retrieved from the onset then the vnf-id must be obtained + * from the event manager's A&AI GET query + */ + String vnfId = this.eventManager.getVnfResponse().getVnfID(); + if (vnfId == null) { + throw new AAIException("No vnf-id found"); + } + return vnfId; + } + throw new ControlLoopException("Target does not match target type"); + default: + throw new ControlLoopException("The target type is not supported"); + } + } + + /** + * Construct an instance. + * + * @param onset the onset event + * @param policy the policy + * @param em the event manager + * @throws ControlLoopException if an error occurs + * @throws AAIException if an error occurs retrieving information from A&AI + */ + public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) + throws ControlLoopException, AAIException { + this.onset = onset; + this.policy = policy; + this.guardApprovalStatus = "NONE"; + this.eventManager = em; + this.targetEntity = getTarget(policy); + + // + // Let's make a sanity check + // + switch (policy.getActor()) { + case "APPC": + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + /* + * The target vnf-id may not be the same as the source vnf-id specified in the + * yaml, the target vnf-id is retrieved by a named query to A&AI. + */ + String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(), + this.targetEntity); + this.targetEntity = targetVnf; + } + break; + case "SO": + break; + case "VFC": + break; + default: + throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor."); + } + } + + /** + * Start an operation. + * + * @param onset the onset event + * @return the operation request + * @throws ControlLoopException if an error occurs + */ + public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException { + verifyOperatonCanRun(); + + // + // Setup + // + this.policyResult = null; + Operation operation = new Operation(); + operation.attempt = ++this.attempts; + operation.clOperation.setActor(this.policy.getActor()); + operation.clOperation.setOperation(this.policy.getRecipe()); + operation.clOperation.setTarget(this.policy.getTarget().toString()); + operation.clOperation.setSubRequestId(Integer.toString(operation.attempt)); + // + // Now determine which actor we need to construct a request for + // + switch (policy.getActor()) { + case "APPC": + /* + * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an + * LCMRequest is constructed. + */ + this.currentOperation = operation; + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.targetEntity); + } else { + this.operationRequest = AppcLcmActorServiceProvider.constructRequest( + (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity); + } + // + // Save the operation + // + + return operationRequest; + case "SO": + SOActorServiceProvider soActorSp = new SOActorServiceProvider(); + this.operationRequest = + soActorSp.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy); + + // Save the operation + this.currentOperation = operation; + + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + + return operationRequest; + case "VFC": + this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.eventManager.getVnfResponse()); + this.currentOperation = operation; + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + return operationRequest; + default: + throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy"); + } + } + + /** + * Handle a response. + * + * @param response the response + * @return a PolicyResult + */ + public PolicyResult onResponse(Object response) { + // + // Which response is it? + // + if (response instanceof Response) { + // + // Cast APPC response and handle it + // + return onResponse((Response) response); + } else if (response instanceof LCMResponseWrapper) { + // + // Cast LCM response and handle it + // + return onResponse((LCMResponseWrapper) response); + } else if (response instanceof SOResponseWrapper) { + // + // Cast SO response and handle it + // + return onResponse((SOResponseWrapper) response); + } else if (response instanceof VFCResponse) { + // + // Cast VFC response and handle it + // + return onResponse((VFCResponse) response); + } else { + return null; + } + } + + /** + * This method handles operation responses from APPC. + * + * @param appcResponse the APPC response + * @return The result of the response handling + */ + private PolicyResult onResponse(Response appcResponse) { + // + // Determine which subrequestID (ie. attempt) + // + Integer operationAttempt = null; + try { + operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestID()); + } catch (NumberFormatException e) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", + PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Sanity check the response message + // + if (appcResponse.getStatus() == null) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, + "Policy was unable to parse APP-C response status field (it was null).", + PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode()); + if (code == null) { + // + // We are unaware of this code + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", + PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + // + // This is good, they got our original message and + // acknowledged it. + // + // Is there any need to track this? + // + return null; + case ERROR: + case REJECT: + // + // We'll consider these two codes as exceptions + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), + PolicyResult.FAILURE_EXCEPTION); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE_EXCEPTION; + case SUCCESS: + // + // + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), + PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + case FAILURE: + // + // + // + this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), + PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE; + default: + return null; + } + } + + /** + * This method handles operation responses from LCM. + * + * @param dmaapResponse the LCM response + * @return The result of the response handling + */ + private PolicyResult onResponse(LCMResponseWrapper dmaapResponse) { + /* + * Parse out the operation attempt using the subrequestid + */ + Integer operationAttempt = AppcLcmActorServiceProvider + .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId()); + if (operationAttempt == null) { + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", + PolicyResult.FAILURE_EXCEPTION); + } + + /* + * Process the APPCLCM response to see what PolicyResult should be returned + */ + AbstractMap.SimpleEntry result = + AppcLcmActorServiceProvider.processResponse(dmaapResponse); + + if (result.getKey() != null) { + this.completeOperation(operationAttempt, result.getValue(), result.getKey()); + if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { + return null; + } + return result.getKey(); + } + return null; + } + + /** + * This method handles operation responses from SO. + * + * @param msoResponse the SO response + * @return The result of the response handling + */ + private PolicyResult onResponse(SOResponseWrapper msoResponse) { + switch (msoResponse.getSoResponse().getHttpResponseCode()) { + case 200: + case 202: + // + // Consider it as success + // + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success", + PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + default: + // + // Consider it as failure + // + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed", + PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE; + } + } + + /** + * This method handles operation responses from VFC. + * + * @param vfcResponse the VFC response + * @return The result of the response handling + */ + private PolicyResult onResponse(VFCResponse vfcResponse) { + if (vfcResponse.getResponseDescriptor().getStatus().equalsIgnoreCase("finished")) { + // + // Consider it as success + // + this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + } else { + // + // Consider it as failure + // + this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + // increment operation attempts for retries + this.attempts += 1; + return PolicyResult.FAILURE; + } + } + + /** + * Get the operation timeout. + * + * @return the timeout + */ + public Integer getOperationTimeout() { + // + // Sanity check + // + if (this.policy == null) { + logger.debug("getOperationTimeout returning 0"); + return 0; + } + logger.debug("getOperationTimeout returning {}", this.policy.getTimeout()); + return this.policy.getTimeout(); + } + + /** + * Get the operation timeout as a String. + * + * @param defaultTimeout the default timeout + * @return the timeout as a String + */ + public String getOperationTimeoutString(int defaultTimeout) { + Integer to = this.getOperationTimeout(); + if (to == null || to == 0) { + return Integer.toString(defaultTimeout) + "s"; + } + return to.toString() + "s"; + } + + public PolicyResult getOperationResult() { + return this.policyResult; + } + + /** + * Get the operation as a message. + * + * @return the operation as a message + */ + public String getOperationMessage() { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toMessage(); + } + + if (!this.operationHistory.isEmpty()) { + return this.operationHistory.getLast().clOperation.toMessage(); + } + return null; + } + + /** + * Get the operation as a message including the guard result. + * + * @param guardResult the guard result + * @return the operation as a message including the guard result + */ + public String getOperationMessage(String guardResult) { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult; + } + + if (!this.operationHistory.isEmpty()) { + return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult; + } + return null; + } + + /** + * Get the operation history. + * + * @return the operation history + */ + public String getOperationHistory() { + if (this.currentOperation != null && this.currentOperation.clOperation != null) { + return this.currentOperation.clOperation.toHistory(); + } + + if (!this.operationHistory.isEmpty()) { + return this.operationHistory.getLast().clOperation.toHistory(); + } + return null; + } + + /** + * Get the history. + * + * @return the list of control loop operations + */ + public List getHistory() { + LinkedList history = new LinkedList<>(); + for (Operation op : this.operationHistory) { + history.add(new ControlLoopOperation(op.clOperation)); + + } + return history; + } + + /** + * Set the operation has timed out. + */ + public void setOperationHasTimedOut() { + // + // + // + this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT); + } + + /** + * Set the operation has been denied by guard. + */ + public void setOperationHasGuardDeny() { + // + // + // + this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD); + } + + public void setOperationHasException(String message) { + this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION); + } + + /** + * Is the operation complete. + * + * @return true if the operation is complete, false otherwise + */ + public boolean isOperationComplete() { + // + // Is there currently a result? + // + if (this.policyResult == null) { + // + // either we are in process or we + // haven't started + // + return false; + } + // + // We have some result, check if the operation failed + // + if (this.policyResult.equals(PolicyResult.FAILURE)) { + // + // Check if there were no retries specified + // + if (policy.getRetry() == null || policy.getRetry() == 0) { + // + // The result is the failure + // + return true; + } + // + // Check retries + // + if (this.isRetriesMaxedOut()) { + // + // No more attempts allowed, reset + // that our actual result is failure due to retries + // + this.policyResult = PolicyResult.FAILURE_RETRIES; + return true; + } else { + // + // There are more attempts available to try the + // policy recipe. + // + return false; + } + } + // + // Other results mean we are done + // + return true; + } + + public boolean isOperationRunning() { + return (this.currentOperation != null); + } + + /** + * This method verifies that the operation manager may run an operation. + * + * @return True if the operation can run, false otherwise + * @throws ControlLoopException if the operation cannot run + */ + private void verifyOperatonCanRun() throws ControlLoopException { + // + // They shouldn't call us if we currently running something + // + if (this.currentOperation != null) { + // + // what do we do if we are already running an operation? + // + throw new ControlLoopException("current operation is not null (an operation is already running)"); + } + // + // Check if we have maxed out on retries + // + if (this.policy.getRetry() == null || this.policy.getRetry() < 1) { + // + // No retries are allowed, so check have we even made + // one attempt to execute the operation? + // + if (this.attempts >= 1) { + // + // We have, let's ensure our PolicyResult is set + // + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + // + // + // + throw new ControlLoopException("current operation failed and retries are not allowed"); + } + } else { + // + // Have we maxed out on retries? + // + if (this.attempts > this.policy.getRetry()) { + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries"); + } + } + + return; + } + + private boolean isRetriesMaxedOut() { + if (policy.getRetry() == null || policy.getRetry() == 0) { + // + // There were NO retries specified, so declare + // this as completed. + // + return (this.attempts > 0); + } + return (this.attempts > policy.getRetry()); + } + + private void storeOperationInDataBase() { + // Only store in DB if enabled + boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled")); + if (!guardEnabled) { + return; + } + + + // DB Properties + Properties props = new Properties(); + if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null + && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null + && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) { + props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); + props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); + props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); + props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader()); + } + + + String opsHistPu = System.getProperty("OperationsHistoryPU"); + if (opsHistPu == null || !opsHistPu.equals("TestOperationsHistoryPU")) { + opsHistPu = "OperationsHistoryPU"; + } else { + props.clear(); + } + EntityManager em; + try { + em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager(); + } catch (Exception e) { + logger.error("storeOperationInDataBase threw: ", e); + return; + } + + OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry(); + + newEntry.setClosedLoopName(this.onset.getClosedLoopControlName()); + newEntry.setRequestId(this.onset.getRequestID().toString()); + newEntry.setActor(this.currentOperation.clOperation.getActor()); + newEntry.setOperation(this.currentOperation.clOperation.getOperation()); + newEntry.setTarget(this.targetEntity); + newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart())); + newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId()); + newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli())); + newEntry.setMessage(this.currentOperation.clOperation.getMessage()); + newEntry.setOutcome(this.currentOperation.clOperation.getOutcome()); + + em.getTransaction().begin(); + em.persist(newEntry); + em.getTransaction().commit(); + + em.close(); + } + + private void completeOperation(Integer attempt, String message, PolicyResult result) { + if (attempt == null) { + logger.debug("attempt cannot be null (i.e. subRequestID)"); + return; + } + if (this.currentOperation != null) { + if (this.currentOperation.attempt == attempt.intValue()) { + this.currentOperation.clOperation.setEnd(Instant.now()); + this.currentOperation.clOperation.setMessage(message); + this.currentOperation.clOperation.setOutcome(result.toString()); + this.currentOperation.policyResult = result; + // + // Save it in history + // + this.operationHistory.add(this.currentOperation); + this.storeOperationInDataBase(); + // + // Set our last result + // + this.policyResult = result; + // + // Clear the current operation field + // + this.currentOperation = null; + return; + } + logger.debug("not current"); + } + for (Operation op : this.operationHistory) { + if (op.attempt == attempt.intValue()) { + op.clOperation.setEnd(Instant.now()); + op.clOperation.setMessage(message); + op.clOperation.setOutcome(result.toString()); + op.policyResult = result; + return; + } + } + logger.debug("Could not find associated operation"); + + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java index 30273d377..002f39119 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -30,92 +30,115 @@ import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(name="operationshistory10") +@Table(name = "operationshistory10") public class OperationsHistoryDbEntry implements Serializable { - private static final long serialVersionUID = 1L; - - @Id@GeneratedValue - @Column(name="ROWID") - public long rowid; - - @Column(name="CLNAME") - private String closedLoopName; - - private String requestId; - private String actor; - private String operation; - private String target; - private Timestamp starttime; - private Timestamp endtime; - private String subrequestId; - private String outcome; - private String message; - public long getRowid() { - return rowid; - } - public void setRowid(long rowid) { - this.rowid = rowid; - } - public String getClosedLoopName() { - return closedLoopName; - } - public void setClosedLoopName(String closedLoopName) { - this.closedLoopName = closedLoopName; - } - public String getRequestId() { - return requestId; - } - public void setRequestId(String requestId) { - this.requestId = requestId; - } - public String getActor() { - return actor; - } - public void setActor(String actor) { - this.actor = actor; - } - public String getOperation() { - return operation; - } - public void setOperation(String operation) { - this.operation = operation; - } - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - public Timestamp getStarttime() { - return starttime; - } - public void setStarttime(Timestamp starttime) { - this.starttime = starttime; - } - public Timestamp getEndtime() { - return endtime; - } - public void setEndtime(Timestamp endtime) { - this.endtime = endtime; - } - public String getSubrequestId() { - return subrequestId; - } - public void setSubrequestId(String subrequestId) { - this.subrequestId = subrequestId; - } - public String getOutcome() { - return outcome; - } - public void setOutcome(String outcome) { - this.outcome = outcome; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + @Column(name = "ROWID") + public long rowid; + + @Column(name = "CLNAME") + private String closedLoopName; + + private String requestId; + private String actor; + private String operation; + private String target; + private Timestamp starttime; + private Timestamp endtime; + private String subrequestId; + private String outcome; + private String message; + + public long getRowid() { + return rowid; + } + + public void setRowid(long rowid) { + this.rowid = rowid; + } + + public String getClosedLoopName() { + return closedLoopName; + } + + public void setClosedLoopName(String closedLoopName) { + this.closedLoopName = closedLoopName; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public Timestamp getStarttime() { + return starttime; + } + + public void setStarttime(Timestamp starttime) { + this.starttime = starttime; + } + + public Timestamp getEndtime() { + return endtime; + } + + public void setEndtime(Timestamp endtime) { + this.endtime = endtime; + } + + public String getSubrequestId() { + return subrequestId; + } + + public void setSubrequestId(String subrequestId) { + this.subrequestId = subrequestId; + } + + public String getOutcome() { + return outcome; + } + + public void setOutcome(String outcome) { + this.outcome = outcome; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java index 33042a915..fbff87fdd 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -24,23 +24,23 @@ package org.onap.policy.controlloop.impl; import org.onap.policy.controlloop.ControlLoopLogger; public class ControlLoopLoggerStdOutImpl implements ControlLoopLogger { - @Override - public void info(String... parameters) { - StringBuilder builder = new StringBuilder(); - for (String param : parameters) { - builder.append(param); - builder.append(" " ); - } - System.out.println(builder.toString().trim()); - } + @Override + public void info(String... parameters) { + StringBuilder builder = new StringBuilder(); + for (String param : parameters) { + builder.append(param); + builder.append(" "); + } + System.out.println(builder.toString().trim()); + } - @Override - public void metrics(String... msgs) { - this.info(msgs); - } + @Override + public void metrics(String... msgs) { + this.info(msgs); + } - @Override - public void metrics(Object obj) { - this.info(obj.toString()); - } + @Override + public void metrics(Object obj) { + this.info(obj.toString()); + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java index eb50ac36e..13f52e36e 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -23,8 +23,9 @@ package org.onap.policy.controlloop.impl; import org.onap.policy.controlloop.ControlLoopPublisher; public class ControlLoopPublisherJUnitImpl implements ControlLoopPublisher { - @Override - public void publish(Object object) { - throw new UnsupportedOperationException("publish() method is not implemented on " + this.getClass().getCanonicalName()); - } + @Override + public void publish(Object object) { + throw new UnsupportedOperationException( + "publish() method is not implemented on " + this.getClass().getCanonicalName()); + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java index 451244392..3dbc25fcf 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * controlloop processor * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -31,76 +31,96 @@ import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor; public class ControlLoopProcessor { - private final String yaml; - private final ControlLoopPolicy policy; - private String currentNestedPolicyID = null; + private final String yaml; + private final ControlLoopPolicy policy; + private String currentNestedPolicyId = null; - public ControlLoopProcessor(String yaml) throws ControlLoopException { - this.yaml = yaml; - try { - final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class, ControlLoopPolicy.class.getClassLoader())); - final Object obj = y.load(this.yaml); + /** + * Construct an instance from yaml. + * + * @param yaml the yaml + * @throws ControlLoopException if an error occurs + */ + public ControlLoopProcessor(String yaml) throws ControlLoopException { + this.yaml = yaml; + try { + final Yaml y = new Yaml(new CustomClassLoaderConstructor(ControlLoopPolicy.class, + ControlLoopPolicy.class.getClassLoader())); + final Object obj = y.load(this.yaml); - this.policy = (ControlLoopPolicy) obj; - this.currentNestedPolicyID = this.policy.getControlLoop().getTrigger_policy(); - } catch (final Exception e) { - // - // Most likely this is a YAML Exception - // - throw new ControlLoopException(e); - } - } + this.policy = (ControlLoopPolicy) obj; + this.currentNestedPolicyId = this.policy.getControlLoop().getTrigger_policy(); + } catch (final Exception e) { + // + // Most likely this is a YAML Exception + // + throw new ControlLoopException(e); + } + } - public ControlLoop getControlLoop() { - return this.policy.getControlLoop(); - } + public ControlLoop getControlLoop() { + return this.policy.getControlLoop(); + } - public FinalResult checkIsCurrentPolicyFinal() { - return FinalResult.toResult(this.currentNestedPolicyID); - } + public FinalResult checkIsCurrentPolicyFinal() { + return FinalResult.toResult(this.currentNestedPolicyId); + } - public Policy getCurrentPolicy() throws ControlLoopException { - if (this.policy == null || this.policy.getPolicies() == null) { - throw new ControlLoopException("There are no policies defined."); - } + /** + * Get the current policy. + * + * @return the current policy + * @throws ControlLoopException if an error occurs + */ + public Policy getCurrentPolicy() throws ControlLoopException { + if (this.policy == null || this.policy.getPolicies() == null) { + throw new ControlLoopException("There are no policies defined."); + } - for (final Policy nestedPolicy : this.policy.getPolicies()) { - if (nestedPolicy.getId().equals(this.currentNestedPolicyID)) { - return nestedPolicy; - } - } - return null; - } + for (final Policy nestedPolicy : this.policy.getPolicies()) { + if (nestedPolicy.getId().equals(this.currentNestedPolicyId)) { + return nestedPolicy; + } + } + return null; + } - public void nextPolicyForResult(PolicyResult result) throws ControlLoopException { - final Policy currentPolicy = this.getCurrentPolicy(); - try { - if (currentPolicy == null) { - throw new ControlLoopException("There is no current policy to determine where to go to."); - } - switch (result) { - case SUCCESS: - this.currentNestedPolicyID = currentPolicy.getSuccess(); - break; - case FAILURE: - this.currentNestedPolicyID = currentPolicy.getFailure(); - break; - case FAILURE_TIMEOUT: - this.currentNestedPolicyID = currentPolicy.getFailure_timeout(); - break; - case FAILURE_RETRIES: - this.currentNestedPolicyID = currentPolicy.getFailure_retries(); - break; - case FAILURE_EXCEPTION: - this.currentNestedPolicyID = currentPolicy.getFailure_exception(); - break; - case FAILURE_GUARD: - this.currentNestedPolicyID = currentPolicy.getFailure_guard(); - break; - } - } catch (final ControlLoopException e) { - this.currentNestedPolicyID = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - throw e; - } - } + /** + * Get the next policy given a result of the current policy. + * + * @param result the result of the current policy + * @throws ControlLoopException if an error occurs + */ + public void nextPolicyForResult(PolicyResult result) throws ControlLoopException { + final Policy currentPolicy = this.getCurrentPolicy(); + try { + if (currentPolicy == null) { + throw new ControlLoopException("There is no current policy to determine where to go to."); + } + switch (result) { + case SUCCESS: + this.currentNestedPolicyId = currentPolicy.getSuccess(); + break; + case FAILURE: + this.currentNestedPolicyId = currentPolicy.getFailure(); + break; + case FAILURE_TIMEOUT: + this.currentNestedPolicyId = currentPolicy.getFailure_timeout(); + break; + case FAILURE_RETRIES: + this.currentNestedPolicyId = currentPolicy.getFailure_retries(); + break; + case FAILURE_EXCEPTION: + this.currentNestedPolicyId = currentPolicy.getFailure_exception(); + break; + case FAILURE_GUARD: + default: + this.currentNestedPolicyId = currentPolicy.getFailure_guard(); + break; + } + } catch (final ControlLoopException e) { + this.currentNestedPolicyId = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + throw e; + } + } } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java index 7acaf370d..3bf364ea4 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,8 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.drools; public interface PolicyEngine { - public boolean deliver(String busType, String topic, Object obj); + public boolean deliver(String busType, String topic, Object obj); } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java index 5bd5d8d2c..419c31094 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,14 +20,13 @@ package org.onap.policy.drools; +@FunctionalInterface public interface PolicyEngineListener { /** - * Any class that implements this interface will - * be notified of a new event on the queue in the - * PolicyEngineJUnitImpl + * Any class that implements this interface will be notified of a new event on the queue in the + * PolicyEngineJUnitImpl. * - * @param topic a key to the queue that contains - * the event + * @param topic a key to the queue that contains the event */ public void newEventNotification(String topic); } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java index e94657fee..d5f73c741 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -31,111 +31,118 @@ import org.onap.policy.appc.Request; import org.onap.policy.appclcm.LCMRequestWrapper; import org.onap.policy.controlloop.ControlLoopNotification; import org.onap.policy.controlloop.util.Serialization; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.onap.policy.drools.PolicyEngine; import org.onap.policy.drools.PolicyEngineListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class PolicyEngineJUnitImpl implements PolicyEngine { - private static final Logger logger = LoggerFactory.getLogger(PolicyEngineJUnitImpl.class); - private Map>> busMap = new HashMap<>(); - private List listeners = new ArrayList<>(); + private static final Logger logger = LoggerFactory.getLogger(PolicyEngineJUnitImpl.class); + private Map>> busMap = new HashMap<>(); + private List listeners = new ArrayList<>(); - /** - * Adds all objects that implement PolicyEngineListener - * to the notification list when an event occurs - * - * @param listener an object that is interest in knowing - * about events published to the PolicyEngine - */ - public void addListener(PolicyEngineListener listener) { - listeners.add(listener); - } + /** + * Adds all objects that implement PolicyEngineListener to the notification list when an event + * occurs. + * + * @param listener an object that is interest in knowing about events published to the + * PolicyEngine + */ + public void addListener(PolicyEngineListener listener) { + listeners.add(listener); + } - /** - * Notifies all listeners about a new event - * @param topic the topic in which the notification - * was sent to - */ - public void notifyListeners(String topic) { - for (PolicyEngineListener listener: listeners) { - listener.newEventNotification(topic); - } - } + /** + * Notifies all listeners about a new event. + * + * @param topic the topic in which the notification was sent to + */ + public void notifyListeners(String topic) { + for (PolicyEngineListener listener : listeners) { + listener.newEventNotification(topic); + } + } - @Override - public boolean deliver(String busType, String topic, Object obj) { - if (obj instanceof ControlLoopNotification) { - ControlLoopNotification notification = (ControlLoopNotification) obj; - if (logger.isDebugEnabled()) { - logger.debug(Serialization.gsonPretty.toJson(notification)); - } - } - if (obj instanceof Request) { - Request request = (Request) obj; - logger.debug("Request: {} subrequest {}", request.getAction(), request.getCommonHeader().getSubRequestID()); - } - else if (obj instanceof LCMRequestWrapper) { - LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj; - logger.debug("Request: {} subrequest {}", dmaapRequest.getBody().getAction(), dmaapRequest.getBody().getCommonHeader().getSubRequestId()); - } - // - // Does the bus exist? - // - if (!busMap.containsKey(busType)) { - logger.debug("creating new bus type {}", busType); - // - // Create the bus - // - busMap.put(busType, new HashMap<>()); - } - // - // Get the bus - // - Map> topicMap = busMap.get(busType); - // - // Does the topic exist? - // - if (!topicMap.containsKey(topic)) { - logger.debug("creating new topic {}", topic); - // - // Create the topic - // - topicMap.put(topic, new LinkedList<>()); - } - // - // Get the topic queue - // - logger.debug("queueing"); - boolean res = topicMap.get(topic).add(obj); - notifyListeners(topic); - return res; - } + @Override + public boolean deliver(String busType, String topic, Object obj) { + if (obj instanceof ControlLoopNotification) { + ControlLoopNotification notification = (ControlLoopNotification) obj; + if (logger.isDebugEnabled()) { + logger.debug(Serialization.gsonPretty.toJson(notification)); + } + } + if (obj instanceof Request) { + Request request = (Request) obj; + logger.debug("Request: {} subrequest {}", request.getAction(), request.getCommonHeader().getSubRequestID()); + } else if (obj instanceof LCMRequestWrapper) { + LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj; + logger.debug("Request: {} subrequest {}", dmaapRequest.getBody().getAction(), + dmaapRequest.getBody().getCommonHeader().getSubRequestId()); + } + // + // Does the bus exist? + // + if (!busMap.containsKey(busType)) { + logger.debug("creating new bus type {}", busType); + // + // Create the bus + // + busMap.put(busType, new HashMap<>()); + } + // + // Get the bus + // + Map> topicMap = busMap.get(busType); + // + // Does the topic exist? + // + if (!topicMap.containsKey(topic)) { + logger.debug("creating new topic {}", topic); + // + // Create the topic + // + topicMap.put(topic, new LinkedList<>()); + } + // + // Get the topic queue + // + logger.debug("queueing"); + boolean res = topicMap.get(topic).add(obj); + notifyListeners(topic); + return res; + } - public Object subscribe(String busType, String topic) { - // - // Does the bus exist? - // - if (busMap.containsKey(busType)) { - // - // Get the bus - // - Map> topicMap = busMap.get(busType); - // - // Does the topic exist? - // - if (topicMap.containsKey(topic)) { - logger.debug("The queue has {}", topicMap.get(topic).size()); - return topicMap.get(topic).poll(); - } else { - logger.error("No topic exists {}", topic); - } - } else { - logger.error("No bus exists {}", busType); - } - return null; - } + /** + * Subscribe to a topic on a bus. + * + * @param busType the bus type + * @param topic the topic + * @return the head of the queue, or null if the queue or bus does not exist or the + * queue is empty + */ + public Object subscribe(String busType, String topic) { + // + // Does the bus exist? + // + if (busMap.containsKey(busType)) { + // + // Get the bus + // + Map> topicMap = busMap.get(busType); + // + // Does the topic exist? + // + if (topicMap.containsKey(topic)) { + logger.debug("The queue has {}", topicMap.get(topic).size()); + return topicMap.get(topic).poll(); + } else { + logger.error("No topic exists {}", topic); + } + } else { + logger.error("No bus exists {}", busType); + } + return null; + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java index 58860435a..f06ea34dc 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java @@ -20,7 +20,7 @@ package org.onap.policy.controlloop; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.io.IOException; @@ -28,12 +28,12 @@ import org.junit.Test; public class ControlLoopExceptionTest { - @Test - public void testControlLoopException() { - assertNotNull(new ControlLoopException()); - assertNotNull(new ControlLoopException("In Oz")); - assertNotNull(new ControlLoopException(new IOException())); - assertNotNull(new ControlLoopException("In Oz", new IOException())); - assertNotNull(new ControlLoopException("In Oz", new IOException(), false, false)); - } + @Test + public void testControlLoopException() { + assertNotNull(new ControlLoopException()); + assertNotNull(new ControlLoopException("In Oz")); + assertNotNull(new ControlLoopException(new IOException())); + assertNotNull(new ControlLoopException("In Oz", new IOException())); + assertNotNull(new ControlLoopException("In Oz", new IOException(), false, false)); + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java index 25208fe32..6c5264e1c 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java @@ -25,25 +25,23 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopLogger; import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl; public class ControlLoopLoggerTest { - @Test - public void testControlLoopLogger() throws ControlLoopException { - ControlLoopLogger logger = new ControlLoopLogger.Factory().buildLogger(ControlLoopLoggerStdOutImpl.class.getCanonicalName()); - assertNotNull(logger); - logger.info("a log message", "and another", " and another"); - logger.metrics("a metric", "and another", " and another"); - logger.metrics(Double.valueOf(3)); + @Test + public void testControlLoopLogger() throws ControlLoopException { + ControlLoopLogger logger = + new ControlLoopLogger.Factory().buildLogger(ControlLoopLoggerStdOutImpl.class.getCanonicalName()); + assertNotNull(logger); + logger.info("a log message", "and another", " and another"); + logger.metrics("a metric", "and another", " and another"); + logger.metrics(Double.valueOf(3)); - try { - new ControlLoopLogger.Factory().buildLogger("java.lang.String"); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("Cannot load class java.lang.String as a control loop logger", e.getMessage()); - } - } + try { + new ControlLoopLogger.Factory().buildLogger("java.lang.String"); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Cannot load class java.lang.String as a control loop logger", e.getMessage()); + } + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java index 3548ab841..309aeb206 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java @@ -25,29 +25,28 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; -import org.onap.policy.controlloop.ControlLoopException; import org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl; public class ControlLoopPublisherTest { - @Test - public void testControlLoopPublisher() throws ControlLoopException { - ControlLoopPublisher publisher = new ControlLoopPublisher.Factory().buildLogger(ControlLoopPublisherJUnitImpl.class.getCanonicalName()); - assertNotNull(publisher); + @Test + public void testControlLoopPublisher() throws ControlLoopException { + ControlLoopPublisher publisher = + new ControlLoopPublisher.Factory().buildLogger(ControlLoopPublisherJUnitImpl.class.getCanonicalName()); + assertNotNull(publisher); - try { - publisher.publish(Double.valueOf(3)); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("publish() method is not implemented on org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl", e.getMessage()); - } + try { + publisher.publish(Double.valueOf(3)); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("publish() method is not implemented on " + + "org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl", e.getMessage()); + } - try { - new ControlLoopPublisher.Factory().buildLogger("java.lang.String"); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("Cannot load class java.lang.String as a control loop publisher", e.getMessage()); - } - } + try { + new ControlLoopPublisher.Factory().buildLogger("java.lang.String"); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Cannot load class java.lang.String as a control loop publisher", e.getMessage()); + } + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java index bf44a8026..ced419a04 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * util * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -24,44 +24,46 @@ import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; - public final class Util { - public static class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - public static Pair loadYaml(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(contents); - return new Pair((ControlLoopPolicy) obj, contents); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - return null; - } + public static class Pair { + public final A key; + public final B value; + + public Pair(A key, B value) { + this.key = key; + this.value = value; + } + } + + /** + * Load yaml into a Pair object. + * + * @param testFile the yaml file + * @return a Pair + */ + public static Pair loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + return new Pair((ControlLoopPolicy) obj, contents); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java index 1df4a4f27..ea057c9d9 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * unit test * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -67,936 +67,983 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopEventManagerTest { - private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManagerTest.class); - - private static VirtualControlLoopEvent onset; - static { - onset = new VirtualControlLoopEvent(); - onset.setClosedLoopControlName("ControlLoop-vUSP"); - onset.setRequestID(UUID.randomUUID()); - onset.setTarget("VM_NAME"); - onset.setClosedLoopAlarmStart(Instant.now()); - onset.setAAI(new HashMap()); - onset.getAAI().put("cloud-region.identity-url", "foo"); - onset.getAAI().put("vserver.selflink", "bar"); - onset.getAAI().put("generic-vnf.vnf-id", "83f674e8-7555-44d7-9a39-bdc3770b0491"); - onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - } - - @BeforeClass - public static void setUpSimulator() { - try { - org.onap.policy.simulators.Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testAAIVnfInfo() { - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - try { - AAIGETVnfResponse response = getQueryByVnfID2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf/", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "5e49ca06-2972-4532-9ed4-6d071588d792"); - assertNotNull(response); - logger.info("testAAIVnfInfo test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVnfInfo Exception: ", e); - fail(e.getMessage()); - } - } - - @Test - public void testAAIVnfInfo2() { - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - try { - AAIGETVnfResponse response = getQueryByVnfName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "lll_vnf_010317"); - assertNotNull(response); - logger.info("testAAIVnfInfo2 test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVnfInfo2 Exception: ", e); - fail(e.getMessage()); - } - } - - @Test - public void testAAIVserver() { - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - try { - AAIGETVserverResponse response = getQueryByVserverName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "USMSO1SX7NJ0103UJZZ01-vjunos0"); - assertNotNull(response); - logger.info("testAAIVserver test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVserver Exception: ", e); - fail(e.getMessage()); - } - } - - @Test - public void testIsClosedLoopDisabled() { - // - // Load up the policy - // - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - - try { - logger.info("testIsClosedLoopDisabled --"); - AAIGETVnfResponse response = getQueryByVnfID2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf/", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "5e49ca06-2972-4532-9ed4-6d071588d792"); - assertNotNull(response); - - // TODO: Handle this - //boolean disabled = ControlLoopEventManager.isClosedLoopDisabled(response); - //logger.info("QueryByVnfID - isClosedLoopDisabled: " + disabled); - - response = getQueryByVnfName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "lll_vnf_010317"); - assertNotNull(response); - // TODO: Handle this - //disabled = ControlLoopEventManager.isClosedLoopDisabled(response); - //logger.info("QueryByVnfName - isClosedLoopDisabled: " + disabled); - - AAIGETVserverResponse response2 = getQueryByVserverName2(PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.user"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), - UUID.randomUUID(), "USMSO1SX7NJ0103UJZZ01-vjunos0"); - assertNotNull(response2); - // TODO: Handle this - //disabled = ControlLoopEventManager.isClosedLoopDisabled(response2); - //logger.info("QueryByVserverName - isClosedLoopDisabled: " + disabled); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void abatemetCheckEventSyntaxTest() { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("abatementAAI"); - event.setRequestID(UUID.randomUUID()); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); - try { - manager.checkEventSyntax(event); - } catch (ControlLoopException e) { - logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: "+e.getMessage()); - e.printStackTrace(); - fail("Exception in check event syntax"); - } - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); - - - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "abatementTest"); - try { - manager.checkEventSyntax(event); - } catch (ControlLoopException e) { - logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: "+e.getMessage()); - e.printStackTrace(); - fail("Exception in check event syntax"); - } - assertNull(manager.getVnfResponse()); - assertNull(manager.getVserverResponse()); - } - - @Test - public void subsequentOnsetTest() { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(event); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = manager.onNewEvent(event); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - - AAIGETVnfResponse response = manager.getVnfResponse(); - assertNotNull(response); - assertNull(manager.getVserverResponse()); - - VirtualControlLoopEvent event2 = new VirtualControlLoopEvent(); - event2.setClosedLoopControlName("TwoOnsetTest"); - event2.setRequestID(requestId); - event2.setTarget("generic-vnf.vnf-id"); - event2.setClosedLoopAlarmStart(Instant.now()); - event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event2.setAAI(new HashMap<>()); - event2.getAAI().put("generic-vnf.vnf-name", "onsetTwo"); - - - try { - status = manager.onNewEvent(event2); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.SUBSEQUENT_ONSET, status); - AAIGETVnfResponse response2 = manager.getVnfResponse(); - assertNotNull(response2); - // We should not have queried AAI, so the stored response should be the same - assertEquals(response, response2); - assertNull(manager.getVserverResponse()); - } - - // Simulate a response - public static AAIGETVnfResponse getQueryByVnfID2(String urlGet, String username, String password, UUID requestID, String key) { - AAIGETVnfResponse response = new AAIGETVnfResponse(); - - response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); - response.setVnfName("lll_vnf_010317"); - response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); - response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); - response.setOrchestrationStatus("Created"); - response.setInMaint("false"); - response.setIsClosedLoopDisabled("false"); - response.setResourceVersion("1494001988835"); - response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey ("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey ("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey ("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); - - return response; - } - - public static AAIGETVnfResponse getQueryByVnfName2(String urlGet, String username, String password, UUID requestID, String key) { - AAIGETVnfResponse response = new AAIGETVnfResponse(); - - response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); - response.setVnfName("lll_vnf_010317"); - response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); - response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); - response.setOrchestrationStatus("Created"); - response.setInMaint("false"); - response.setIsClosedLoopDisabled("false"); - response.setResourceVersion("1494001988835"); - response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); - - return response; - } - - public static AAIGETVserverResponse getQueryByVserverName2(String urlGet, String username, String password, UUID requestID, String key) { - AAIGETVserverResponse response = new AAIGETVserverResponse(); - - response.setVserverID("d0668d4f-c25e-4a1b-87c4-83845c01efd8"); - response.setVserverName("USMSO1SX7NJ0103UJZZ01-vjunos0"); - response.setVserverName2("vjunos0"); - response.setVserverSelflink("https://aai-ext1.test.att.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USMSO1SX7NJ0103UJZZ01%3A%3AuCPE-VMS/vservers/vserver/d0668d4f-c25e-4a1b-87c4-83845c01efd8"); - response.setInMaint("false"); - response.setIsClosedLoopDisabled("false"); - response.setResourceVersion("1494001931513"); - - RelationshipList relationshipList = new RelationshipList(); - Relationship relationship = new Relationship(); - RelationshipData relationshipData = new RelationshipData(); - RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); - - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationshipData.getRelationshipData().add(relationshipDataItem); - - RelatedToProperty relatedToProperty = new RelatedToProperty(); - RelatedToPropertyItem item = new RelatedToPropertyItem(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); - relatedToProperty.getRelatedTo().add(item); - - relationship.setRelatedTo("service-instance"); - relationship.setRelatedLink("/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); - relationship.setRelationshipData(relationshipData); - relationship.setRelatedToProperty(relatedToProperty); - - relationshipList.getRelationshipList().add(relationship); - response.setRelationshipList(relationshipList); - - return response; - } - - @Test - public void testMethods() { - ControlLoopEventManager clem = new ControlLoopEventManager("MyClosedLoopName", UUID.randomUUID()); - - clem.setActivated(true); - assertEquals(true, clem.isActivated()); - - clem.setControlLoopResult("SUCCESS"); - assertEquals("SUCCESS", clem.getControlLoopResult()); - - clem.setControlLoopTimedOut(); - assertEquals(true, clem.isControlLoopTimedOut()); - - clem.setNumAbatements(12345); - assertEquals(Integer.valueOf(12345), clem.getNumAbatements()); - - clem.setNumOnsets(54321); - assertEquals(Integer.valueOf(54321), clem.getNumOnsets()); - - assertNull(clem.getOnsetEvent()); - assertNull(clem.getAbatementEvent()); - assertNull(clem.getProcessor()); - - assertEquals(true, clem.isActive()); - assertEquals(false, clem.releaseLock()); - assertEquals(true, clem.isControlLoopTimedOut()); - - assertNull(clem.unlockCurrentOperation()); - } - - @Test - public void testAlreadyActivated() { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - manager.setActivated(true); - VirtualControlLoopNotification notification = manager.activate(event); - assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); - } - - @Test - public void testActivationYaml() throws IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml")); - String yamlStringBad = IOUtils.toString(isBad, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - - // Null YAML should fail - VirtualControlLoopNotification notificationNull = manager.activate(null, event); - assertNotNull(notificationNull); - assertEquals(ControlLoopNotificationType.REJECTED, notificationNull.getNotification()); - - // Empty YAML should fail - VirtualControlLoopNotification notificationEmpty = manager.activate("", event); - assertNotNull(notificationEmpty); - assertEquals(ControlLoopNotificationType.REJECTED, notificationEmpty.getNotification()); - - // Bad YAML should fail - VirtualControlLoopNotification notificationBad = manager.activate(yamlStringBad, event); - assertNotNull(notificationBad); - assertEquals(ControlLoopNotificationType.REJECTED, notificationBad.getNotification()); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - // Another activate should fail - VirtualControlLoopNotification notificationActive = manager.activate(yamlString, event); - assertNotNull(notificationActive); - assertEquals(ControlLoopNotificationType.REJECTED, notificationActive.getNotification()); - } - - @Test - public void testControlLoopFinal() throws ControlLoopException, IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - try { - manager.isControlLoopFinal(); - fail("test should throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); - } - - manager.setActivated(true); - try { - manager.isControlLoopFinal(); - fail("test should throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); - } - - manager.setActivated(false); - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); - assertNull(clfNotification); - - manager.getProcessor().nextPolicyForResult(PolicyResult.SUCCESS); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, clfNotification.getNotification()); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - manager.setControlLoopTimedOut(); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - } - - @Test - public void testProcessControlLoop() throws ControlLoopException, IOException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); - } - - manager.setActivated(true); - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); - } - - manager.setActivated(false); - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - // Test operation in progress - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Already working an Operation, do not call this method.", e.getMessage()); - } - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); - VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - // Test operation completed - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Control Loop is in FINAL state, do not call this method.", e.getMessage()); - } - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE); - - // Test operation with no next policy defined - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is null", e.getMessage()); - } - } - - @Test - public void testFinishOperation() throws IOException, ControlLoopException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - InputStream isStd = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); - event.setRequestID(requestId); - event.setTarget("generic-vnf.vnf-id"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAAI(new HashMap<>()); - event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - try { - manager.finishOperation(null); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No operation to finish.", e.getMessage()); - } - - manager.setActivated(true); - try { - manager.finishOperation(null); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No operation to finish.", e.getMessage()); - } - - manager.setActivated(false); - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - try { - manager.lockCurrentOperation(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Do not have a current operation.", e.getMessage()); - } - - assertNull(manager.unlockCurrentOperation()); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - LockResult lockLock = manager.lockCurrentOperation(); - assertNotNull(lockLock); - - LockResult lockLockAgain = manager.lockCurrentOperation(); - assertNotNull(lockLockAgain); - assertEquals(lockLock.getB(), lockLockAgain.getB()); - - assertEquals(lockLock.getB(), manager.unlockCurrentOperation()); - assertNull(manager.unlockCurrentOperation()); - - lockLock = manager.lockCurrentOperation(); - assertNotNull(lockLock); - PolicyGuard.unlockTarget(lockLock.getB()); - assertNull(manager.unlockCurrentOperation()); - - clom.startOperation(event); - - // This call should be exception free - manager.finishOperation(clom); - - ControlLoopEventManager otherManager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); - VirtualControlLoopNotification otherNotification = otherManager.activate(yamlStringStd, event); - assertNotNull(otherNotification); - assertEquals(ControlLoopNotificationType.ACTIVE, otherNotification.getNotification()); - - ControlLoopOperationManager otherClom = otherManager.processControlLoop(); - assertNotNull(otherClom); - assertNull(otherClom.getOperationResult()); - - otherManager.finishOperation(clom); - } - - @Test - public void testOnNewEvent() throws IOException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent(); - abatedEvent.setClosedLoopControlName("TwoOnsetTest"); - abatedEvent.setRequestID(requestId); - abatedEvent.setTarget("generic-vnf.vnf-id"); - abatedEvent.setClosedLoopAlarmStart(Instant.now()); - abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); - abatedEvent.setAAI(new HashMap<>()); - abatedEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertEquals(NEW_EVENT_STATUS.FIRST_ONSET, manager.onNewEvent(onsetEvent)); - assertEquals(NEW_EVENT_STATUS.FIRST_ABATEMENT, manager.onNewEvent(abatedEvent)); - assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - VirtualControlLoopEvent checkSyntaxEvent = new VirtualControlLoopEvent(); - checkSyntaxEvent.setAAI(null); - checkSyntaxEvent.setClosedLoopAlarmEnd(null); - checkSyntaxEvent.setClosedLoopAlarmStart(null); - checkSyntaxEvent.setClosedLoopControlName(null); - checkSyntaxEvent.setClosedLoopEventClient(null); - checkSyntaxEvent.setClosedLoopEventStatus(null); - checkSyntaxEvent.setFrom(null); - checkSyntaxEvent.setPolicyName(null); - checkSyntaxEvent.setPolicyScope(null); - checkSyntaxEvent.setPolicyVersion(null); - checkSyntaxEvent.setRequestID(null); - checkSyntaxEvent.setTarget(null); - checkSyntaxEvent.setTargetType(null); - checkSyntaxEvent.setVersion(null); - - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName(null); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName(""); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName("TwoOnsetTest"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setRequestID(null); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setRequestID(requestId); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAAI(null); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAAI(new HashMap<>()); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(""); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(null); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(""); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("OZ"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("VM_NAME"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("VNF_NAME"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("vserver.vserver-name"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("generic-vnf.vnf-id"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("generic-vnf.vnf-name"); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAAI(null); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAAI(new HashMap<>()); - assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - checkSyntaxEvent.getAAI().put("vserver.vserver-name", "onsetOne"); - assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - checkSyntaxEvent.getAAI().put("generic-vnf.vnf-id", "onsetOne"); - assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - } - - @Test - public void testControlLoopTimeout() throws IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - assertTrue(0 == manager.getControlLoopTimeout(null)); - assertTrue(120 == manager.getControlLoopTimeout(120)); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertTrue(60 == manager.getControlLoopTimeout(null)); - } - - @Test - public void testQueryAAI() throws IOException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - manager.queryAai(onsetEvent); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "true"); - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); - } - onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "true"); - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); - } - onsetEvent.getAAI().remove("generic-vnf.is-closed-loop-disabled"); - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); - } - onsetEvent.getAAI().remove("vserver.is-closed-loop-disabled"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "false"); - manager.queryAai(onsetEvent); - onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "false"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().remove("generic-vnf.vnf-id"); - onsetEvent.getAAI().remove("generic-vnf.vnf-name"); - onsetEvent.getAAI().remove("vserver.vserver-name"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().put("generic-vnf.vnf-id", "AVNFID"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().remove("vserver.vserver-name"); - manager.queryAai(onsetEvent); - - onsetEvent.getAAI().remove("generic-vnf.vnf-name"); - manager.queryAai(onsetEvent); - - // Force AAI errors - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:9999"); - - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vnf-id)", e.getMessage()); - } - - onsetEvent.getAAI().remove("generic-vnf.vnf-id"); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vnf-name)", e.getMessage()); - } - - onsetEvent.getAAI().remove("generic-vnf.vnf-name"); - onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); - try { - manager.queryAai(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null (query by vserver-name)", e.getMessage()); - } - - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManagerTest.class); + + private static VirtualControlLoopEvent onset; + + { + onset = new VirtualControlLoopEvent(); + onset.setClosedLoopControlName("ControlLoop-vUSP"); + onset.setRequestID(UUID.randomUUID()); + onset.setTarget("VM_NAME"); + onset.setClosedLoopAlarmStart(Instant.now()); + onset.setAAI(new HashMap()); + onset.getAAI().put("cloud-region.identity-url", "foo"); + onset.getAAI().put("vserver.selflink", "bar"); + onset.getAAI().put("generic-vnf.vnf-id", "83f674e8-7555-44d7-9a39-bdc3770b0491"); + onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + } + + /** + * Set up test class. + */ + @BeforeClass + public static void setUpSimulator() { + try { + org.onap.policy.simulators.Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testAaiVnfInfo() { + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + try { + AAIGETVnfResponse response = getQueryByVnfId2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + + "/aai/v11/network/generic-vnfs/generic-vnf/", + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), + "5e49ca06-2972-4532-9ed4-6d071588d792"); + assertNotNull(response); + logger.info("testAAIVnfInfo test result is " + (response == null ? "null" : "not null")); + } catch (Exception e) { + logger.error("testAAIVnfInfo Exception: ", e); + fail(e.getMessage()); + } + } + + @Test + public void testAaiVnfInfo2() { + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + try { + AAIGETVnfResponse response = getQueryByVnfName2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "lll_vnf_010317"); + assertNotNull(response); + logger.info("testAAIVnfInfo2 test result is " + (response == null ? "null" : "not null")); + } catch (Exception e) { + logger.error("testAAIVnfInfo2 Exception: ", e); + fail(e.getMessage()); + } + } + + @Test + public void testAaiVserver() { + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + try { + AAIGETVserverResponse response = getQueryByVserverName2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), + "USMSO1SX7NJ0103UJZZ01-vjunos0"); + assertNotNull(response); + logger.info("testAAIVserver test result is " + (response == null ? "null" : "not null")); + } catch (Exception e) { + logger.error("testAAIVserver Exception: ", e); + fail(e.getMessage()); + } + } + + @Test + public void testIsClosedLoopDisabled() { + // + // Load up the policy + // + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + + try { + logger.info("testIsClosedLoopDisabled --"); + AAIGETVnfResponse response = getQueryByVnfId2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + + "/aai/v11/network/generic-vnfs/generic-vnf/", + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), + "5e49ca06-2972-4532-9ed4-6d071588d792"); + assertNotNull(response); + + // TODO: Handle this + // boolean disabled = ControlLoopEventManager.isClosedLoopDisabled(response); + // logger.info("QueryByVnfID - isClosedLoopDisabled: " + disabled); + + response = getQueryByVnfName2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "lll_vnf_010317"); + assertNotNull(response); + // TODO: Handle this + // disabled = ControlLoopEventManager.isClosedLoopDisabled(response); + // logger.info("QueryByVnfName - isClosedLoopDisabled: " + disabled); + + AAIGETVserverResponse response2 = getQueryByVserverName2( + PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", + PolicyEngine.manager.getEnvironmentProperty("aai.user"), + PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), + "USMSO1SX7NJ0103UJZZ01-vjunos0"); + assertNotNull(response2); + // TODO: Handle this + // disabled = ControlLoopEventManager.isClosedLoopDisabled(response2); + // logger.info("QueryByVserverName - isClosedLoopDisabled: " + disabled); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void abatemetCheckEventSyntaxTest() { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("abatementAAI"); + event.setRequestID(UUID.randomUUID()); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); + try { + manager.checkEventSyntax(event); + } catch (ControlLoopException e) { + logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: " + e.getMessage()); + e.printStackTrace(); + fail("Exception in check event syntax"); + } + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); + + + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "abatementTest"); + try { + manager.checkEventSyntax(event); + } catch (ControlLoopException e) { + logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: " + e.getMessage()); + e.printStackTrace(); + fail("Exception in check event syntax"); + } + assertNull(manager.getVnfResponse()); + assertNull(manager.getVserverResponse()); + } + + @Test + public void subsequentOnsetTest() { + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(event); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NEW_EVENT_STATUS status = null; + try { + status = manager.onNewEvent(event); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + + AAIGETVnfResponse response = manager.getVnfResponse(); + assertNotNull(response); + assertNull(manager.getVserverResponse()); + + VirtualControlLoopEvent event2 = new VirtualControlLoopEvent(); + event2.setClosedLoopControlName("TwoOnsetTest"); + event2.setRequestID(requestId); + event2.setTarget("generic-vnf.vnf-id"); + event2.setClosedLoopAlarmStart(Instant.now()); + event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event2.setAAI(new HashMap<>()); + event2.getAAI().put("generic-vnf.vnf-name", "onsetTwo"); + + + try { + status = manager.onNewEvent(event2); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.SUBSEQUENT_ONSET, status); + AAIGETVnfResponse response2 = manager.getVnfResponse(); + assertNotNull(response2); + // We should not have queried AAI, so the stored response should be the same + assertEquals(response, response2); + assertNull(manager.getVserverResponse()); + } + + /** + * Simulate a response. + */ + public static AAIGETVnfResponse getQueryByVnfId2(String urlGet, String username, String password, UUID requestId, + String key) { + AAIGETVnfResponse response = new AAIGETVnfResponse(); + + response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); + response.setVnfName("lll_vnf_010317"); + response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); + response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); + response.setOrchestrationStatus("Created"); + response.setInMaint("false"); + response.setIsClosedLoopDisabled("false"); + response.setResourceVersion("1494001988835"); + response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); + + final RelationshipList relationshipList = new RelationshipList(); + final Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink( + "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" + + "/MSO-dev-service-type/service-instances/service-instance/" + + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); + + return response; + } + + /** + * Simulate a response. + */ + public static AAIGETVnfResponse getQueryByVnfName2(String urlGet, String username, String password, UUID requestId, + String key) { + AAIGETVnfResponse response = new AAIGETVnfResponse(); + + response.setVnfID("83f674e8-7555-44d7-9a39-bdc3770b0491"); + response.setVnfName("lll_vnf_010317"); + response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); + response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); + response.setOrchestrationStatus("Created"); + response.setInMaint("false"); + response.setIsClosedLoopDisabled("false"); + response.setResourceVersion("1494001988835"); + response.setModelInvariantId("f18be3cd-d446-456e-9109-121d9b62feaa"); + + final RelationshipList relationshipList = new RelationshipList(); + final Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink( + "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" + + "/MSO-dev-service-type/service-instances/service-instance/" + + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); + + return response; + } + + /** + * Simulate a response. + */ + public static AAIGETVserverResponse getQueryByVserverName2(String urlGet, String username, String password, + UUID requestId, String key) { + AAIGETVserverResponse response = new AAIGETVserverResponse(); + + response.setVserverID("d0668d4f-c25e-4a1b-87c4-83845c01efd8"); + response.setVserverName("USMSO1SX7NJ0103UJZZ01-vjunos0"); + response.setVserverName2("vjunos0"); + response.setVserverSelflink( + "https://aai-ext1.test.att.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USMSO1SX7NJ0103UJZZ01%3A%3AuCPE-VMS/vservers/vserver/d0668d4f-c25e-4a1b-87c4-83845c01efd8"); + response.setInMaint("false"); + response.setIsClosedLoopDisabled("false"); + response.setResourceVersion("1494001931513"); + + final RelationshipList relationshipList = new RelationshipList(); + final Relationship relationship = new Relationship(); + RelationshipData relationshipData = new RelationshipData(); + RelationshipDataItem relationshipDataItem = new RelationshipDataItem(); + + relationshipDataItem.setRelationshipKey("customer.global-customer-id"); + relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-subscription.service-type"); + relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); + relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipData.getRelationshipData().add(relationshipDataItem); + + RelatedToProperty relatedToProperty = new RelatedToProperty(); + RelatedToPropertyItem item = new RelatedToPropertyItem(); + item.setPropertyKey("service-instance.service-instance-name"); + item.setPropertyValue("lll_svc_010317"); + relatedToProperty.getRelatedTo().add(item); + + relationship.setRelatedTo("service-instance"); + relationship.setRelatedLink( + "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" + + "/MSO-dev-service-type/service-instances/service-instance/" + + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationship.setRelationshipData(relationshipData); + relationship.setRelatedToProperty(relatedToProperty); + + relationshipList.getRelationshipList().add(relationship); + response.setRelationshipList(relationshipList); + + return response; + } + + @Test + public void testMethods() { + ControlLoopEventManager clem = new ControlLoopEventManager("MyClosedLoopName", UUID.randomUUID()); + + clem.setActivated(true); + assertEquals(true, clem.isActivated()); + + clem.setControlLoopResult("SUCCESS"); + assertEquals("SUCCESS", clem.getControlLoopResult()); + + clem.setControlLoopTimedOut(); + assertEquals(true, clem.isControlLoopTimedOut()); + + clem.setNumAbatements(12345); + assertEquals(Integer.valueOf(12345), clem.getNumAbatements()); + + clem.setNumOnsets(54321); + assertEquals(Integer.valueOf(54321), clem.getNumOnsets()); + + assertNull(clem.getOnsetEvent()); + assertNull(clem.getAbatementEvent()); + assertNull(clem.getProcessor()); + + assertEquals(true, clem.isActive()); + assertEquals(false, clem.releaseLock()); + assertEquals(true, clem.isControlLoopTimedOut()); + + assertNull(clem.unlockCurrentOperation()); + } + + @Test + public void testAlreadyActivated() { + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + manager.setActivated(true); + VirtualControlLoopNotification notification = manager.activate(event); + assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); + } + + @Test + public void testActivationYaml() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml")); + final String yamlStringBad = IOUtils.toString(isBad, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + + // Null YAML should fail + VirtualControlLoopNotification notificationNull = manager.activate(null, event); + assertNotNull(notificationNull); + assertEquals(ControlLoopNotificationType.REJECTED, notificationNull.getNotification()); + + // Empty YAML should fail + VirtualControlLoopNotification notificationEmpty = manager.activate("", event); + assertNotNull(notificationEmpty); + assertEquals(ControlLoopNotificationType.REJECTED, notificationEmpty.getNotification()); + + // Bad YAML should fail + VirtualControlLoopNotification notificationBad = manager.activate(yamlStringBad, event); + assertNotNull(notificationBad); + assertEquals(ControlLoopNotificationType.REJECTED, notificationBad.getNotification()); + + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + // Another activate should fail + VirtualControlLoopNotification notificationActive = manager.activate(yamlString, event); + assertNotNull(notificationActive); + assertEquals(ControlLoopNotificationType.REJECTED, notificationActive.getNotification()); + } + + @Test + public void testControlLoopFinal() throws ControlLoopException, IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.isControlLoopFinal(); + fail("test should throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.isControlLoopFinal(); + fail("test should throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); + assertNull(clfNotification); + + manager.getProcessor().nextPolicyForResult(PolicyResult.SUCCESS); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, clfNotification.getNotification()); + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + manager.setControlLoopTimedOut(); + clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + } + + @Test + public void testProcessControlLoop() throws ControlLoopException, IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + // Test operation in progress + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Already working an Operation, do not call this method.", e.getMessage()); + } + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); + VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); + assertNotNull(clfNotification); + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); + + // Test operation completed + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Control Loop is in FINAL state, do not call this method.", e.getMessage()); + } + + manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE); + + // Test operation with no next policy defined + try { + manager.processControlLoop(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is null", e.getMessage()); + } + } + + @Test + public void testFinishOperation() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + InputStream isStd = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName("TwoOnsetTest"); + event.setRequestID(requestId); + event.setTarget("generic-vnf.vnf-id"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + event.setAAI(new HashMap<>()); + event.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + try { + manager.finishOperation(null); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No operation to finish.", e.getMessage()); + } + + manager.setActivated(true); + try { + manager.finishOperation(null); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("No operation to finish.", e.getMessage()); + } + + manager.setActivated(false); + VirtualControlLoopNotification notification = manager.activate(yamlString, event); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + try { + manager.lockCurrentOperation(); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Do not have a current operation.", e.getMessage()); + } + + assertNull(manager.unlockCurrentOperation()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + LockResult lockLock = manager.lockCurrentOperation(); + assertNotNull(lockLock); + + LockResult lockLockAgain = manager.lockCurrentOperation(); + assertNotNull(lockLockAgain); + assertEquals(lockLock.getB(), lockLockAgain.getB()); + + assertEquals(lockLock.getB(), manager.unlockCurrentOperation()); + assertNull(manager.unlockCurrentOperation()); + + lockLock = manager.lockCurrentOperation(); + assertNotNull(lockLock); + PolicyGuard.unlockTarget(lockLock.getB()); + assertNull(manager.unlockCurrentOperation()); + + clom.startOperation(event); + + // This call should be exception free + manager.finishOperation(clom); + + ControlLoopEventManager otherManager = + new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestID()); + VirtualControlLoopNotification otherNotification = otherManager.activate(yamlStringStd, event); + assertNotNull(otherNotification); + assertEquals(ControlLoopNotificationType.ACTIVE, otherNotification.getNotification()); + + ControlLoopOperationManager otherClom = otherManager.processControlLoop(); + assertNotNull(otherClom); + assertNull(otherClom.getOperationResult()); + + otherManager.finishOperation(clom); + } + + @Test + public void testOnNewEvent() throws IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent(); + abatedEvent.setClosedLoopControlName("TwoOnsetTest"); + abatedEvent.setRequestID(requestId); + abatedEvent.setTarget("generic-vnf.vnf-id"); + abatedEvent.setClosedLoopAlarmStart(Instant.now()); + abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); + abatedEvent.setAAI(new HashMap<>()); + abatedEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + assertEquals(NEW_EVENT_STATUS.FIRST_ONSET, manager.onNewEvent(onsetEvent)); + assertEquals(NEW_EVENT_STATUS.FIRST_ABATEMENT, manager.onNewEvent(abatedEvent)); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + VirtualControlLoopEvent checkSyntaxEvent = new VirtualControlLoopEvent(); + checkSyntaxEvent.setAAI(null); + checkSyntaxEvent.setClosedLoopAlarmEnd(null); + checkSyntaxEvent.setClosedLoopAlarmStart(null); + checkSyntaxEvent.setClosedLoopControlName(null); + checkSyntaxEvent.setClosedLoopEventClient(null); + checkSyntaxEvent.setClosedLoopEventStatus(null); + checkSyntaxEvent.setFrom(null); + checkSyntaxEvent.setPolicyName(null); + checkSyntaxEvent.setPolicyScope(null); + checkSyntaxEvent.setPolicyVersion(null); + checkSyntaxEvent.setRequestID(null); + checkSyntaxEvent.setTarget(null); + checkSyntaxEvent.setTargetType(null); + checkSyntaxEvent.setVersion(null); + + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setClosedLoopControlName("TwoOnsetTest"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setRequestID(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setRequestID(requestId); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(new HashMap<>()); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget(""); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("OZ"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("VM_NAME"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("VNF_NAME"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("vserver.vserver-name"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("generic-vnf.vnf-id"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setTarget("generic-vnf.vnf-name"); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(null); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.setAAI(new HashMap<>()); + assertEquals(NEW_EVENT_STATUS.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); + + checkSyntaxEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + checkSyntaxEvent.getAAI().put("vserver.vserver-name", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + + checkSyntaxEvent.getAAI().put("generic-vnf.vnf-id", "onsetOne"); + assertEquals(NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); + } + + @Test + public void testControlLoopTimeout() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + assertTrue(0 == manager.getControlLoopTimeout(null)); + assertTrue(120 == manager.getControlLoopTimeout(120)); + + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + assertTrue(60 == manager.getControlLoopTimeout(null)); + } + + @Test + public void testQueryAai() throws IOException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + manager.queryAai(onsetEvent); + + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "true"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "true"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().remove("generic-vnf.is-closed-loop-disabled"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", e.getMessage()); + } + onsetEvent.getAAI().remove("vserver.is-closed-loop-disabled"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.is-closed-loop-disabled", "false"); + manager.queryAai(onsetEvent); + onsetEvent.getAAI().put("vserver.is-closed-loop-disabled", "false"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().remove("vserver.vserver-name"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().put("generic-vnf.vnf-id", "AVNFID"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("vserver.vserver-name"); + manager.queryAai(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + manager.queryAai(onsetEvent); + + // Force AAI errors + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:9999"); + + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null " + + "(query by vnf-id)", e.getMessage()); + } + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "AVNFName"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null " + + "(query by vnf-name)", e.getMessage()); + } + + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().put("vserver.vserver-name", "AVserver"); + try { + manager.queryAai(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Exception from queryAai: org.onap.policy.aai.util.AAIException: AAI Response is null " + + "(query by vserver-name)", e.getMessage()); + } + + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + } +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java index 4a30a451a..0d811bbd8 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * unit test * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -51,11 +51,11 @@ import org.onap.policy.appclcm.LCMRequestWrapper; import org.onap.policy.appclcm.LCMResponse; import org.onap.policy.appclcm.LCMResponseWrapper; import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.ControlLoopNotificationType; import org.onap.policy.controlloop.ControlLoopTargetType; import org.onap.policy.controlloop.Util; +import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.onap.policy.controlloop.policy.Policy; @@ -73,674 +73,691 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManagerTest { - private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManagerTest.class); - - - private static VirtualControlLoopEvent onset; - - static { - onset = new VirtualControlLoopEvent(); - onset.setRequestID(UUID.randomUUID()); - onset.setTarget("generic-vnf.vnf-name"); - onset.setTargetType(ControlLoopTargetType.VNF); - onset.setClosedLoopAlarmStart(Instant.now()); - onset.setAAI(new HashMap<>()); - onset.getAAI().put("generic-vnf.vnf-name", "testTriggerSource"); - onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - - /* Set environment properties */ - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - } - - @BeforeClass - public static void setUpSimulator() { - try { - org.onap.policy.simulators.Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testRetriesFail() { - // - // Load up the policy - // - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - try { - // - // Create a processor - // - ControlLoopProcessor processor = new ControlLoopProcessor(pair.b); - // - // create the manager - // - ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - - ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - logger.debug("{}",manager); - // - // - // - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}",manager); - assertNotNull(request); - assertTrue(request instanceof LCMRequestWrapper); - LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) request; - LCMRequest appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - LCMResponseWrapper dmaapResponse = new LCMResponseWrapper(); - LCMResponse appcResponse = new LCMResponse((LCMRequest) appcRequest); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - dmaapResponse.setBody(appcResponse); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new LCMResponse(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - assertTrue(result.equals(PolicyResult.FAILURE)); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Retry it - // - request = manager.startOperation(onset); - logger.debug("{}",manager); - assertNotNull(request); - assertTrue(request instanceof LCMRequestWrapper); - dmaapRequest = (LCMRequestWrapper) request; - appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // - // - appcResponse = new LCMResponse((LCMRequest) appcRequest); - logger.debug("{}",manager); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - dmaapResponse.setBody(appcResponse); - // - // - // - result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new LCMResponse((LCMRequest) appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - assertTrue(result.equals(PolicyResult.FAILURE)); - // - // Should be complete now - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertNotNull(manager.getOperationResult()); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES)); - assertTrue(manager.getHistory().size() == 2); - } catch (ControlLoopException | AAIException e) { - fail(e.getMessage()); - } - } - - @Test - public void testTimeout() { - // - // Load up the policy - // - final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); - onset.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - try { - // - // Create a processor - // - ControlLoopProcessor processor = new ControlLoopProcessor(pair.b); - // - // create the manager - // - ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NEW_EVENT_STATUS status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AAIException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); - - ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - // - // - // - logger.debug("{}",manager); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}",manager); - assertNotNull(request); - assertTrue((request) instanceof LCMRequestWrapper); - LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) request; - LCMRequest appcRequest = dmaapRequest.getBody(); - assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - LCMResponseWrapper dmaapResponse = new LCMResponseWrapper(); - LCMResponse appcResponse = new LCMResponse(appcRequest); - dmaapResponse.setBody(appcResponse); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to simulate Timeout - // - manager.setOperationHasTimedOut(); - logger.debug("{}",manager); - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertTrue(manager.getHistory().size() == 1); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); - // - // Now we are going to Fail the previous request - // - appcResponse = new LCMResponse(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}",manager); - // - // - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertTrue(manager.getHistory().size() == 1); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); - } catch (ControlLoopException | AAIException e) { - fail(e.getMessage()); - } - } - - @Test - public void testMethods() throws IOException, ControlLoopException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - clom.setEventManager(manager); - assertEquals(manager, clom.getEventManager()); - - assertNull(clom.getTargetEntity()); - - clom.setGuardApprovalStatus("WizardOKedIt"); - assertEquals("WizardOKedIt", clom.getGuardApprovalStatus()); - - assertNull(clom.getOperationResult()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - clom.getTarget(policy); - - Target savedTarget = policy.getTarget(); - policy.setTarget(null); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target is null", e.getMessage()); - } - - policy.setTarget(new Target()); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is null", e.getMessage()); - } - - policy.setTarget(savedTarget); - - policy.getTarget().setType(TargetType.PNF); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("PNF target is not supported", e.getMessage()); - } - - onsetEvent.setTarget("Oz"); - onsetEvent.getAAI().remove("generic-vnf.vnf-name"); - onsetEvent.getAAI().remove("generic-vnf.vnf-id"); - onsetEvent.getAAI().remove("vserver.vserver-name"); - - policy.getTarget().setType(TargetType.VNF); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Target does not match target type", e.getMessage()); - } - - onsetEvent.setTarget("vserver.vserver-name"); - onsetEvent.getAAI().put("vserver.vserver-name", "OzVServer"); - assertEquals("OzVServer", clom.getTarget(policy)); - - onsetEvent.getAAI().remove("vserver.vserver-name"); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.getAAI().put("generic-vnf.vnf-id", "OzVNF"); - assertEquals("OzVNF", clom.getTarget(policy)); - - onsetEvent.setTarget("generic-vnf.vnf-name"); - assertEquals("OzVNF", clom.getTarget(policy)); - - manager.onNewEvent(onsetEvent); - - onsetEvent.getAAI().remove("generic-vnf.vnf-id"); - manager.getVnfResponse(); - clom.getEventManager().getVnfResponse().setVnfID("generic-vnf.vnf-id"); - assertEquals("generic-vnf.vnf-id", clom.getTarget(policy)); - - policy.getTarget().setType(TargetType.VFC); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is not supported", e.getMessage()); - } - - assertEquals(Integer.valueOf(20), clom.getOperationTimeout()); - - assertEquals("20s", clom.getOperationTimeoutString(100)); - - assertEquals(null, clom.getOperationMessage()); - assertEquals(null, clom.getOperationMessage("The Wizard Escaped")); - - clom.startOperation(onsetEvent); - - assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1", clom.getOperationMessage()); - assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1, Guard result: The Wizard Escaped", clom.getOperationMessage("The Wizard Escaped")); - - assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30)); - - clom.setOperationHasException("The Wizard is gone"); - clom.setOperationHasGuardDeny(); - } - - @Test - public void testConstructor() throws IOException, ControlLoopException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setRecipe("ModifyConfig"); - policy.getTarget().setResourceID(UUID.randomUUID().toString()); - try { - new ControlLoopOperationManager(onsetEvent, policy, manager); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Target vnf-id could not be found", e.getMessage()); - } - - policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor("SO"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor("VFC"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor("Dorothy"); - try { - new ControlLoopOperationManager(onsetEvent, policy, manager); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage()); - } - } - - @Test - public void testStartOperation() throws IOException, ControlLoopException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - clom.startOperation(onsetEvent); - - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation is not null (an operation is already running)", e.getMessage()); - } - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - String savedRecipe = policy.getRecipe(); - policy.setRecipe("ModifyConfig"); - policy.getTarget().setResourceID(UUID.randomUUID().toString()); - clom.startOperation(onsetEvent); - policy.setRecipe(savedRecipe); - - policy.setRetry(null); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation failed and retries are not allowed", e.getMessage()); - } - - policy.setRetry(0); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation failed and retries are not allowed", e.getMessage()); - } - - policy.setRetry(1); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current oepration has failed after 2 retries", e.getMessage()); - } - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("SO"); - clom.startOperation(onsetEvent); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("VFC"); - clom.startOperation(onsetEvent); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("Oz"); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("invalid actor Oz on policy", e.getMessage()); - } - } - - @Test - public void testOnResponse() throws IOException, ControlLoopException, AAIException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - assertNull(clom.onResponse(null)); - - Response appcResponse = new Response(); - CommonHeader commonHeader = new CommonHeader(); - appcResponse.setCommonHeader(commonHeader ); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - commonHeader.setSubRequestID("12345"); - appcResponse.setStatus(null); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - ResponseStatus responseStatus = new ResponseStatus(); - appcResponse.setStatus(responseStatus); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(0); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.ACCEPT.getValue()); - assertEquals(null, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.ERROR.getValue()); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.FAILURE.getValue()); - assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.REJECT.getValue()); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.SUCCESS.getValue()); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse)); - - LCMResponseWrapper lrw = new LCMResponseWrapper(); - LCMResponse body = new LCMResponse(); - LCMCommonHeader lcmCH = new LCMCommonHeader(); - body.setCommonHeader(lcmCH ); - lrw.setBody(body ); - - lcmCH.setSubRequestId("NotANumber"); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); - - lcmCH.setSubRequestId("12345"); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); - - SOResponse soResponse = new SOResponse(); - SOResponseWrapper soRW = new SOResponseWrapper(soResponse , null); - - soResponse.setHttpResponseCode(200); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRW)); - - soResponse.setHttpResponseCode(202); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRW)); - - soResponse.setHttpResponseCode(500); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); - - VFCResponse vfcResponse = new VFCResponse(); - VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); - vfcResponse.setResponseDescriptor(responseDescriptor ); - - responseDescriptor.setStatus("finished"); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse)); - - responseDescriptor.setStatus("unfinished"); - assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse)); - } - - @Test - public void testCompleteOperation() throws ControlLoopException, AAIException, IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); - onsetEvent.setRequestID(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAAI(new HashMap<>()); - onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); - - ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManagerTest.class); + + + private static VirtualControlLoopEvent onset; + + static { + onset = new VirtualControlLoopEvent(); + onset.setRequestID(UUID.randomUUID()); + onset.setTarget("generic-vnf.vnf-name"); + onset.setTargetType(ControlLoopTargetType.VNF); + onset.setClosedLoopAlarmStart(Instant.now()); + onset.setAAI(new HashMap<>()); + onset.getAAI().put("generic-vnf.vnf-name", "testTriggerSource"); + onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + + /* Set environment properties */ + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); + PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); + } + + /** + * Set up test class. + */ + @BeforeClass + public static void setUpSimulator() { + try { + org.onap.policy.simulators.Util.buildAaiSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testRetriesFail() { + // + // Load up the policy + // + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + try { + // + // Create a processor + // + final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); + // + // create the manager + // + ControlLoopEventManager eventManager = + new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); + VirtualControlLoopNotification notification = eventManager.activate(onset); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NEW_EVENT_STATUS status = null; + try { + status = eventManager.onNewEvent(onset); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + + ControlLoopOperationManager manager = + new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + logger.debug("{}", manager); + // + // + // + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue(request instanceof LCMRequestWrapper); + LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) request; + LCMRequest appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + LCMResponseWrapper dmaapResponse = new LCMResponseWrapper(); + LCMResponse appcResponse = new LCMResponse(appcRequest); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage("ACCEPT"); + dmaapResponse.setBody(appcResponse); + // + // + // + PolicyResult result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + appcResponse = new LCMResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage("AppC failed for some reason"); + dmaapResponse.setBody(appcResponse); + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Retry it + // + request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue(request instanceof LCMRequestWrapper); + dmaapRequest = (LCMRequestWrapper) request; + appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // + // + appcResponse = new LCMResponse(appcRequest); + logger.debug("{}", manager); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage("ACCEPT"); + dmaapResponse.setBody(appcResponse); + // + // + // + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + appcResponse = new LCMResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage("AppC failed for some reason"); + dmaapResponse.setBody(appcResponse); + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + // + // Should be complete now + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertNotNull(manager.getOperationResult()); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES)); + assertTrue(manager.getHistory().size() == 2); + } catch (ControlLoopException | AAIException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTimeout() { + // + // Load up the policy + // + final Util.Pair pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); + try { + // + // Create a processor + // + final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); + // + // create the manager + // + ControlLoopEventManager eventManager = + new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestID()); + VirtualControlLoopNotification notification = eventManager.activate(onset); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NEW_EVENT_STATUS status = null; + try { + status = eventManager.onNewEvent(onset); + } catch (AAIException e) { + logger.warn(e.toString()); + fail("A&AI Query Failed"); + } + assertNotNull(status); + assertEquals(ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET, status); + + ControlLoopOperationManager manager = + new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + // + // + // + logger.debug("{}", manager); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue((request) instanceof LCMRequestWrapper); + LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) request; + LCMRequest appcRequest = dmaapRequest.getBody(); + assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + LCMResponseWrapper dmaapResponse = new LCMResponseWrapper(); + LCMResponse appcResponse = new LCMResponse(appcRequest); + dmaapResponse.setBody(appcResponse); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage("ACCEPT"); + // + // + // + PolicyResult result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to simulate Timeout + // + manager.setOperationHasTimedOut(); + logger.debug("{}", manager); + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); + // + // Now we are going to Fail the previous request + // + appcResponse = new LCMResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage("AppC failed for some reason"); + dmaapResponse.setBody(appcResponse); + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + // + // + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); + } catch (ControlLoopException | AAIException e) { + fail(e.getMessage()); + } + } + + @Test + public void testMethods() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopOperationManager clom = manager.processControlLoop(); + assertNotNull(clom); + assertNull(clom.getOperationResult()); + + clom.setEventManager(manager); + assertEquals(manager, clom.getEventManager()); + + assertNull(clom.getTargetEntity()); + + clom.setGuardApprovalStatus("WizardOKedIt"); + assertEquals("WizardOKedIt", clom.getGuardApprovalStatus()); + + assertNull(clom.getOperationResult()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + clom.getTarget(policy); + + final Target savedTarget = policy.getTarget(); + policy.setTarget(null); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target is null", e.getMessage()); + } + + policy.setTarget(new Target()); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is null", e.getMessage()); + } + + policy.setTarget(savedTarget); + + policy.getTarget().setType(TargetType.PNF); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("PNF target is not supported", e.getMessage()); + } + + onsetEvent.setTarget("Oz"); + onsetEvent.getAAI().remove("generic-vnf.vnf-name"); + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + onsetEvent.getAAI().remove("vserver.vserver-name"); + + policy.getTarget().setType(TargetType.VNF); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Target does not match target type", e.getMessage()); + } + + onsetEvent.setTarget("vserver.vserver-name"); + onsetEvent.getAAI().put("vserver.vserver-name", "OzVServer"); + assertEquals("OzVServer", clom.getTarget(policy)); + + onsetEvent.getAAI().remove("vserver.vserver-name"); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.getAAI().put("generic-vnf.vnf-id", "OzVNF"); + assertEquals("OzVNF", clom.getTarget(policy)); + + onsetEvent.setTarget("generic-vnf.vnf-name"); + assertEquals("OzVNF", clom.getTarget(policy)); + + manager.onNewEvent(onsetEvent); + + onsetEvent.getAAI().remove("generic-vnf.vnf-id"); + manager.getVnfResponse(); + clom.getEventManager().getVnfResponse().setVnfID("generic-vnf.vnf-id"); + assertEquals("generic-vnf.vnf-id", clom.getTarget(policy)); + + policy.getTarget().setType(TargetType.VFC); + try { + clom.getTarget(policy); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("The target type is not supported", e.getMessage()); + } + + assertEquals(Integer.valueOf(20), clom.getOperationTimeout()); + + assertEquals("20s", clom.getOperationTimeoutString(100)); + + assertEquals(null, clom.getOperationMessage()); + assertEquals(null, clom.getOperationMessage("The Wizard Escaped")); + + clom.startOperation(onsetEvent); + + assertEquals("actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1", + clom.getOperationMessage()); + assertEquals( + "actor=SO,operation=Restart,target=Target [type=VFC, resourceID=null],subRequestId=1, Guard result: " + + "The Wizard Escaped", + clom.getOperationMessage("The Wizard Escaped")); + + assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30)); + + clom.setOperationHasException("The Wizard is gone"); + clom.setOperationHasGuardDeny(); + } + + @Test + public void testConstructor() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setRecipe("ModifyConfig"); + policy.getTarget().setResourceID(UUID.randomUUID().toString()); + try { + new ControlLoopOperationManager(onsetEvent, policy, manager); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("Target vnf-id could not be found", e.getMessage()); + } + + policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("SO"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("VFC"); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + policy.setActor("Dorothy"); + try { + new ControlLoopOperationManager(onsetEvent, policy, manager); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage()); + } + } + + @Test + public void testStartOperation() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + clom.startOperation(onsetEvent); + + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation is not null (an operation is already running)", e.getMessage()); + } + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + final String savedRecipe = policy.getRecipe(); + policy.setRecipe("ModifyConfig"); + policy.getTarget().setResourceID(UUID.randomUUID().toString()); + clom.startOperation(onsetEvent); + policy.setRecipe(savedRecipe); + + policy.setRetry(null); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation failed and retries are not allowed", e.getMessage()); + } + + policy.setRetry(0); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current operation failed and retries are not allowed", e.getMessage()); + } + + policy.setRetry(1); + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + clom.startOperation(onsetEvent); + clom.setOperationHasTimedOut(); + assertTrue(clom.isOperationComplete()); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("current oepration has failed after 2 retries", e.getMessage()); + } + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("SO"); + clom.startOperation(onsetEvent); + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("VFC"); + clom.startOperation(onsetEvent); + + clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + policy.setActor("Oz"); + try { + clom.startOperation(onsetEvent); + fail("test should throw an exception here"); + } catch (Exception e) { + assertEquals("invalid actor Oz on policy", e.getMessage()); + } + } + + @Test + public void testOnResponse() throws IOException, ControlLoopException, AAIException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); + + assertNull(clom.onResponse(null)); + + Response appcResponse = new Response(); + CommonHeader commonHeader = new CommonHeader(); + appcResponse.setCommonHeader(commonHeader); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + commonHeader.setSubRequestID("12345"); + appcResponse.setStatus(null); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + ResponseStatus responseStatus = new ResponseStatus(); + appcResponse.setStatus(responseStatus); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(0); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.ACCEPT.getValue()); + assertEquals(null, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.ERROR.getValue()); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.FAILURE.getValue()); + assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.REJECT.getValue()); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); + + responseStatus.setCode(ResponseCode.SUCCESS.getValue()); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse)); + + LCMResponseWrapper lrw = new LCMResponseWrapper(); + LCMResponse body = new LCMResponse(); + LCMCommonHeader lcmCh = new LCMCommonHeader(); + body.setCommonHeader(lcmCh); + lrw.setBody(body); + + lcmCh.setSubRequestId("NotANumber"); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); + + lcmCh.setSubRequestId("12345"); + assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(lrw)); + + SOResponse soResponse = new SOResponse(); + SOResponseWrapper soRw = new SOResponseWrapper(soResponse, null); + + soResponse.setHttpResponseCode(200); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw)); + + soResponse.setHttpResponseCode(202); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw)); + + soResponse.setHttpResponseCode(500); + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); + + VFCResponse vfcResponse = new VFCResponse(); + VFCResponseDescriptor responseDescriptor = new VFCResponseDescriptor(); + vfcResponse.setResponseDescriptor(responseDescriptor); + + responseDescriptor.setStatus("finished"); + assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse)); + + responseDescriptor.setStatus("unfinished"); + assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse)); + } + + @Test + public void testCompleteOperation() throws ControlLoopException, AAIException, IOException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + UUID requestId = UUID.randomUUID(); + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setRequestID(requestId); + onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setClosedLoopAlarmStart(Instant.now()); + onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + onsetEvent.setAAI(new HashMap<>()); + onsetEvent.getAAI().put("generic-vnf.vnf-name", "onsetOne"); + + ControlLoopEventManager manager = + new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestID()); + VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + Policy policy = manager.getProcessor().getCurrentPolicy(); + ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); + assertNotNull(clom); - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); + clom.startOperation(onsetEvent); - clom.startOperation(onsetEvent); + SOResponse soResponse = new SOResponse(); + final SOResponseWrapper soRw = new SOResponseWrapper(soResponse, null); - SOResponse soResponse = new SOResponse(); - SOResponseWrapper soRW = new SOResponseWrapper(soResponse , null); + PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, + "http://somewhere.over.the.rainbow"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); - PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); - - System.setProperty("OperationsHistoryPU", "TestOperationsHistoryPU"); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRW)); - } + System.setProperty("OperationsHistoryPU", "TestOperationsHistoryPU"); + assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java index 315565cf0..db22ce1a6 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntryTest.java @@ -20,7 +20,7 @@ package org.onap.policy.controlloop.eventmanager; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.sql.Timestamp; import java.util.UUID; @@ -29,52 +29,52 @@ import org.junit.Test; public class OperationsHistoryDbEntryTest { - @Test - public void testOperationsHistoryDbEntry() { - OperationsHistoryDbEntry entry = new OperationsHistoryDbEntry(); - - String actor = "Dorothy"; - entry.setActor(actor); - assertEquals(actor, entry.getActor()); - - String closedLoopName = "GoToOz"; - entry.setClosedLoopName(closedLoopName); - assertEquals(closedLoopName, entry.getClosedLoopName()); - - Timestamp endtime = new Timestamp(System.currentTimeMillis()); - entry.setEndtime(endtime); - assertEquals(endtime, entry.getEndtime()); - - String message = "I Want to go Home"; - entry.setMessage(message); - assertEquals(message, entry.getMessage()); - - String operation = "Get Home"; - entry.setOperation(operation); - assertEquals(operation, entry.getOperation()); - - String outcome = "Back in Kansas"; - entry.setOutcome(outcome); - assertEquals(outcome, entry.getOutcome()); - - String requestId = UUID.randomUUID().toString(); - entry.setRequestId(requestId); - assertEquals(requestId, entry.getRequestId()); - - long rowid = 12345; - entry.setRowid(rowid); - assertEquals(rowid, entry.getRowid()); - - Timestamp starttime = new Timestamp(endtime.getTime() - 100); - entry.setStarttime(starttime); - assertEquals(starttime, entry.getStarttime()); - - String subrequestId = "12321"; - entry.setSubrequestId(subrequestId); - assertEquals(subrequestId, entry.getSubrequestId()); - - String target = "WizardOfOz"; - entry.setTarget(target); - assertEquals(target, entry.getTarget()); - } + @Test + public void testOperationsHistoryDbEntry() { + OperationsHistoryDbEntry entry = new OperationsHistoryDbEntry(); + + String actor = "Dorothy"; + entry.setActor(actor); + assertEquals(actor, entry.getActor()); + + String closedLoopName = "GoToOz"; + entry.setClosedLoopName(closedLoopName); + assertEquals(closedLoopName, entry.getClosedLoopName()); + + Timestamp endtime = new Timestamp(System.currentTimeMillis()); + entry.setEndtime(endtime); + assertEquals(endtime, entry.getEndtime()); + + String message = "I Want to go Home"; + entry.setMessage(message); + assertEquals(message, entry.getMessage()); + + String operation = "Get Home"; + entry.setOperation(operation); + assertEquals(operation, entry.getOperation()); + + String outcome = "Back in Kansas"; + entry.setOutcome(outcome); + assertEquals(outcome, entry.getOutcome()); + + String requestId = UUID.randomUUID().toString(); + entry.setRequestId(requestId); + assertEquals(requestId, entry.getRequestId()); + + long rowid = 12345; + entry.setRowid(rowid); + assertEquals(rowid, entry.getRowid()); + + Timestamp starttime = new Timestamp(endtime.getTime() - 100); + entry.setStarttime(starttime); + assertEquals(starttime, entry.getStarttime()); + + String subrequestId = "12321"; + entry.setSubrequestId(subrequestId); + assertEquals(subrequestId, entry.getSubrequestId()); + + String target = "WizardOfOz"; + entry.setTarget(target); + assertEquals(target, entry.getTarget()); + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java index 87ccdb5b9..2a6dc7bbd 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * unit test * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -20,7 +20,10 @@ package org.onap.policy.controlloop.processor; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -30,7 +33,6 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.junit.Test; - import org.onap.policy.controlloop.ControlLoopException; import org.onap.policy.controlloop.policy.FinalResult; import org.onap.policy.controlloop.policy.Policy; @@ -39,122 +41,132 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopProcessorTest { - private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class); - - @Test - public void testControlLoopProcessor() throws IOException, ControlLoopException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - this.testSuccess(yamlString); - this.testFailure(yamlString); - } - - @Test - public void testControlLoopProcessorBadYaml() throws IOException { - InputStream is = new FileInputStream(new File("src/test/resources/string.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - try { - new ControlLoopProcessor(yamlString); - fail("test should thrown an exception"); - } - catch (Exception e) { - assertEquals("Cannot create property=string for JavaBean=ControlLoopPolicy", e.getMessage().substring(0, 60)); - } - } - - @Test - public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException { - InputStream is = new FileInputStream(new File("src/test/resources/badtriggerpolicy.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); - assertNull(clProcessor.getCurrentPolicy()); - - try { - clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); - fail("test shold throw an exception here"); - } - catch (ControlLoopException e) { - assertEquals("There is no current policy to determine where to go to.", e.getMessage()); - } - } - - @Test - public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException { - InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); - - try { - clProcessor.getCurrentPolicy(); - fail("test shold throw an exception here"); - } - catch (ControlLoopException e) { - assertEquals("There are no policies defined.", e.getMessage()); - } - } - - @Test - public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); - String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); - - clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.FAILURE); - - clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); - - clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.FAILURE_GUARD); - - clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.FAILURE_RETRIES); - - clProcessor = new ControlLoopProcessor(yamlString); - clProcessor.getCurrentPolicy(); - clProcessor.nextPolicyForResult(PolicyResult.FAILURE_TIMEOUT); - } - - public void testSuccess(String yaml) throws ControlLoopException { - ControlLoopProcessor processor = new ControlLoopProcessor(yaml); - logger.debug("testSuccess: {}", processor.getControlLoop()); - while (true) { - FinalResult result = processor.checkIsCurrentPolicyFinal(); - if (result != null) { - logger.debug("{}", result); - break; - } - Policy policy = processor.getCurrentPolicy(); - assertNotNull(policy); - logger.debug("current policy is: {} {}", policy.getId(), policy.getName()); - processor.nextPolicyForResult(PolicyResult.SUCCESS); - } - } - - public void testFailure(String yaml) throws ControlLoopException { - ControlLoopProcessor processor = new ControlLoopProcessor(yaml); - logger.debug("testFailure: {}", processor.getControlLoop()); - while (true) { - FinalResult result = processor.checkIsCurrentPolicyFinal(); - if (result != null) { - logger.debug("{}", result); - break; - } - Policy policy = processor.getCurrentPolicy(); - assertNotNull(policy); - logger.debug("current policy is: {} {}", policy.getId(), policy.getName()); - processor.nextPolicyForResult(PolicyResult.FAILURE); - } - } + private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class); + + @Test + public void testControlLoopProcessor() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + this.testSuccess(yamlString); + this.testFailure(yamlString); + } + + @Test + public void testControlLoopProcessorBadYaml() throws IOException { + InputStream is = new FileInputStream(new File("src/test/resources/string.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + try { + new ControlLoopProcessor(yamlString); + fail("test should thrown an exception"); + } catch (Exception e) { + assertEquals("Cannot create property=string for JavaBean=ControlLoopPolicy", + e.getMessage().substring(0, 60)); + } + } + + @Test + public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/badtriggerpolicy.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + assertNull(clProcessor.getCurrentPolicy()); + + try { + clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); + fail("test shold throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("There is no current policy to determine where to go to.", e.getMessage()); + } + } + + @Test + public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + + try { + clProcessor.getCurrentPolicy(); + fail("test shold throw an exception here"); + } catch (ControlLoopException e) { + assertEquals("There are no policies defined.", e.getMessage()); + } + } + + @Test + public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException { + InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); + + ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_GUARD); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_RETRIES); + + clProcessor = new ControlLoopProcessor(yamlString); + clProcessor.getCurrentPolicy(); + clProcessor.nextPolicyForResult(PolicyResult.FAILURE_TIMEOUT); + } + + /** + * Test policies in the given yaml following the successfull path. + * + * @param yaml yaml containing the policies to test + * @throws ControlLoopException if an error occurs + */ + public void testSuccess(String yaml) throws ControlLoopException { + ControlLoopProcessor processor = new ControlLoopProcessor(yaml); + logger.debug("testSuccess: {}", processor.getControlLoop()); + while (true) { + FinalResult result = processor.checkIsCurrentPolicyFinal(); + if (result != null) { + logger.debug("{}", result); + break; + } + Policy policy = processor.getCurrentPolicy(); + assertNotNull(policy); + logger.debug("current policy is: {} {}", policy.getId(), policy.getName()); + processor.nextPolicyForResult(PolicyResult.SUCCESS); + } + } + + /** + * Test policies in the given yaml following the failure path. + * + * @param yaml yaml containing the policies to test + * @throws ControlLoopException if an error occurs + */ + public void testFailure(String yaml) throws ControlLoopException { + ControlLoopProcessor processor = new ControlLoopProcessor(yaml); + logger.debug("testFailure: {}", processor.getControlLoop()); + while (true) { + FinalResult result = processor.checkIsCurrentPolicyFinal(); + if (result != null) { + logger.debug("{}", result); + break; + } + Policy policy = processor.getCurrentPolicy(); + assertNotNull(policy); + logger.debug("current policy is: {} {}", policy.getId(), policy.getName()); + processor.nextPolicyForResult(PolicyResult.FAILURE); + } + } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java index d94230e5e..13d5f3679 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java @@ -34,40 +34,40 @@ import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; public class DroolsPolicyEngineTest { - @Test - public void testDroolsPolicyEngine() { - PolicyEngineJUnitImpl pe = new PolicyEngineJUnitImpl(); - assertNotNull(pe); - - pe.addListener(new TestPolicyEngineListener()); - pe.notifyListeners("TheWizardOfOz"); - - pe.subscribe("OmniBus", "TheWizardOfOz"); + @Test + public void testDroolsPolicyEngine() { + PolicyEngineJUnitImpl pe = new PolicyEngineJUnitImpl(); + assertNotNull(pe); - pe.deliver("OmniBus", "TheWizardOfOz", "Dorothy"); - - pe.subscribe("OmniBus", "TheWizardOfOz"); - pe.subscribe("OmniBus", "ThisTopicDoesNotExist"); + pe.addListener(new TestPolicyEngineListener()); + pe.notifyListeners("TheWizardOfOz"); - ControlLoopNotification notification = new VirtualControlLoopNotification(); - pe.deliver("OmniBus", "TheWizardOfOz", notification); - - Request request = new Request(); - request.setCommonHeader(new CommonHeader()); - request.getCommonHeader().setSubRequestID("12321"); - pe.deliver("OmniBus", "TheWizardOfOz", request); - - LCMRequestWrapper lcmRW = new LCMRequestWrapper(); - lcmRW.setBody(new LCMRequest()); - lcmRW.getBody().setCommonHeader(new LCMCommonHeader()); - lcmRW.getBody().getCommonHeader().setSubRequestId("54321"); - pe.deliver("OmniBus", "TheWizardOfOz", lcmRW); - } - - private class TestPolicyEngineListener implements PolicyEngineListener { - @Override - public void newEventNotification(String topic) { - assertEquals("TheWizardOfOz", topic); - } - } + pe.subscribe("OmniBus", "TheWizardOfOz"); + + pe.deliver("OmniBus", "TheWizardOfOz", "Dorothy"); + + pe.subscribe("OmniBus", "TheWizardOfOz"); + pe.subscribe("OmniBus", "ThisTopicDoesNotExist"); + + ControlLoopNotification notification = new VirtualControlLoopNotification(); + pe.deliver("OmniBus", "TheWizardOfOz", notification); + + Request request = new Request(); + request.setCommonHeader(new CommonHeader()); + request.getCommonHeader().setSubRequestID("12321"); + pe.deliver("OmniBus", "TheWizardOfOz", request); + + LCMRequestWrapper lcmRw = new LCMRequestWrapper(); + lcmRw.setBody(new LCMRequest()); + lcmRw.getBody().setCommonHeader(new LCMCommonHeader()); + lcmRw.getBody().getCommonHeader().setSubRequestId("54321"); + pe.deliver("OmniBus", "TheWizardOfOz", lcmRw); + } + + private class TestPolicyEngineListener implements PolicyEngineListener { + @Override + public void newEventNotification(String topic) { + assertEquals("TheWizardOfOz", topic); + } + } } diff --git a/controlloop/common/feature-controlloop-utils/src/main/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeature.java b/controlloop/common/feature-controlloop-utils/src/main/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeature.java index 3cee70eda..99597f52d 100644 --- a/controlloop/common/feature-controlloop-utils/src/main/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeature.java +++ b/controlloop/common/feature-controlloop-utils/src/main/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeature.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -30,36 +30,33 @@ import org.slf4j.LoggerFactory; /** * PDP-D feature for lab environments that provides Server simulation capabilities for AAI, SO, and - * VFC + * VFC. * */ public class ControlLoopUtilsFeature implements PolicyEngineFeatureAPI { - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(ControlLoopUtilsFeature.class); - - @Override - public boolean afterStart(PolicyEngine engine) { - try { - Util.buildAaiSim(); - Util.buildSoSim(); - Util.buildVfcSim(); - Util.buildGuardSim(); - } catch (final InterruptedException e) { - logger.error("{}: initialization aborted", ControlLoopUtilsFeature.class.getName(), e); - Thread.currentThread().interrupt(); - } catch (final IOException e) { - logger.error("{}: a simulator cannot be built because of {}", - ControlLoopUtilsFeature.class.getName(), e.getMessage(), e); + private static Logger logger = LoggerFactory.getLogger(ControlLoopUtilsFeature.class); + + @Override + public boolean afterStart(PolicyEngine engine) { + try { + Util.buildAaiSim(); + Util.buildSoSim(); + Util.buildVfcSim(); + Util.buildGuardSim(); + } catch (final InterruptedException e) { + logger.error("{}: initialization aborted", ControlLoopUtilsFeature.class.getName(), e); + Thread.currentThread().interrupt(); + } catch (final IOException e) { + logger.error("{}: a simulator cannot be built because of {}", ControlLoopUtilsFeature.class.getName(), + e.getMessage(), e); + } + return false; } - return false; - } - @Override - public int getSequenceNumber() { - return 100000; - } + @Override + public int getSequenceNumber() { + return 100000; + } } diff --git a/controlloop/common/feature-controlloop-utils/src/test/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeatureTest.java b/controlloop/common/feature-controlloop-utils/src/test/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeatureTest.java index 2a8bc35ea..edb48fed5 100644 --- a/controlloop/common/feature-controlloop-utils/src/test/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeatureTest.java +++ b/controlloop/common/feature-controlloop-utils/src/test/java/org/onap/policy/drools/apps/controlloop/feature/utils/ControlLoopUtilsFeatureTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.drools.apps.controlloop.feature.utils; import static org.junit.Assert.assertNotNull; @@ -28,20 +29,20 @@ import org.onap.policy.drools.utils.LoggerUtil; import org.onap.policy.simulators.Util; /** - * ControlLoopUtilsFeature JUnit Tests + * ControlLoopUtilsFeature JUnit Tests. */ public class ControlLoopUtilsFeatureTest { - @Test - public void simulate() { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - final ControlLoopUtilsFeature feature = new ControlLoopUtilsFeature(); - feature.afterStart(PolicyEngine.manager); - assertNotNull(HttpServletServer.factory.get(Util.AAISIM_SERVER_PORT)); - assertNotNull(HttpServletServer.factory.get(Util.SOSIM_SERVER_PORT)); - assertNotNull(HttpServletServer.factory.get(Util.SOSIM_SERVER_PORT)); - assertNotNull(HttpServletServer.factory.get(Util.GUARDSIM_SERVER_PORT)); - } + @Test + public void simulate() { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + final ControlLoopUtilsFeature feature = new ControlLoopUtilsFeature(); + feature.afterStart(PolicyEngine.manager); + assertNotNull(HttpServletServer.factory.get(Util.AAISIM_SERVER_PORT)); + assertNotNull(HttpServletServer.factory.get(Util.SOSIM_SERVER_PORT)); + assertNotNull(HttpServletServer.factory.get(Util.SOSIM_SERVER_PORT)); + assertNotNull(HttpServletServer.factory.get(Util.GUARDSIM_SERVER_PORT)); + } } -- cgit 1.2.3-korg