b4fe10a9077af97274bb8b355a8dbcdb4f975a65
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2022 Nordix Foundation. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.doReturn;
29
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
32
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.PrintStream;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.time.Duration;
41 import java.time.Instant;
42 import java.util.ArrayList;
43 import java.util.Collections;
44 import java.util.List;
45
46 import org.json.JSONObject;
47 import org.junit.jupiter.api.AfterEach;
48 import org.junit.jupiter.api.Test;
49 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
50 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
51 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
52 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
53 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
54 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
55 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
56 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
57 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbackInfo;
58 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
67 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
68 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
69 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
70 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
71 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
72 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
73 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
74 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.boot.test.context.SpringBootTest;
79 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
80 import org.springframework.boot.test.context.TestConfiguration;
81 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
82 import org.springframework.boot.web.server.LocalServerPort;
83 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
84 import org.springframework.context.ApplicationContext;
85 import org.springframework.context.annotation.Bean;
86 import org.springframework.http.HttpStatus;
87 import org.springframework.http.MediaType;
88 import org.springframework.http.ResponseEntity;
89 import org.springframework.test.context.TestPropertySource;
90 import org.springframework.web.reactive.function.client.WebClientResponseException;
91
92 import reactor.core.publisher.Mono;
93 import reactor.test.StepVerifier;
94 import reactor.util.annotation.Nullable;
95
96 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
97 @TestPropertySource(properties = { //
98         "server.ssl.key-store=./src/test/resources/keystore.jks", //
99         "app.webclient.trust-store=./src/test/resources/truststore.jks", //
100         "app.webclient.trust-store-used=true", //
101         "app.vardata-directory=./target/testdata", //
102         "app.filepath=" //
103 })
104 class ApplicationTest {
105     private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
106
107     @Autowired
108     ApplicationContext context;
109
110     @Autowired
111     private Rics rics;
112
113     @Autowired
114     private Policies policies;
115
116     @Autowired
117     private PolicyTypes policyTypes;
118
119     @Autowired
120     MockA1ClientFactory a1ClientFactory;
121
122     @Autowired
123     RicSupervision supervision;
124
125     @Autowired
126     ApplicationConfig applicationConfig;
127
128     @Autowired
129     Services services;
130
131     @Autowired
132     RappSimulatorController rAppSimulator;
133
134     @Autowired
135     RefreshConfigTask refreshConfigTask;
136
137     @Autowired
138     SecurityContext securityContext;
139
140     private static Gson gson = new GsonBuilder().create();
141
142     /**
143      * Overrides the BeanFactory.
144      */
145     @TestConfiguration
146     static class TestBeanFactory {
147
148         @Bean
149         A1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
150             return new MockA1ClientFactory(appConfig, types);
151         }
152
153         @Bean
154         public ServiceSupervision getServiceSupervision(@Autowired Services services,
155                 @Autowired A1ClientFactory a1ClientFactory, @Autowired Policies policies) {
156             Duration checkInterval = Duration.ofMillis(1);
157             return new ServiceSupervision(services, policies, a1ClientFactory, checkInterval);
158         }
159
160         @Bean
161         public ServletWebServerFactory servletContainer() {
162             return new TomcatServletWebServerFactory();
163         }
164     }
165
166     @LocalServerPort
167     private int port;
168
169     @AfterEach
170     void reset() {
171         rics.clear();
172         policies.clear();
173         policyTypes.clear();
174         services.clear();
175         a1ClientFactory.reset();
176         this.rAppSimulator.getTestResults().clear();
177         this.a1ClientFactory.setPolicyTypes(policyTypes); // Default same types in RIC and in this app
178         this.securityContext.setAuthTokenFilePath(null);
179     }
180
181     @AfterEach
182     void verifyNoRicLocks() {
183         for (Ric ric : this.rics.getRics()) {
184             Lock.Grant grant = ric.getLock().lockBlocking(LockType.EXCLUSIVE, "");
185             grant.unlockBlocking();
186             assertThat(ric.getLock().getLockCounter()).isZero();
187             assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
188         }
189     }
190
191     @Test
192     void generateApiDoc() throws IOException {
193         String url = "https://localhost:" + this.port + "/v3/api-docs";
194         ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
195         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
196         JSONObject jsonObj = new JSONObject(resp.getBody());
197         assertThat(jsonObj.remove("servers")).isNotNull();
198
199         String indented = (jsonObj).toString(4);
200         String docDir = "api/";
201         Files.createDirectories(Paths.get(docDir));
202         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "pms-api.json"))) {
203             out.print(indented);
204         }
205     }
206
207     @Test
208     void testPersistencyPolicies() throws ServiceException {
209         Ric ric = this.addRic("ric1");
210         PolicyType type = this.addPolicyType("type1", ric.id());
211
212         final int noOfPolicies = 100;
213         for (int i = 0; i < noOfPolicies; ++i) {
214             addPolicy("id" + i, type.getId(), "service", ric.id());
215         }
216
217         {
218             Policies policies = new Policies(this.applicationConfig);
219             policies.restoreFromDatabase(ric, this.policyTypes);
220             assertThat(policies.size()).isEqualTo(noOfPolicies);
221         }
222
223         {
224             restClient().delete("/policies/id2").block();
225             Policies policies = new Policies(this.applicationConfig);
226             policies.restoreFromDatabase(ric, this.policyTypes);
227             assertThat(policies.size()).isEqualTo(noOfPolicies - 1);
228         }
229     }
230
231     @Test
232     void testPersistencyPolicyTypes() throws ServiceException {
233         Ric ric = this.addRic("ric1");
234         this.addPolicyType("type1", ric.id());
235         PolicyTypes types = new PolicyTypes(this.applicationConfig);
236         assertThat(types.size()).isEqualTo(1);
237     }
238
239     @Test
240     void testPersistencyService() throws ServiceException {
241         final String SERVICE = "serviceName";
242         putService(SERVICE, 1234, HttpStatus.CREATED);
243         assertThat(this.services.size()).isEqualTo(1);
244         Service service = this.services.getService(SERVICE);
245
246         Services servicesRestored = new Services(this.applicationConfig);
247         Service serviceRestored = servicesRestored.getService(SERVICE);
248         assertThat(servicesRestored.size()).isEqualTo(1);
249         assertThat(serviceRestored.getCallbackUrl()).isEqualTo(service.getCallbackUrl());
250         assertThat(serviceRestored.getKeepAliveInterval()).isEqualTo(service.getKeepAliveInterval());
251
252         // check that the service can be deleted
253         this.services.remove(SERVICE);
254         servicesRestored = new Services(this.applicationConfig);
255         assertThat(servicesRestored.size()).isZero();
256     }
257
258     @Test
259     void testAddingRicFromConfiguration() throws Exception {
260         // Test adding the RIC from configuration
261
262         final String RIC = "ric1";
263         final String TYPE = "type123";
264         PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
265         nearRtRicPolicyTypes.put(createPolicyType(TYPE));
266         this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
267
268         putService("service");
269
270         refreshConfigTask.handleUpdatedRicConfig( //
271                 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
272                 .block();
273         waitForRicState(RIC, RicState.AVAILABLE);
274
275         // Test that the type has been synched
276         Ric addedRic = this.rics.getRic(RIC);
277         assertThat(addedRic.getSupportedPolicyTypes()).hasSize(1);
278         assertThat(addedRic.getSupportedPolicyTypes().iterator().next().getId()).isEqualTo(TYPE);
279
280         // Check that a service callback for the AVAILABLE RIC is invoked
281         final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
282         await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
283         ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
284         assertThat(callbackInfo.ricId).isEqualTo(RIC);
285         assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
286     }
287
288     @Test
289     void testAddingRicFromConfiguration_nonRespondingRic() throws Exception {
290         putService("service");
291
292         final String RIC = "NonRespondingRic";
293         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(RIC);
294         doReturn(MockA1Client.monoError("error", HttpStatus.BAD_GATEWAY)).when(a1Client).getPolicyTypeIdentities();
295
296         refreshConfigTask.handleUpdatedRicConfig( //
297                 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
298                 .block();
299
300         waitForRicState(RIC, RicState.UNAVAILABLE);
301
302         // Check that no service callback for the UNAVAILABLE RIC is invoked
303         final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
304         await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).isEmpty());
305
306         // Run a synch and check that the AVAILABLE notification is received
307         a1ClientFactory.reset();
308         supervision.checkAllRics();
309         waitForRicState(RIC, RicState.AVAILABLE);
310
311         await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
312     }
313
314     @Test
315     void testTrustValidation() {
316         addRic("ric1");
317         String rsp = restClient(true).get("/rics").block(); // restClient(true) enables trust validation
318         assertThat(rsp).contains("ric1");
319     }
320
321     @Test
322     void testGetRics() throws Exception {
323         addRic("ric1");
324         this.addPolicyType("type1", "ric1");
325         String url = "/rics?policytype_id=type1";
326         String rsp = restClient().get(url).block();
327         assertThat(rsp).contains("ric1");
328
329         // nameless type for ORAN A1 1.1
330         addRic("ric2");
331         this.addPolicyType("", "ric2");
332         url = "/rics?policytype_id=";
333         rsp = restClient().get(url).block();
334         assertThat(rsp).contains("ric2") //
335                 .doesNotContain("ric1") //
336                 .contains("AVAILABLE");
337
338         // All RICs
339         rsp = restClient().get("/rics").block();
340         assertThat(rsp).contains("ric2") //
341                 .contains("ric1");
342
343         // Non existing policy type
344         url = "/rics?policytype_id=XXXX";
345         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
346     }
347
348     @Test
349     void testSynchronization() throws Exception {
350         // Two polictypes will be put in the NearRT RICs
351         PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
352         nearRtRicPolicyTypes.put(createPolicyType("typeName"));
353         nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
354         this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
355
356         // One type and one instance added to the Policy Management Service's storage
357         final String ric1Name = "ric1";
358         Ric ric1 = addRic(ric1Name);
359         Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
360         Ric ric2 = addRic("ric2");
361
362         getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
363         policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
364
365         String policyId = "policyId";
366         Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
367         supervision.checkAllRics(); // The created policy should be put in the RIC
368
369         // Wait until synch is completed
370         waitForRicState(ric1Name, RicState.SYNCHRONIZING);
371         waitForRicState(ric1Name, RicState.AVAILABLE);
372         waitForRicState("ric2", RicState.AVAILABLE);
373
374         Policies ricPolicies = getA1Client(ric1Name).getPolicies();
375         assertThat(ricPolicies.size()).isEqualTo(1);
376         Policy ricPolicy = ricPolicies.get(policyId);
377         assertThat(ricPolicy.getJson()).isEqualTo(policy.getJson());
378
379         // Both types should be in the Policy Management Service's storage after the
380         // synch
381         assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
382         assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
383     }
384
385     @Test
386     void testGetRic() throws Exception {
387         String ricId = "ric1";
388         String managedElementId = "kista_1";
389         addRic(ricId, managedElementId);
390
391         String url = "/rics/ric?managed_element_id=" + managedElementId;
392         String rsp = restClient().get(url).block();
393         RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
394         assertThat(ricInfo.ricId).isEqualTo(ricId);
395
396         url = "/rics/ric?ric_id=" + ricId;
397         rsp = restClient().get(url).block();
398         ricInfo = gson.fromJson(rsp, RicInfo.class);
399         assertThat(ricInfo.ricId).isEqualTo(ricId);
400
401         // test GET RIC for ManagedElement that does not exist
402         url = "/rics/ric?managed_element_id=" + "junk";
403         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
404
405         url = "/rics/ric";
406         testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
407     }
408
409     private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
410             boolean isTransient) {
411         PolicyInfo info = new PolicyInfo();
412         info.policyId = policyInstanceId;
413         info.policyTypeId = policyTypeName;
414         info.ricId = ricId;
415         info.serviceId = serviceName;
416         info.policyData = gson.fromJson(jsonString(), Object.class);
417
418         if (isTransient) {
419             info.isTransient = isTransient;
420         }
421         info.statusNotificationUri = "statusNotificationUri";
422         return gson.toJson(info);
423     }
424
425     private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
426         return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false);
427     }
428
429     @Test
430     void testPutPolicy() throws Exception {
431         String serviceName = "service.1";
432         String ricId = "ric.1";
433         String policyTypeName = "type1_1.2.3";
434         String policyInstanceId = "instance_1.2.3";
435
436         putService(serviceName);
437         addPolicyType(policyTypeName, ricId);
438
439         // PUT a transient policy
440         String url = "/policies";
441         String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true);
442         this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
443
444         restClient().put(url, policyBody).block();
445
446         Policy policy = policies.getPolicy(policyInstanceId);
447         assertThat(policy).isNotNull();
448         assertThat(policy.getId()).isEqualTo(policyInstanceId);
449         assertThat(policy.getOwnerServiceId()).isEqualTo(serviceName);
450         assertThat(policy.getRic().id()).isEqualTo(ricId);
451         assertThat(policy.isTransient()).isTrue();
452
453         // Put a non transient policy
454         policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
455         restClient().put(url, policyBody).block();
456         policy = policies.getPolicy(policyInstanceId);
457         assertThat(policy.isTransient()).isFalse();
458
459         url = "/policy-instances";
460         String rsp = restClient().get(url).block();
461         assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
462
463         url = "/policies/" + policyInstanceId;
464         rsp = restClient().get(url).block();
465         assertThat(rsp).contains(policyBody);
466
467         // Test of error codes
468         url = "/policies";
469         policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
470         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
471
472         policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
473         addPolicyType(policyTypeName + "XX", "otherRic");
474         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
475
476         policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
477         this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
478         testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
479         this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
480     }
481
482     @Test
483     /**
484      * Test that HttpStatus and body from failing REST call to A1 is passed on to
485      * the caller.
486      *
487      * @throws ServiceException
488      */
489     void testErrorFromRic() throws ServiceException {
490         putService("service1");
491         addPolicyType("type1", "ric1");
492
493         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
494         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
495         String responseBody = "Refused";
496         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
497
498         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
499                 responseBodyBytes, StandardCharsets.UTF_8, null);
500         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
501
502         // PUT Policy
503         String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
504         String url = "/policies";
505         testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
506
507         // DELETE POLICY
508         this.addPolicy("instance1", "type1", "service1", "ric1");
509         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
510         testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
511
512     }
513
514     @Test
515     void testPutTypelessPolicy() throws Exception {
516         putService("service1");
517         addPolicyType("", "ric1");
518         String body = putPolicyBody("service1", "ric1", "", "id1");
519         restClient().put("/policies", body).block();
520
521         String rsp = restClient().get("/policy-instances").block();
522         PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
523         assertThat(info.policies).hasSize(1);
524         PolicyInfo policyInfo = info.policies.iterator().next();
525         assertThat(policyInfo.policyId).isEqualTo("id1");
526         assertThat(policyInfo.policyTypeId).isEmpty();
527     }
528
529     @Test
530     void testRefuseToUpdatePolicy() throws Exception {
531         // Test that only the json can be changed for a already created policy
532         // In this case service is attempted to be changed
533         this.addRic("ric1");
534         this.addRic("ricXXX");
535         this.addPolicy("instance1", "type1", "service1", "ric1");
536         this.addPolicy("instance2", "type1", "service1", "ricXXX");
537
538         // Try change ric1 -> ricXXX
539         String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
540         testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
541     }
542
543     @Test
544     void testGetPolicy() throws Exception {
545         String url = "/policies/id";
546         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
547         {
548             String rsp = restClient().get(url).block();
549             PolicyInfo info = gson.fromJson(rsp, PolicyInfo.class);
550             String policyStr = gson.toJson(info.policyData);
551             assertThat(policyStr).isEqualTo(policy.getJson());
552         }
553         {
554             policies.remove(policy);
555             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
556         }
557     }
558
559     @Test
560     void testDeletePolicy() throws Exception {
561         String policyId = "id.1";
562         addPolicy(policyId, "typeName", "service1", "ric1");
563         assertThat(policies.size()).isEqualTo(1);
564
565         String url = "/policies/" + policyId;
566         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
567
568         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
569         assertThat(policies.size()).isZero();
570
571         // Delete a non existing policy
572         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
573     }
574
575     @Test
576     void testGetPolicyType() throws Exception {
577         String typeId = "AC.D";
578         addPolicyType(typeId, "ric1");
579
580         waitForRicState("ric1", RicState.AVAILABLE);
581
582         String url = "/policy-types/" + typeId;
583
584         String rsp = this.restClient().get(url).block();
585
586         PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
587         assertThat(info.schema).isNotNull();
588
589         // Get non existing schema
590         url = "/policy-types/JUNK";
591         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
592     }
593
594     String createPolicyTypesJson(String... types) {
595         List<String> list = new ArrayList<>();
596         Collections.addAll(list, types);
597         PolicyTypeIdList ids = new PolicyTypeIdList(list);
598         return gson.toJson(ids);
599     }
600
601     @Test
602     void testGetPolicyTypes() throws Exception {
603         String TYPE_ID_1 = "A_type1_1.9.0";
604         String TYPE_ID_2 = "A_type1_2.0.0";
605         String TYPE_ID_3 = "A_type1_1.5.0";
606         String TYPE_ID_4 = "type3_1.9.0";
607         addPolicyType(TYPE_ID_1, "ric1");
608         addPolicyType(TYPE_ID_2, "ric2");
609         addPolicyType(TYPE_ID_3, "ric2");
610         addPolicyType(TYPE_ID_4, "ric2");
611
612         addPolicyType("junk", "ric2");
613         addPolicyType("junk_a.b.c", "ric2");
614
615         String url = "/policy-types";
616         String rsp = restClient().get(url).block();
617         assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
618
619         url = "/policy-types?ric_id=ric1";
620         rsp = restClient().get(url).block();
621         String expResp = createPolicyTypesJson(TYPE_ID_1);
622         assertThat(rsp).isEqualTo(expResp);
623
624         // Get policy types for non existing RIC
625         url = "/policy-types?ric_id=ric1XXX";
626         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
627
628         // All types with a type_name
629         url = "/policy-types?type_name=A_type1";
630         rsp = restClient().get(url).block();
631         assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
632
633         // All types compatible with type1_1.5.0 (which is type1_1.9.0)
634         url = "/policy-types?type_name=A_type1&&compatible_with_version=1.5.0";
635         rsp = restClient().get(url).block();
636         expResp = createPolicyTypesJson(TYPE_ID_3, TYPE_ID_1);
637         assertThat(rsp).isEqualTo(expResp);
638
639         url = "/policy-types?type_name=A_type1&&compatible_with_version=junk";
640         testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Version must contain major.minor.patch code");
641
642         url = "/policy-types?type_name=A_type1&&compatible_with_version=a.b.c";
643         testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Syntax error in");
644
645         url = "/policy-types?compatible_with_version=1.5.0";
646         testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "type_name");
647     }
648
649     @Test
650     void testGetPolicyInstances() throws Exception {
651         addPolicy("id1", "type1", "service1");
652
653         String url = "/policy-instances";
654         String rsp = restClient().get(url).block();
655         logger.info(rsp);
656         PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
657         assertThat(info.policies).hasSize(1);
658         PolicyInfo policyInfo = info.policies.iterator().next();
659         assert (policyInfo.validate());
660         assertThat(policyInfo.policyId).isEqualTo("id1");
661         assertThat(policyInfo.policyTypeId).isEqualTo("type1");
662         assertThat(policyInfo.serviceId).isEqualTo("service1");
663     }
664
665     @Test
666     void testGetPolicyInstancesFilter() throws Exception {
667         addPolicy("id1", "type1", "service1");
668         addPolicy("id2", "type1", "service2");
669         addPolicy("id3", "type2", "service1");
670         addPolicy("id4", "type1_1.0.0", "service1");
671
672         String url = "/policy-instances?policytype_id=type1";
673         String rsp = restClient().get(url).block();
674         logger.info(rsp);
675         assertThat(rsp).contains("id1") //
676                 .contains("id2") //
677                 .doesNotContain("id3");
678
679         url = "/policy-instances?policytype_id=type1&service_id=service2";
680         rsp = restClient().get(url).block();
681         logger.info(rsp);
682         assertThat(rsp).doesNotContain("id1") //
683                 .contains("id2") //
684                 .doesNotContain("id3");
685
686         url = "/policy-instances?type_name=type1";
687         rsp = restClient().get(url).block();
688         assertThat(rsp).contains("id1") //
689                 .contains("id2") //
690                 .doesNotContain("id3") //
691                 .contains("id4");
692
693         // Test get policies for non existing type
694         url = "/policy-instances?policytype_id=type1XXX";
695         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
696
697         // Test get policies for non existing RIC
698         url = "/policy-instances?ric_id=XXX";
699         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
700     }
701
702     @Test
703     void testGetPolicyIdsFilter() throws Exception {
704         addPolicy("id1", "type1", "service1", "ric1");
705         addPolicy("id2", "type1", "service2", "ric1");
706         addPolicy("id3", "type2", "service1", "ric1");
707         addPolicy("id4", "type1_1.0.0", "service1");
708
709         String url = "/policies?policytype_id=type1";
710         String rsp = restClient().get(url).block();
711         logger.info(rsp);
712         assertThat(rsp).contains("id1") //
713                 .contains("id2") //
714                 .doesNotContain("id3");
715
716         url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
717         rsp = restClient().get(url).block();
718         PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
719         assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
720
721         url = "/policies?policytype_name=type1&service_id=service1";
722         rsp = restClient().get(url).block();
723         assertThat(rsp).contains("id1") //
724                 .contains("id3") //
725                 .contains("id4");
726         assertThat(gson.fromJson(rsp, PolicyIdList.class).policyIds).hasSize(3);
727
728         // Test get policy ids for non existing type
729         url = "/policies?policytype_id=type1XXX";
730         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
731
732         // Test get policy ids for non existing RIC
733         url = "/policies?ric_id=XXX";
734         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
735     }
736
737     @Test
738     void testPutAndGetService() throws Exception {
739         // PUT
740         String serviceName = "ac.dc";
741         putService(serviceName, 0, HttpStatus.CREATED);
742         putService(serviceName, 0, HttpStatus.OK);
743
744         // GET one service
745         String url = "/services?service_id=" + serviceName;
746         String rsp = restClient().get(url).block();
747         ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
748         assertThat(info.statusList).hasSize(1);
749         ServiceStatus status = info.statusList.iterator().next();
750         assertThat(status.keepAliveIntervalSeconds).isZero();
751         assertThat(status.serviceId).isEqualTo(serviceName);
752
753         // GET (all)
754         url = "/services";
755         rsp = restClient().get(url).block();
756         assertThat(rsp).as("Response contains service name").contains(serviceName);
757         logger.info(rsp);
758
759         // Keep alive
760         url = "/services/" + serviceName + "/keepalive";
761         ResponseEntity<?> entity = restClient().putForEntity(url).block();
762         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
763
764         // DELETE service
765         assertThat(services.size()).isEqualTo(1);
766         url = "/services/" + serviceName;
767         restClient().delete(url).block();
768         assertThat(services.size()).isZero();
769
770         // Keep alive, no registered service
771         testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
772
773         // PUT service with bad payload
774         testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
775         testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
776         testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
777                 false);
778         testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
779                 HttpStatus.BAD_REQUEST, false);
780
781         // GET non existing service
782         testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
783     }
784
785     @Test
786     void testServiceSupervision() throws Exception {
787         putService("service1", 1, HttpStatus.CREATED);
788         addPolicyType("type1", "ric1");
789
790         String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
791         restClient().put("/policies", policyBody).block();
792
793         assertThat(policies.size()).isEqualTo(1);
794         assertThat(services.size()).isEqualTo(1);
795
796         // Timeout after ~1 second
797         await().untilAsserted(() -> assertThat(policies.size()).isZero());
798         assertThat(services.size()).isZero();
799     }
800
801     @Test
802     void testGetPolicyStatus() throws Exception {
803         addPolicy("id", "typeName", "service1", "ric1");
804         assertThat(policies.size()).isEqualTo(1);
805
806         String url = "/policies/id/status";
807         String rsp = restClient().get(url).block();
808         PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
809         assertThat(info.status).isEqualTo("OK");
810
811         // GET non existing policy status
812         url = "/policies/XXX/status";
813         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
814
815         // GET STATUS, the NearRT RIC returns error
816         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
817         url = "/policies/id/status";
818         WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
819         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
820         rsp = restClient().get(url).block();
821         info = gson.fromJson(rsp, PolicyStatusInfo.class);
822         assertThat(info.status).hasToString("{}");
823     }
824
825     @Test
826     void testGetServiceStatus() throws Exception {
827         String url = "/status";
828         String rsp = restClient().get(url).block();
829         assertThat(rsp).contains("hunky dory");
830
831         rsp = restClient(baseUrl(), false).get(url).block(); // V1 status is used by a readinessProbe
832         assertThat(rsp).isEqualTo("hunky dory");
833     }
834
835     @Test
836     void testServiceNotification() throws Exception {
837
838         final String AUTH_TOKEN = "testToken";
839         Path authFile = Files.createTempFile("pmsTestAuthToken", ".txt");
840         Files.write(authFile, AUTH_TOKEN.getBytes());
841         this.securityContext.setAuthTokenFilePath(authFile);
842
843         putService("junkService");
844         Service junkService = this.services.get("junkService");
845         junkService.setCallbackUrl("https://junk");
846         putService("service");
847
848         Ric ric = addRic("ric1");
849         ric.setState(Ric.RicState.UNAVAILABLE);
850         supervision.checkAllRics();
851         waitForRicState("ric1", RicState.AVAILABLE);
852
853         final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
854         await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
855         ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
856         assertThat(callbackInfo.ricId).isEqualTo("ric1");
857         assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
858
859         var headers = receivedCallbacks.receivedHeaders.get(0);
860         assertThat(headers).containsEntry("authorization", "Bearer " + AUTH_TOKEN);
861
862         Files.delete(authFile);
863     }
864
865     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
866         addRic(ric);
867         Policy policy = Policy.builder() //
868                 .id(id) //
869                 .json(jsonString()) //
870                 .ownerServiceId(service) //
871                 .ric(rics.getRic(ric)) //
872                 .type(addPolicyType(typeName, ric)) //
873                 .lastModified(Instant.now()) //
874                 .isTransient(false) //
875                 .statusNotificationUri("/policy-status?id=XXX") //
876                 .build();
877         policies.put(policy);
878         return policy;
879     }
880
881     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
882         return addPolicy(id, typeName, service, "ric");
883     }
884
885     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
886         String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
887         return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
888     }
889
890     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
891         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
892
893         String json = gson.toJson(service);
894         return json;
895     }
896
897     private void putService(String name) {
898         putService(name, 0, null);
899     }
900
901     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
902         String url = "/services";
903         String body = createServiceJson(name, keepAliveIntervalSeconds);
904         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
905         if (expectedStatus != null) {
906             assertEquals(expectedStatus, resp.getStatusCode(), "");
907         }
908     }
909
910     private String jsonString() {
911         return "{\"servingCellNrcgi\":\"1\"}";
912     }
913
914     @Test
915     void testConcurrency() throws Exception {
916         logger.info("Concurrency test starting");
917         final Instant startTime = Instant.now();
918         List<Thread> threads = new ArrayList<>();
919         List<ConcurrencyTestRunnable> tests = new ArrayList<>();
920         a1ClientFactory.setResponseDelay(Duration.ofMillis(2));
921         addRic("ric");
922         addPolicyType("type1", "ric");
923         addPolicyType("type2", "ric");
924
925         final String NON_RESPONDING_RIC = "NonRespondingRic";
926         Ric nonRespondingRic = addRic(NON_RESPONDING_RIC);
927         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(NON_RESPONDING_RIC);
928         a1Client.setErrorInject("errorInject");
929
930         for (int i = 0; i < 10; ++i) {
931             AsyncRestClient restClient = restClient();
932             ConcurrencyTestRunnable test =
933                     new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
934             Thread thread = new Thread(test, "TestThread_" + i);
935             thread.start();
936             threads.add(thread);
937             tests.add(test);
938         }
939         for (Thread t : threads) {
940             t.join();
941         }
942         for (ConcurrencyTestRunnable test : tests) {
943             assertThat(test.isFailed()).isFalse();
944         }
945         assertThat(policies.size()).isZero();
946         logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
947
948         assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
949         nonRespondingRic.setState(RicState.AVAILABLE);
950     }
951
952     private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
953         WebClientConfig config = this.applicationConfig.getWebClientConfig();
954         config = WebClientConfig.builder() //
955                 .keyStoreType(config.getKeyStoreType()) //
956                 .keyStorePassword(config.getKeyStorePassword()) //
957                 .keyStore(config.getKeyStore()) //
958                 .keyPassword(config.getKeyPassword()) //
959                 .isTrustStoreUsed(useTrustValidation) //
960                 .trustStore(config.getTrustStore()) //
961                 .trustStorePassword(config.getTrustStorePassword()) //
962                 .httpProxyConfig(config.getHttpProxyConfig()) //
963                 .build();
964
965         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
966         return f.createRestClientNoHttpProxy(baseUrl);
967
968     }
969
970     private String baseUrl() {
971         return "https://localhost:" + port;
972     }
973
974     private AsyncRestClient restClient(boolean useTrustValidation) {
975         return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
976     }
977
978     private AsyncRestClient restClient() {
979         return restClient(false);
980     }
981
982     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
983         testErrorCode(request, expStatus, "", true);
984     }
985
986     private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
987         testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
988     }
989
990     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
991         testErrorCode(request, expStatus, responseContains, true);
992     }
993
994     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
995             boolean expectApplicationProblemJsonMediaType) {
996         StepVerifier.create(request) //
997                 .expectSubscription() //
998                 .expectErrorMatches(
999                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
1000                 .verify();
1001     }
1002
1003     private void waitForRicState(String ricId, RicState state) throws ServiceException {
1004         Ric ric = rics.getRic(ricId);
1005         await().untilAsserted(() -> state.equals(ric.getState()));
1006     }
1007
1008     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
1009             boolean expectApplicationProblemJsonMediaType) {
1010         assertTrue(throwable instanceof WebClientResponseException);
1011         WebClientResponseException responseException = (WebClientResponseException) throwable;
1012         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
1013         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
1014         if (expectApplicationProblemJsonMediaType) {
1015             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
1016         }
1017         return true;
1018     }
1019
1020     private MockA1Client getA1Client(String ricId) throws ServiceException {
1021         return a1ClientFactory.getOrCreateA1Client(ricId);
1022     }
1023
1024     private PolicyType createPolicyType(String policyTypeName) {
1025         return PolicyType.builder() //
1026                 .id(policyTypeName) //
1027                 .schema("{\"title\":\"" + policyTypeName + "\"}") //
1028                 .build();
1029     }
1030
1031     private PolicyType addPolicyType(String policyTypeName, String ricId) {
1032         PolicyType type = createPolicyType(policyTypeName);
1033         policyTypes.put(type);
1034         addRic(ricId).addSupportedPolicyType(type);
1035         return type;
1036     }
1037
1038     private Ric addRic(String ricId) {
1039         return addRic(ricId, null);
1040     }
1041
1042     private RicConfig ricConfig(String ricId, String managedElement) {
1043         List<String> mes = new ArrayList<>();
1044         if (managedElement != null) {
1045             mes.add(managedElement);
1046         }
1047         return RicConfig.builder() //
1048                 .ricId(ricId) //
1049                 .baseUrl(ricId) //
1050                 .managedElementIds(mes) //
1051                 .build();
1052     }
1053
1054     private Ric addRic(String ricId, String managedElement) {
1055         if (rics.get(ricId) != null) {
1056             return rics.get(ricId);
1057         }
1058
1059         RicConfig conf = ricConfig(ricId, managedElement);
1060         Ric ric = new Ric(conf);
1061         ric.setState(Ric.RicState.AVAILABLE);
1062         this.rics.put(ric);
1063         return ric;
1064     }
1065
1066 }