From 2e2eae531ad0d6e0e09a1cc4824fc5bb74432679 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Wed, 19 Feb 2020 17:24:11 -0500 Subject: Add Guard Actor Issue-ID: POLICY-2350 Signed-off-by: Jim Hahn Change-Id: Ib68c22a1154607563cb8a657b8101757a29b47ef --- .../model-actors/actor.guard/pom.xml | 83 ++++++++++ .../actor/guard/GuardActorServiceProvider.java | 41 +++++ .../controlloop/actor/guard/GuardOperation.java | 174 +++++++++++++++++++++ ...licy.controlloop.actorServiceProvider.spi.Actor | 1 + .../actor/guard/GuardActorServiceProviderTest.java | 41 +++++ .../actor/guard/GuardOperationTest.java | 167 ++++++++++++++++++++ .../actor.guard/src/test/resources/makeReq.json | 10 ++ .../src/test/resources/makeReqDefault.json | 5 + .../actor.guard/src/test/resources/makeReqStd.json | 11 ++ .../model-actors/actor.test/pom.xml | 2 - models-interactions/model-actors/pom.xml | 1 + 11 files changed, 534 insertions(+), 2 deletions(-) create mode 100644 models-interactions/model-actors/actor.guard/pom.xml create mode 100644 models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProvider.java create mode 100644 models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardOperation.java create mode 100644 models-interactions/model-actors/actor.guard/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorServiceProvider.spi.Actor create mode 100644 models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProviderTest.java create mode 100644 models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardOperationTest.java create mode 100644 models-interactions/model-actors/actor.guard/src/test/resources/makeReq.json create mode 100644 models-interactions/model-actors/actor.guard/src/test/resources/makeReqDefault.json create mode 100644 models-interactions/model-actors/actor.guard/src/test/resources/makeReqStd.json (limited to 'models-interactions') diff --git a/models-interactions/model-actors/actor.guard/pom.xml b/models-interactions/model-actors/actor.guard/pom.xml new file mode 100644 index 000000000..a70c84f31 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/pom.xml @@ -0,0 +1,83 @@ + + + + + 4.0.0 + + + org.onap.policy.models.policy-models-interactions.model-actors + model-actors + 2.2.1-SNAPSHOT + + + actor.guard + + + + org.onap.policy.models.policy-models-interactions.model-actors + actorServiceProvider + ${project.version} + provided + + + org.onap.policy.models.policy-models-interactions.model-impl + aai + ${project.version} + provided + + + org.onap.policy.models.policy-models-interactions.model-actors + actor.aai + ${project.version} + provided + + + org.onap.policy.models + policy-models-decisions + ${project.version} + provided + + + org.onap.policy.common + policy-endpoints + ${policy.common.version} + provided + + + junit + junit + test + + + org.onap.policy.models.policy-models-interactions.model-actors + actor.test + ${project.version} + test + + + org.powermock + powermock-api-mockito2 + test + + + diff --git a/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProvider.java b/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProvider.java new file mode 100644 index 000000000..104c3830c --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProvider.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * SdncActorServiceProvider + * ================================================================================ + * Copyright (C) 2018-2019 Huawei Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.guard; + +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpActor; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator; + +public class GuardActorServiceProvider extends HttpActor { + // actor name + public static final String NAME = "GUARD"; + + /** + * Constructs the object. + */ + public GuardActorServiceProvider() { + super(NAME); + + addOperator(HttpOperator.makeOperator(NAME, GuardOperation.NAME, + GuardOperation::new)); + } +} diff --git a/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardOperation.java b/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardOperation.java new file mode 100644 index 000000000..941838f00 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/main/java/org/onap/policy/controlloop/actor/guard/GuardOperation.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.guard; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Guard Operation. The outcome message is set to the guard response. If the guard is + * permitted or indeterminate, then the outcome is set to SUCCESS. + *

+ * The input to the request is taken from the payload, where properties are mapped to the + * field names in the {@link DecisionRequest} object. Properties whose names begin with + * "resource." are placed into the "resource" field of the {@link DecisionRequest}. The + * following will be provided, if not specified in the payload: + *

+ *
action
+ *
"guard"
+ *
request ID
+ *
generated
+ *
+ */ +public class GuardOperation extends HttpOperation { + private static final Logger logger = LoggerFactory.getLogger(GuardOperation.class); + + // operation name + public static final String NAME = "Decision"; + + public static final String PERMIT = "Permit"; + public static final String DENY = "Deny"; + public static final String INDETERMINATE = "Indeterminate"; + + private static final String RESOURCE = "resource"; + + /** + * Prefix for properties in the payload that should be copied to the "resource" field + * of the request. + */ + public static final String RESOURCE_PREFIX = "resource."; + + + /** + * Constructs the object. + * + * @param params operation parameters + * @param operator operator that created this operation + */ + public GuardOperation(ControlLoopOperationParams params, HttpOperator operator) { + super(params, operator, DecisionResponse.class); + } + + @Override + protected CompletableFuture startOperationAsync(int attempt, OperationOutcome outcome) { + + DecisionRequest request = Util.translate(getName(), makeRequest(), DecisionRequest.class); + + Entity entity = Entity.entity(request, MediaType.APPLICATION_JSON); + + Map headers = makeHeaders(); + + headers.put("Accept", MediaType.APPLICATION_JSON); + String url = makeUrl(); + + logMessage(EventType.OUT, CommInfrastructure.REST, url, request); + + // @formatter:off + return handleResponse(outcome, url, + callback -> getOperator().getClient().post(callback, makePath(), entity, headers)); + // @formatter:on + } + + /** + * Makes a request from the payload. + * + * @return a new request map + */ + protected Map makeRequest() { + if (params.getPayload() == null) { + throw new IllegalArgumentException("missing payload"); + } + + /* + * This code could be easily modified to allow the context and/or resource to be + * an encoded JSON string, that is decoded into a Map and stuffed into the + * appropriate field. + */ + + Map req = new LinkedHashMap<>(); + Map resource = new LinkedHashMap<>(); + + for (Entry ent : params.getPayload().entrySet()) { + String key = ent.getKey(); + + if (key.startsWith(RESOURCE_PREFIX)) { + // it's a resource property - put into the resource map + key = key.substring(RESOURCE_PREFIX.length()); + resource.put(key, ent.getValue()); + + } else if (key.indexOf('.') < 0) { + // it's a normal property - put into the request map + req.put(key, ent.getValue()); + + } else { + logger.warn("{}: unused key {} in payload for {}", getFullName(), key, params.getRequestId()); + } + } + + req.putIfAbsent("action", "guard"); + req.computeIfAbsent("requestId", key -> UUID.randomUUID().toString()); + req.put(RESOURCE, resource); + + return req; + } + + @Override + protected CompletableFuture postProcessResponse(OperationOutcome outcome, String url, + Response rawResponse, DecisionResponse response) { + + // determine the result + String status = response.getStatus(); + if (status == null) { + outcome.setResult(PolicyResult.FAILURE); + outcome.setMessage("response contains no status"); + return CompletableFuture.completedFuture(outcome); + } + + if (PERMIT.equalsIgnoreCase(status) || INDETERMINATE.equalsIgnoreCase(status)) { + outcome.setResult(PolicyResult.SUCCESS); + } else { + outcome.setResult(PolicyResult.FAILURE); + } + + // set the message + outcome.setMessage(response.getStatus()); + + return CompletableFuture.completedFuture(outcome); + } +} diff --git a/models-interactions/model-actors/actor.guard/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorServiceProvider.spi.Actor b/models-interactions/model-actors/actor.guard/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorServiceProvider.spi.Actor new file mode 100644 index 000000000..dd4368504 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorServiceProvider.spi.Actor @@ -0,0 +1 @@ +org.onap.policy.controlloop.actor.guard.GuardActorServiceProvider diff --git a/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProviderTest.java b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProviderTest.java new file mode 100644 index 000000000..f4ab6061e --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardActorServiceProviderTest.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.guard; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.stream.Collectors; +import org.junit.Test; + +public class GuardActorServiceProviderTest { + + @Test + public void test() { + final GuardActorServiceProvider prov = new GuardActorServiceProvider(); + + // verify that it has the operators we expect + var expected = Arrays.asList(GuardOperation.NAME).stream().sorted().collect(Collectors.toList()); + var actual = prov.getOperationNames().stream().sorted().collect(Collectors.toList()); + + assertEquals(expected.toString(), actual.toString()); + } +} diff --git a/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardOperationTest.java b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardOperationTest.java new file mode 100644 index 000000000..505106041 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/GuardOperationTest.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.guard; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.controlloop.actor.test.BasicHttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; + +public class GuardOperationTest extends BasicHttpOperation { + + private GuardOperation oper; + + /** + * Sets up. + */ + @Before + public void setUp() throws Exception { + super.setUp(); + + oper = new GuardOperation(params, operator); + } + + @Test + public void testConstructor() { + assertEquals(DEFAULT_ACTOR, oper.getActorName()); + assertEquals(DEFAULT_OPERATION, oper.getName()); + } + + @Test + public void testStartOperationAsync() throws Exception { + CompletableFuture future2 = oper.start(); + executor.runAll(100); + assertFalse(future2.isDone()); + + DecisionResponse resp = new DecisionResponse(); + resp.setStatus(GuardOperation.PERMIT); + when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class)); + + verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any()); + callbackCaptor.getValue().completed(rawResponse); + + executor.runAll(100); + assertTrue(future2.isDone()); + + DecisionRequest request = requestCaptor.getValue().getEntity(); + verifyRequest("makeReqStd.json", request, "requestId"); + + assertEquals(PolicyResult.SUCCESS, future2.get().getResult()); + } + + @Test + public void testMakeRequest() throws CoderException { + verifyPayload("makeReqStd.json", makePayload()); + verifyPayload("makeReqDefault.json", new TreeMap<>()); + + Map payload = new TreeMap<>(); + payload.put("action", "some action"); + payload.put("hello", "world"); + payload.put("r u there?", "yes"); + payload.put("requestId", "some request id"); + payload.put("resource.abc", "def"); + payload.put("resource.ghi", "jkl"); + payload.put("some.other", "unused"); + + verifyPayload("makeReq.json", payload); + + // null payload - start with fresh parameters and operation + params = params.toBuilder().payload(null).build(); + oper = new GuardOperation(params, operator); + assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest()); + } + + private void verifyPayload(String expectedJsonFile, Map payload) throws CoderException { + params.getPayload().clear(); + params.getPayload().putAll(payload); + + Map requestMap = oper.makeRequest(); + + verifyRequest(expectedJsonFile, requestMap, "requestId"); + } + + @Test + public void testPostProcessResponse() { + DecisionResponse response = new DecisionResponse(); + + // null status + response.setStatus(null); + verifyOutcome(response, PolicyResult.FAILURE, "response contains no status"); + + // permit, mixed case + response.setStatus("peRmit"); + verifyOutcome(response, PolicyResult.SUCCESS, "peRmit"); + + // indeterminate, mixed case + response.setStatus("inDETerminate"); + verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate"); + + // deny, mixed case + response.setStatus("deNY"); + verifyOutcome(response, PolicyResult.FAILURE, "deNY"); + + // unknown status + response.setStatus("unknown"); + verifyOutcome(response, PolicyResult.FAILURE, "unknown"); + } + + private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) { + oper.postProcessResponse(outcome, BASE_URI, rawResponse, response); + assertEquals(expectedResult, outcome.getResult()); + assertEquals(expectedMessage, outcome.getMessage()); + } + + @Override + protected Map makePayload() { + DecisionRequest req = new DecisionRequest(); + req.setAction("my-action"); + req.setOnapComponent("my-onap-component"); + req.setOnapInstance("my-onap-instance"); + req.setOnapName("my-onap-name"); + req.setRequestId("my-request-id"); + + @SuppressWarnings("unchecked") + Map map = Util.translate("", req, LinkedHashMap.class); + + // add resources + map.put(GuardOperation.RESOURCE_PREFIX + "actor", "resource-actor"); + map.put(GuardOperation.RESOURCE_PREFIX + "operation", "resource-operation"); + + return map; + } +} diff --git a/models-interactions/model-actors/actor.guard/src/test/resources/makeReq.json b/models-interactions/model-actors/actor.guard/src/test/resources/makeReq.json new file mode 100644 index 000000000..2716d030e --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/test/resources/makeReq.json @@ -0,0 +1,10 @@ +{ + "action": "some action", + "hello": "world", + "r u there?": "yes", + "requestId": "abcdefghi", + "resource": { + "abc": "def", + "ghi": "jkl" + } +} diff --git a/models-interactions/model-actors/actor.guard/src/test/resources/makeReqDefault.json b/models-interactions/model-actors/actor.guard/src/test/resources/makeReqDefault.json new file mode 100644 index 000000000..9e9df7b22 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/test/resources/makeReqDefault.json @@ -0,0 +1,5 @@ +{ + "action": "guard", + "requestId": "abcdefghi", + "resource": {} +} diff --git a/models-interactions/model-actors/actor.guard/src/test/resources/makeReqStd.json b/models-interactions/model-actors/actor.guard/src/test/resources/makeReqStd.json new file mode 100644 index 000000000..5437ae896 --- /dev/null +++ b/models-interactions/model-actors/actor.guard/src/test/resources/makeReqStd.json @@ -0,0 +1,11 @@ +{ + "ONAPName": "my-onap-name", + "ONAPComponent": "my-onap-component", + "ONAPInstance": "my-onap-instance", + "requestId": "abcdefghi", + "action": "my-action", + "resource": { + "actor": "resource-actor", + "operation": "resource-operation" + } +} \ No newline at end of file diff --git a/models-interactions/model-actors/actor.test/pom.xml b/models-interactions/model-actors/actor.test/pom.xml index 9bddbd9dd..3df35c355 100644 --- a/models-interactions/model-actors/actor.test/pom.xml +++ b/models-interactions/model-actors/actor.test/pom.xml @@ -36,13 +36,11 @@ org.onap.policy.models.policy-models-interactions.model-impl events ${project.version} - provided org.onap.policy.models.policy-models-interactions.model-actors actorServiceProvider ${project.version} - provided org.onap.policy.common diff --git a/models-interactions/model-actors/pom.xml b/models-interactions/model-actors/pom.xml index 30891142d..987788c51 100644 --- a/models-interactions/model-actors/pom.xml +++ b/models-interactions/model-actors/pom.xml @@ -38,6 +38,7 @@ actorServiceProvider actor.test actor.aai + actor.guard actor.appc actor.vfc actor.sdnc -- cgit 1.2.3-korg