diff options
Diffstat (limited to 'controlloop/common/actors')
12 files changed, 1198 insertions, 1161 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<String> recipes = ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); - private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() - .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<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>() - .put(RECIPE_MODIFY, ImmutableList.of("generic-vnf.vnf-id")) - .build(); - - @Override - public String actor() { - return "APPC"; - } - - @Override - public List<String> recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List<String> recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List<String> 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<String> recipes = + ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); + private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() + .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<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>() + .put(RECIPE_MODIFY, ImmutableList.of("generic-vnf.vnf-id")).build(); + + @Override + public String actor() { + return "APPC"; + } + + @Override + public List<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> 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 eb0eef927..673a23c32 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<String> recipes = ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); - private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() - .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<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>() - .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<String> recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List<String> recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List<String> 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<AAINQInventoryResponseItem> 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<String, Map<String, String>> filter = new HashMap<>(); - Map<String, String> 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<String, String> 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<PolicyResult, String> 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<String> recipes = + ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY); + private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() + .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<String, List<String>> payloads = + new ImmutableMap.Builder<String, List<String>>().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<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> 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<AAINQInventoryResponseItem> 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<String, Map<String, String>> filter = new HashMap<>(); + Map<String, String> 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<String, String> 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<PolicyResult, String> 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<String, String> 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<PolicyResult, String> result = AppcLcmActorServiceProvider - .processResponse(dmaapResponse); + AbstractMap.SimpleEntry<PolicyResult, String> 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<PolicyResult, String> 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<String> recipes = ImmutableList.of(RECIPE_VF_MODULE_CREATE); - private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() - .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<String> recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List<String> recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List<String> 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<String, Map<String, String>> aainqinstancefiltermap = new HashMap<>(); - Map<String, String> 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<AAINQInventoryResponseItem> 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<AAINQInventoryResponseItem> 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<String> recipes = ImmutableList.of(RECIPE_VF_MODULE_CREATE); + private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() + .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<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> 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<String, Map<String, String>> aaiNqInstanceFilterMap = new HashMap<>(); + Map<String, String> 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<AAINQInventoryResponseItem> 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<AAINQInventoryResponseItem> 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<String> recipes = ImmutableList.of(RECIPE_RESTART); - private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() - .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).build(); - - @Override - public String actor() { - return VFC_ACTOR; - } - - @Override - public List<String> recipes() { - return ImmutableList.copyOf(recipes); - } - - @Override - public List<String> recipeTargets(String recipe) { - return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); - } - - @Override - public List<String> 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<String> recipes = ImmutableList.of(RECIPE_RESTART); + private static final ImmutableMap<String, List<String>> targets = + new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).build(); + + @Override + public String actor() { + return VFC_ACTOR; + } + + @Override + public List<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> 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<Actor> loader; - - private ActorService() { - loader = ServiceLoader.load(Actor.class); - } - - public static synchronized ActorService getInstance() { - if (service == null) { - service = new ActorService(); - } - return service; - } - - public ImmutableList<Actor> actors() { - Iterator<Actor> 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<Actor> 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<Actor> actors() { + Iterator<Actor> 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<String> recipes(); - - public List<String> recipeTargets(String recipe); - - public List<String> recipePayloads(String recipe); + + public String actor(); + + public List<String> recipes(); + + public List<String> recipeTargets(String recipe); + + public List<String> 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<String> recipes() { - List<String> recipieList = new ArrayList<>(); - recipieList.add("Dorothy"); - recipieList.add("Wizard"); - - return recipieList; - } - - @Override - public List<String> recipeTargets(String recipe) { - List<String> recipieTargetList = new ArrayList<>(); - recipieTargetList.add("Wicked Witch"); - recipieTargetList.add("Wizard of Oz"); - - return recipieTargetList; - } - - @Override - public List<String> recipePayloads(String recipe) { - List<String> recipiePayloadList = new ArrayList<>(); - recipiePayloadList.add("Dorothy"); - recipiePayloadList.add("Toto"); - - return recipiePayloadList; - } + @Override + public String actor() { + return this.getClass().getSimpleName(); + } + + @Override + public List<String> recipes() { + List<String> recipieList = new ArrayList<>(); + recipieList.add("Dorothy"); + recipieList.add("Wizard"); + + return recipieList; + } + + @Override + public List<String> recipeTargets(String recipe) { + List<String> recipieTargetList = new ArrayList<>(); + recipieTargetList.add("Wicked Witch"); + recipieTargetList.add("Wizard of Oz"); + + return recipieTargetList; + } + + @Override + public List<String> recipePayloads(String recipe) { + List<String> 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()); + } } |