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