435faf25d498a6d8bd572881e2a130a2c6e08cc0
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 Bell Canada.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.template.demo;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
26 import io.grpc.Server;
27 import io.grpc.ServerBuilder;
28 import io.grpc.stub.StreamObserver;
29
30 import java.io.IOException;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.UUID;
34 import java.util.concurrent.atomic.AtomicReference;
35
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
41 import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType;
42 import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
43 import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc;
44 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
45 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
46 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
47 import org.onap.policy.common.endpoints.event.comm.TopicListener;
48 import org.onap.policy.common.endpoints.event.comm.TopicSink;
49 import org.onap.policy.controlloop.ControlLoopEventStatus;
50 import org.onap.policy.controlloop.ControlLoopNotificationType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
54 import org.onap.policy.controlloop.util.Serialization;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Test class for vfirewall use case using CDS actor.
60  */
61 public class VfwControlLoopCdsTest extends ControlLoopBase implements TopicListener {
62
63     private static final Logger LOGGER = LoggerFactory.getLogger(VfwControlLoopCdsTest.class);
64
65     private final AtomicReference<StreamObserver<ExecutionServiceOutput>> responseObserverRef = new AtomicReference<>();
66     private Server server;
67
68     /**
69      * Setup the simulator.
70      */
71     @BeforeClass
72     public static void setUpBeforeClass() {
73         ControlLoopBase.setUpBeforeClass("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/"
74                                                  + "main/resources/__closedLoopControlName__.drl",
75                 "src/test/resources/yaml/policy_ControlLoop_vFW_CDS.yaml",
76                 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW",
77                 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
78         SupportUtil.setCustomQuery("true");
79     }
80
81     @Before
82     public void setUp() throws IOException {
83         this.startGrpcServer();
84     }
85
86     @After
87     public void tearDown() {
88         this.stopGrpcServer();
89     }
90
91     private void startGrpcServer() throws IOException {
92
93         BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase cdsBlueprintServerImpl =
94
95             new BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
96
97                 @Override
98                 public StreamObserver<ExecutionServiceInput> process(
99                         final StreamObserver<ExecutionServiceOutput> responseObserver) {
100
101                     responseObserverRef.set(responseObserver);
102
103                     return new StreamObserver<ExecutionServiceInput>() {
104                         @Override
105                         public void onNext(final ExecutionServiceInput input) {
106                             LOGGER.info("gRPC server onNext() for input: {} ...", input);
107                             ExecutionServiceOutput output =
108                                     ExecutionServiceOutput.newBuilder()
109                                             .setCommonHeader(
110                                                     CommonHeader.newBuilder().setRequestId(
111                                                             input.getCommonHeader().getRequestId()).build())
112                                             .setStatus(
113                                                     Status.newBuilder().setEventType(
114                                                             EventType.EVENT_COMPONENT_EXECUTED).build())
115                                             .build();
116                             responseObserver.onNext(output);
117                         }
118
119                         @Override
120                         public void onError(final Throwable throwable) {
121                             LOGGER.error("gRPC server onError() for throwable: {} ...", throwable);
122                         }
123
124                         @Override
125                         public void onCompleted() {
126                             LOGGER.info("gRPC server onCompleted() ...");
127                             responseObserver.onCompleted();
128                         }
129                     };
130                 }
131             };
132
133         server = ServerBuilder.forPort(SupportUtil.GRPC_SERVER_PORT).addService(cdsBlueprintServerImpl).build().start();
134         LOGGER.info("gRPC server is listening for CDS requests on port {}", SupportUtil.GRPC_SERVER_PORT);
135
136     }
137
138     private void stopGrpcServer() {
139         if (server != null) {
140             this.server.shutdown();
141             LOGGER.info("gRPC server handling CDS requests has been successfully shut down.");
142         }
143     }
144
145     @Test
146     public void successTest() {
147
148         /*
149          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
150          * to be pulled from the queue
151          */
152         for (TopicSink sink : noopTopics) {
153             assertTrue(sink.start());
154             sink.register(this);
155         }
156
157         /*
158          * Create a unique requestId
159          */
160         requestId = UUID.randomUUID();
161
162         /*
163          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
164          * through the rules
165          */
166         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
167
168         kieSession.fireUntilHalt();
169         kieSession.fireAllRules();
170
171         /*
172          * The only fact in memory should be Params
173          */
174         assertEquals(1, kieSession.getFactCount());
175
176         /*
177          * Print what's left in memory
178          */
179         dumpFacts(kieSession);
180     }
181
182
183     /*
184      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
185      */
186     @Override
187     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
188         /*
189          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNotification
190          * of type active
191          */
192         assertEquals("POLICY-CL-MGT", topic);
193         VirtualControlLoopNotification notification =
194                 Serialization.gsonJunit.fromJson(event, VirtualControlLoopNotification.class);
195         assertNotNull(notification);
196         String policyName = notification.getPolicyName();
197         if (policyName.endsWith("EVENT")) {
198             logger.debug("Rule Fired: " + notification.getPolicyName());
199             assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
200         } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
201             logger.debug("Rule Fired: " + notification.getPolicyName());
202             assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
203             assertNotNull(notification.getMessage());
204             assertTrue(notification.getMessage().startsWith("Sending guard query"));
205         } else if (policyName.endsWith("GUARD.RESPONSE")) {
206             logger.debug("Rule Fired: " + notification.getPolicyName());
207             assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
208             assertNotNull(notification.getMessage());
209             assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
210         } else if (policyName.endsWith("GUARD_PERMITTED")) {
211             logger.debug("Rule Fired: " + notification.getPolicyName());
212             assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
213             assertNotNull(notification.getMessage());
214             assertTrue(notification.getMessage().startsWith("actor=CDS"));
215         } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
216             logger.debug("Rule Fired: " + notification.getPolicyName());
217             kieSession.halt();
218             logger.debug("The operation timed out");
219             fail("Operation Timed Out");
220         } else if (policyName.endsWith("CDS.RESPONSE")) {
221             logger.debug("Rule Fired: " + notification.getPolicyName());
222             assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
223             assertNotNull(notification.getMessage());
224             assertTrue(notification.getMessage().startsWith("actor=CDS"));
225             sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
226         } else if (policyName.endsWith("EVENT.MANAGER")) {
227             logger.debug("Rule Fired: " + notification.getPolicyName());
228             if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
229                 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
230                 assertEquals("Target vnf-id could not be found", notification.getMessage());
231             } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
232                 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
233             } else {
234                 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
235             }
236             kieSession.halt();
237         } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
238             logger.debug("Rule Fired: " + notification.getPolicyName());
239             kieSession.halt();
240             logger.debug("The control loop timed out");
241             fail("Control Loop Timed Out");
242         }
243     }
244
245     /**
246      * This method is used to simulate event messages from DCAE that start the control loop (onset
247      * message) or end the control loop (abatement message).
248      *
249      * @param policy the controlLoopName comes from the policy
250      * @param requestId the requestId for this event
251      * @param status could be onset or abated
252      */
253     private void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
254         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
255         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
256         event.setRequestId(requestId);
257         event.setTarget("generic-vnf.vnf-name");
258         event.setClosedLoopAlarmStart(Instant.now());
259         event.setAai(new HashMap<>());
260         event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
261         event.getAai().put("vserver.vserver-name", "OzVServer");
262         event.setClosedLoopEventStatus(status);
263         kieSession.insert(event);
264     }
265
266 }