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