2 * ========================LICENSE_START=================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
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;
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.PrintStream;
36 import java.lang.invoke.MethodHandles;
37 import java.nio.charset.StandardCharsets;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.time.Duration;
42 import java.time.Instant;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.List;
47 import org.json.JSONObject;
48 import org.junit.jupiter.api.AfterAll;
49 import org.junit.jupiter.api.AfterEach;
50 import org.junit.jupiter.api.MethodOrderer;
51 import org.junit.jupiter.api.Test;
52 import org.junit.jupiter.api.TestMethodOrder;
53 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
54 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
55 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
56 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
57 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
58 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
59 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
60 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
61 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbackInfo;
62 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
67 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
68 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
69 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
70 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
71 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
72 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
73 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
74 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
75 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
76 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
77 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
78 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.boot.test.context.SpringBootTest;
83 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
84 import org.springframework.boot.test.context.TestConfiguration;
85 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
86 import org.springframework.boot.web.server.LocalServerPort;
87 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
88 import org.springframework.context.ApplicationContext;
89 import org.springframework.context.annotation.Bean;
90 import org.springframework.http.HttpStatus;
91 import org.springframework.http.MediaType;
92 import org.springframework.http.ResponseEntity;
93 import org.springframework.test.context.TestPropertySource;
94 import org.springframework.util.FileSystemUtils;
95 import org.springframework.web.reactive.function.client.WebClientRequestException;
96 import org.springframework.web.reactive.function.client.WebClientResponseException;
98 import reactor.core.publisher.Mono;
99 import reactor.test.StepVerifier;
100 import reactor.util.annotation.Nullable;
102 @TestMethodOrder(MethodOrderer.MethodName.class)
103 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
104 @TestPropertySource(properties = { //
105 "server.ssl.key-store=./config/keystore.jks", //
106 "app.webclient.trust-store=./config/truststore.jks", //
107 "app.webclient.trust-store-used=true", //
108 "app.vardata-directory=/tmp/pmstest", //
110 "app.s3.bucket=" // If this is set, S3 will be used to store data.
112 class ApplicationTest {
113 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
116 ApplicationContext context;
122 private Policies policies;
125 private PolicyTypes policyTypes;
128 MockA1ClientFactory a1ClientFactory;
131 RicSupervision supervision;
134 ApplicationConfig applicationConfig;
140 RappSimulatorController rAppSimulator;
143 RefreshConfigTask refreshConfigTask;
146 SecurityContext securityContext;
148 private static Gson gson = new GsonBuilder().create();
151 * Overrides the BeanFactory.
154 static class TestBeanFactory {
157 A1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
158 return new MockA1ClientFactory(appConfig, types);
162 public ServiceSupervision getServiceSupervision(@Autowired Services services,
163 @Autowired A1ClientFactory a1ClientFactory, @Autowired Policies policies) {
164 Duration checkInterval = Duration.ofMillis(1);
165 return new ServiceSupervision(services, policies, a1ClientFactory, checkInterval);
169 public ServletWebServerFactory servletContainer() {
170 return new TomcatServletWebServerFactory();
183 a1ClientFactory.reset();
184 this.rAppSimulator.getTestResults().clear();
185 this.a1ClientFactory.setPolicyTypes(policyTypes); // Default same types in RIC and in this app
186 this.securityContext.setAuthTokenFilePath(null);
190 static void clearTestDir() {
192 FileSystemUtils.deleteRecursively(Path.of("/tmp/pmstest"));
193 } catch (Exception e) {
194 logger.warn("Could test directory : {}", e.getMessage());
199 void verifyNoRicLocks() {
200 for (Ric ric : this.rics.getRics()) {
201 Lock.Grant grant = ric.getLock().lockBlocking(LockType.EXCLUSIVE, "verifyNoRicLocks");
202 grant.unlockBlocking();
203 assertThat(ric.getLock().getLockCounter()).isZero();
204 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
209 @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
210 void testZZActuator() throws Exception {
211 // The test must be run last, hence the "ZZ" in the name. All succeeding tests
213 AsyncRestClient client = restClient(baseUrl(), false);
215 client.post("/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice",
216 "{\"configuredLevel\":\"trace\"}").block();
218 String resp = client.get("/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice").block();
219 assertThat(resp).contains("TRACE");
221 client.post("/actuator/loggers/org.springframework.boot.actuate", "{\"configuredLevel\":\"trace\"}").block();
223 // This will stop the web server and all coming tests will fail.
224 client.post("/actuator/shutdown", "").block();
228 StepVerifier.create(restClient().get("/rics")) // Any call
229 .expectSubscription() //
230 .expectErrorMatches(t -> t instanceof WebClientRequestException) //
236 void generateApiDoc() throws IOException {
237 String url = "https://localhost:" + this.port + "/v3/api-docs";
238 ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
239 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
240 JSONObject jsonObj = new JSONObject(resp.getBody());
241 assertThat(jsonObj.remove("servers")).isNotNull();
243 String indented = (jsonObj).toString(4);
244 String docDir = "api/";
245 Files.createDirectories(Paths.get(docDir));
246 try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "pms-api.json"))) {
252 void testPersistencyPolicies() throws Exception {
253 Ric ric = this.addRic("ric1");
254 PolicyType type = this.addPolicyType("type1", ric.id());
256 final int noOfPolicies = 100;
257 for (int i = 0; i < noOfPolicies; ++i) {
258 addPolicy("id" + i, type.getId(), "service", ric.id());
263 Policies policies = new Policies(this.applicationConfig);
264 policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
265 assertThat(policies.size()).isEqualTo(noOfPolicies);
269 restClient().delete("/policies/id2").block();
270 Policies policies = new Policies(this.applicationConfig);
271 policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
272 assertThat(policies.size()).isEqualTo(noOfPolicies - 1);
277 void testPersistencyPolicyTypes() throws Exception {
278 Ric ric = this.addRic("ric1");
279 this.addPolicyType("type1", ric.id());
282 PolicyTypes types = new PolicyTypes(this.applicationConfig);
283 types.restoreFromDatabase().blockLast();
284 assertThat(types.size()).isEqualTo(1);
287 @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
288 private void waitforS3() throws Exception {
289 if (applicationConfig.isS3Enabled()) {
295 void testPersistencyService() throws Exception {
296 final String SERVICE = "serviceName";
297 putService(SERVICE, 1234, HttpStatus.CREATED);
298 assertThat(this.services.size()).isEqualTo(1);
299 Service service = this.services.getService(SERVICE);
302 Services servicesRestored = new Services(this.applicationConfig);
303 servicesRestored.restoreFromDatabase().blockLast();
304 Service serviceRestored = servicesRestored.getService(SERVICE);
305 assertThat(servicesRestored.size()).isEqualTo(1);
306 assertThat(serviceRestored.getCallbackUrl()).isEqualTo(service.getCallbackUrl());
307 assertThat(serviceRestored.getKeepAliveInterval()).isEqualTo(service.getKeepAliveInterval());
309 // check that the service can be deleted
310 this.services.remove(SERVICE);
311 servicesRestored = new Services(this.applicationConfig);
312 assertThat(servicesRestored.size()).isZero();
316 void testAddingRicFromConfiguration() throws Exception {
317 // Test adding the RIC from configuration
319 final String RIC = "ric1";
320 final String TYPE = "type123";
321 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
322 nearRtRicPolicyTypes.put(createPolicyType(TYPE));
323 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
325 putService("service");
327 refreshConfigTask.handleUpdatedRicConfig( //
328 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
330 waitForRicState(RIC, RicState.AVAILABLE);
332 // Test that the type has been synched
333 Ric addedRic = this.rics.getRic(RIC);
334 assertThat(addedRic.getSupportedPolicyTypes()).hasSize(1);
335 assertThat(addedRic.getSupportedPolicyTypes().iterator().next().getId()).isEqualTo(TYPE);
337 // Check that a service callback for the AVAILABLE RIC is invoked
338 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
339 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
340 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
341 assertThat(callbackInfo.ricId).isEqualTo(RIC);
342 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
346 void testAddingRicFromConfiguration_nonRespondingRic() throws Exception {
347 putService("service");
349 final String RIC = "NonRespondingRic";
350 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(RIC);
351 doReturn(MockA1Client.monoError("error", HttpStatus.BAD_GATEWAY)).when(a1Client).getPolicyTypeIdentities();
353 refreshConfigTask.handleUpdatedRicConfig( //
354 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
357 waitForRicState(RIC, RicState.UNAVAILABLE);
359 // Check that no service callback for the UNAVAILABLE RIC is invoked
360 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
361 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).isEmpty());
363 // Run a synch and check that the AVAILABLE notification is received
364 a1ClientFactory.reset();
365 supervision.checkAllRics();
366 waitForRicState(RIC, RicState.AVAILABLE);
368 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
372 void testTrustValidation() {
375 String rsp = restClient(true).get("/rics").block(); // restClient(true) enables trust validation
376 assertThat(rsp).contains("ric1");
381 void testGetRics() throws Exception {
383 this.addPolicyType("type1", "ric1");
384 String url = "/rics?policytype_id=type1";
385 String rsp = restClient().get(url).block();
386 assertThat(rsp).contains("ric1");
388 // nameless type for ORAN A1 1.1
390 this.addPolicyType("", "ric2");
391 url = "/rics?policytype_id=";
392 rsp = restClient().get(url).block();
393 assertThat(rsp).contains("ric2") //
394 .doesNotContain("ric1") //
395 .contains("AVAILABLE");
398 rsp = restClient().get("/rics").block();
399 assertThat(rsp).contains("ric2") //
402 // Non existing policy type
403 url = "/rics?policytype_id=XXXX";
404 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
408 void testSynchronization() throws Exception {
409 // Two polictypes will be put in the NearRT RICs
410 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
411 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
412 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
413 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
415 // One type and one instance added to the Policy Management Service's storage
416 final String ric1Name = "ric1";
417 Ric ric1 = addRic(ric1Name);
418 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
419 Ric ric2 = addRic("ric2");
421 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
422 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
424 String policyId = "policyId";
425 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
426 supervision.checkAllRics(); // The created policy should be put in the RIC
428 // Wait until synch is completed
429 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
430 waitForRicState(ric1Name, RicState.AVAILABLE);
431 waitForRicState("ric2", RicState.AVAILABLE);
433 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
434 assertThat(ricPolicies.size()).isEqualTo(1);
435 Policy ricPolicy = ricPolicies.get(policyId);
436 assertThat(ricPolicy.getJson()).isEqualTo(policy.getJson());
438 // Both types should be in the Policy Management Service's storage after the
440 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
441 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
445 void testGetRic() throws Exception {
446 String ricId = "ric1";
447 String managedElementId = "kista_1";
448 addRic(ricId, managedElementId);
450 String url = "/rics/ric?managed_element_id=" + managedElementId;
451 String rsp = restClient().get(url).block();
452 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
453 assertThat(ricInfo.ricId).isEqualTo(ricId);
455 url = "/rics/ric?ric_id=" + ricId;
456 rsp = restClient().get(url).block();
457 ricInfo = gson.fromJson(rsp, RicInfo.class);
458 assertThat(ricInfo.ricId).isEqualTo(ricId);
460 // test GET RIC for ManagedElement that does not exist
461 url = "/rics/ric?managed_element_id=" + "junk";
462 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
465 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
468 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
469 boolean isTransient, String statusNotificationUri) {
470 PolicyInfo info = new PolicyInfo();
471 info.policyId = policyInstanceId;
472 info.policyTypeId = policyTypeName;
474 info.serviceId = serviceName;
475 info.policyData = gson.fromJson(jsonString(), Object.class);
478 info.isTransient = isTransient;
480 info.statusNotificationUri = statusNotificationUri;
481 return gson.toJson(info);
484 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
485 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false, "statusUri");
489 void testPutPolicy() throws Exception {
490 String serviceName = "service.1";
491 String ricId = "ric.1";
492 String policyTypeName = "type1_1.2.3";
493 String policyInstanceId = "instance_1.2.3";
495 putService(serviceName);
496 addPolicyType(policyTypeName, ricId);
498 // PUT a transient policy
499 String url = "/policies";
500 String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true, "statusNotif");
501 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
503 restClient().put(url, policyBody).block();
505 Policy policy = policies.getPolicy(policyInstanceId);
506 assertThat(policy).isNotNull();
507 assertThat(policy.getId()).isEqualTo(policyInstanceId);
508 assertThat(policy.getOwnerServiceId()).isEqualTo(serviceName);
509 assertThat(policy.getRic().id()).isEqualTo(ricId);
510 assertThat(policy.isTransient()).isTrue();
512 // Put a non transient policy
513 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
514 restClient().put(url, policyBody).block();
515 policy = policies.getPolicy(policyInstanceId);
516 assertThat(policy.isTransient()).isFalse();
518 url = "/policy-instances";
519 String rsp = restClient().get(url).block();
520 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
522 url = "/policies/" + policyInstanceId;
523 rsp = restClient().get(url).block();
524 assertThat(rsp).contains(policyBody);
526 // Test of error codes
528 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
529 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
531 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
532 addPolicyType(policyTypeName + "XX", "otherRic");
533 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
535 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
536 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
537 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
538 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
542 void testPutPolicy_NoServiceNoStatusUri() throws Exception {
543 String ricId = "ric.1";
544 String policyTypeName = "type1_1.2.3";
545 String policyInstanceId = "instance_1.2.3";
547 addPolicyType(policyTypeName, ricId);
549 // PUT a transient policy
550 String url = "/policies";
551 String policyBody = putPolicyBody(null, ricId, policyTypeName, policyInstanceId, true, null);
552 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
554 restClient().put(url, policyBody).block();
556 Policy policy = policies.getPolicy(policyInstanceId);
557 assertThat(policy).isNotNull();
558 assertThat(policy.getOwnerServiceId()).isBlank();
559 assertThat(policy.getStatusNotificationUri()).isBlank();
564 * Test that HttpStatus and body from failing REST call to A1 is passed on to
567 * @throws ServiceException
569 void testErrorFromRic() throws ServiceException {
570 putService("service1");
571 addPolicyType("type1", "ric1");
573 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
574 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
575 String responseBody = "Refused";
576 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
578 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
579 responseBodyBytes, StandardCharsets.UTF_8, null);
580 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
583 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
584 String url = "/policies";
585 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
588 this.addPolicy("instance1", "type1", "service1", "ric1");
589 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
590 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
595 void testPutTypelessPolicy() throws Exception {
596 putService("service1");
597 addPolicyType("", "ric1");
598 String body = putPolicyBody("service1", "ric1", "", "id1");
599 restClient().put("/policies", body).block();
601 String rsp = restClient().get("/policy-instances").block();
602 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
603 assertThat(info.policies).hasSize(1);
604 PolicyInfo policyInfo = info.policies.iterator().next();
605 assertThat(policyInfo.policyId).isEqualTo("id1");
606 assertThat(policyInfo.policyTypeId).isEmpty();
610 void testUpdateService() throws Exception {
612 this.addPolicy("p", "type1", "", "ric1");
614 String url = "/policies?service_id=";
615 String resp = restClient().get(url).block();
616 assertThat(resp).contains("[\"p\"]");
618 this.addPolicy("p", "type1", "service", "ric1");
619 url = "/policies?service_id=";
620 resp = restClient().get(url).block();
621 assertThat(resp).contains("[]");
623 url = "/policies?service_id=service";
624 resp = restClient().get(url).block();
625 assertThat(resp).contains("[\"p\"]");
629 void testRefuseToUpdatePolicy() throws Exception {
630 // Test that only the json can be changed for a already created policy
631 // In this case service is attempted to be changed
633 this.addRic("ricXXX");
634 this.addPolicy("instance1", "type1", "service1", "ric1");
635 this.addPolicy("instance2", "type1", "service1", "ricXXX");
637 // Try change ric1 -> ricXXX
638 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
639 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
643 void testGetPolicy() throws Exception {
644 String url = "/policies/id";
645 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
647 String rsp = restClient().get(url).block();
648 PolicyInfo info = gson.fromJson(rsp, PolicyInfo.class);
649 String policyStr = gson.toJson(info.policyData);
650 assertThat(policyStr).isEqualTo(policy.getJson());
653 policies.remove(policy);
654 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
659 void testDeletePolicy() throws Exception {
660 String policyId = "id.1";
661 addPolicy(policyId, "typeName", "service1", "ric1");
662 assertThat(policies.size()).isEqualTo(1);
664 String url = "/policies/" + policyId;
665 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
667 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
668 assertThat(policies.size()).isZero();
670 // Delete a non existing policy
671 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
675 void testGetPolicyType() throws Exception {
676 String typeId = "AC.D";
677 addPolicyType(typeId, "ric1");
679 waitForRicState("ric1", RicState.AVAILABLE);
681 String url = "/policy-types/" + typeId;
683 String rsp = this.restClient().get(url).block();
685 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
686 assertThat(info.schema).isNotNull();
688 // Get non existing schema
689 url = "/policy-types/JUNK";
690 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
693 String createPolicyTypesJson(String... types) {
694 List<String> list = new ArrayList<>();
695 Collections.addAll(list, types);
696 PolicyTypeIdList ids = new PolicyTypeIdList(list);
697 return gson.toJson(ids);
701 void testGetPolicyTypes() throws Exception {
702 String TYPE_ID_1 = "A_type1_1.9.0";
703 String TYPE_ID_2 = "A_type1_2.0.0";
704 String TYPE_ID_3 = "A_type1_1.5.0";
705 String TYPE_ID_4 = "type3_1.9.0";
706 addPolicyType(TYPE_ID_1, "ric1");
707 addPolicyType(TYPE_ID_2, "ric2");
708 addPolicyType(TYPE_ID_3, "ric2");
709 addPolicyType(TYPE_ID_4, "ric2");
711 addPolicyType("junk", "ric2");
712 addPolicyType("junk_a.b.c", "ric2");
714 String url = "/policy-types";
715 String rsp = restClient().get(url).block();
716 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
718 url = "/policy-types?ric_id=ric1";
719 rsp = restClient().get(url).block();
720 String expResp = createPolicyTypesJson(TYPE_ID_1);
721 assertThat(rsp).isEqualTo(expResp);
723 // Get policy types for non existing RIC
724 url = "/policy-types?ric_id=ric1XXX";
725 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
727 // All types with a type_name
728 url = "/policy-types?type_name=A_type1";
729 rsp = restClient().get(url).block();
730 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
732 // All types compatible with type1_1.5.0 (which is type1_1.9.0)
733 url = "/policy-types?type_name=A_type1&&compatible_with_version=1.5.0";
734 rsp = restClient().get(url).block();
735 expResp = createPolicyTypesJson(TYPE_ID_3, TYPE_ID_1);
736 assertThat(rsp).isEqualTo(expResp);
738 url = "/policy-types?type_name=A_type1&&compatible_with_version=junk";
739 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Version must contain major.minor.patch code");
741 url = "/policy-types?type_name=A_type1&&compatible_with_version=a.b.c";
742 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Syntax error in");
744 url = "/policy-types?compatible_with_version=1.5.0";
745 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "type_name");
749 void testGetPolicyInstances() throws Exception {
750 addPolicy("id1", "type1", "service1");
752 String url = "/policy-instances";
753 String rsp = restClient().get(url).block();
755 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
756 assertThat(info.policies).hasSize(1);
757 PolicyInfo policyInfo = info.policies.iterator().next();
758 assert (policyInfo.validate());
759 assertThat(policyInfo.policyId).isEqualTo("id1");
760 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
761 assertThat(policyInfo.serviceId).isEqualTo("service1");
765 void testGetPolicyInstancesFilter() throws Exception {
766 addPolicy("id1", "type1", "service1");
767 addPolicy("id2", "type1", "service2");
768 addPolicy("id3", "type2", "service1");
769 addPolicy("id4", "type1_1.0.0", "service1");
771 String url = "/policy-instances?policytype_id=type1";
772 String rsp = restClient().get(url).block();
774 assertThat(rsp).contains("id1") //
776 .doesNotContain("id3");
778 url = "/policy-instances?policytype_id=type1&service_id=service2";
779 rsp = restClient().get(url).block();
781 assertThat(rsp).doesNotContain("id1") //
783 .doesNotContain("id3");
785 url = "/policy-instances?type_name=type1";
786 rsp = restClient().get(url).block();
787 assertThat(rsp).contains("id1") //
789 .doesNotContain("id3") //
792 // Test get policies for non existing type
793 url = "/policy-instances?policytype_id=type1XXX";
794 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
796 // Test get policies for non existing RIC
797 url = "/policy-instances?ric_id=XXX";
798 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
802 void testGetPolicyIdsFilter() throws Exception {
803 addPolicy("id1", "type1", "service1", "ric1");
804 addPolicy("id2", "type1", "service2", "ric1");
805 addPolicy("id3", "type2", "service1", "ric1");
806 addPolicy("id4", "type1_1.0.0", "service1");
808 String url = "/policies?policytype_id=type1";
809 String rsp = restClient().get(url).block();
811 assertThat(rsp).contains("id1") //
813 .doesNotContain("id3");
815 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
816 rsp = restClient().get(url).block();
817 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
818 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
820 url = "/policies?policytype_name=type1&service_id=service1";
821 rsp = restClient().get(url).block();
822 assertThat(rsp).contains("id1") //
825 assertThat(gson.fromJson(rsp, PolicyIdList.class).policyIds).hasSize(3);
827 // Test get policy ids for non existing type
828 url = "/policies?policytype_id=type1XXX";
829 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
831 // Test get policy ids for non existing RIC
832 url = "/policies?ric_id=XXX";
833 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
837 void testPutAndGetService() throws Exception {
839 String serviceName = "ac.dc";
840 putService(serviceName, 0, HttpStatus.CREATED);
841 putService(serviceName, 0, HttpStatus.OK);
844 String url = "/services?service_id=" + serviceName;
845 String rsp = restClient().get(url).block();
846 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
847 assertThat(info.statusList).hasSize(1);
848 ServiceStatus status = info.statusList.iterator().next();
849 assertThat(status.keepAliveIntervalSeconds).isZero();
850 assertThat(status.serviceId).isEqualTo(serviceName);
854 rsp = restClient().get(url).block();
855 assertThat(rsp).as("Response contains service name").contains(serviceName);
859 url = "/services/" + serviceName + "/keepalive";
860 ResponseEntity<?> entity = restClient().putForEntity(url).block();
861 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
864 assertThat(services.size()).isEqualTo(1);
865 url = "/services/" + serviceName;
866 restClient().delete(url).block();
867 assertThat(services.size()).isZero();
869 // Keep alive, no registered service
870 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
872 // PUT service with bad payload
873 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
874 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
875 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
877 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
878 HttpStatus.BAD_REQUEST, false);
880 // GET non existing service
881 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
885 void testServiceSupervision() throws Exception {
886 putService("service1", 1, HttpStatus.CREATED);
887 addPolicyType("type1", "ric1");
889 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
890 restClient().put("/policies", policyBody).block();
892 assertThat(policies.size()).isEqualTo(1);
893 assertThat(services.size()).isEqualTo(1);
895 // Timeout after ~1 second
896 await().untilAsserted(() -> assertThat(policies.size()).isZero());
897 assertThat(services.size()).isZero();
901 void testGetPolicyStatus() throws Exception {
902 addPolicy("id", "typeName", "service1", "ric1");
903 assertThat(policies.size()).isEqualTo(1);
905 String url = "/policies/id/status";
906 String rsp = restClient().get(url).block();
907 PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
908 assertThat(info.status).isEqualTo("OK");
910 // GET non existing policy status
911 url = "/policies/XXX/status";
912 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
914 // GET STATUS, the NearRT RIC returns error
915 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
916 url = "/policies/id/status";
917 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
918 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
919 rsp = restClient().get(url).block();
920 info = gson.fromJson(rsp, PolicyStatusInfo.class);
921 assertThat(info.status).hasToString("{}");
925 void testGetServiceStatus() throws Exception {
926 String url = "/status";
927 String rsp = restClient().get(url).block();
928 assertThat(rsp).contains("hunky dory");
930 rsp = restClient(baseUrl(), false).get(url).block(); // V1 status is used by a readinessProbe
931 assertThat(rsp).isEqualTo("hunky dory");
935 void testServiceNotification() throws Exception {
937 final String AUTH_TOKEN = "testToken";
938 Path authFile = Files.createTempFile("pmsTestAuthToken", ".txt");
939 Files.write(authFile, AUTH_TOKEN.getBytes());
940 this.securityContext.setAuthTokenFilePath(authFile);
942 putService("junkService");
943 Service junkService = this.services.get("junkService");
944 junkService.setCallbackUrl("https://junk");
945 putService("service");
947 Ric ric = addRic("ric1");
948 ric.setState(Ric.RicState.UNAVAILABLE);
949 supervision.checkAllRics();
950 waitForRicState("ric1", RicState.AVAILABLE);
952 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
953 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
954 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
955 assertThat(callbackInfo.ricId).isEqualTo("ric1");
956 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
958 var headers = receivedCallbacks.receivedHeaders.get(0);
959 assertThat(headers).containsEntry("authorization", "Bearer " + AUTH_TOKEN);
961 Files.delete(authFile);
964 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
966 Policy policy = Policy.builder() //
968 .json(jsonString()) //
969 .ownerServiceId(service) //
970 .ric(rics.getRic(ric)) //
971 .type(addPolicyType(typeName, ric)) //
972 .lastModified(Instant.now()) //
973 .isTransient(false) //
974 .statusNotificationUri("/policy-status?id=XXX") //
976 policies.put(policy);
980 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
981 return addPolicy(id, typeName, service, "ric");
984 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
985 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
986 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
989 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
990 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
992 String json = gson.toJson(service);
996 private void putService(String name) {
997 putService(name, 0, null);
1000 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
1001 String url = "/services";
1002 String body = createServiceJson(name, keepAliveIntervalSeconds);
1003 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
1004 if (expectedStatus != null) {
1005 assertEquals(expectedStatus, resp.getStatusCode(), "");
1009 private String jsonString() {
1010 return "{\"servingCellNrcgi\":\"1\"}";
1014 void testConcurrency() throws Exception {
1015 logger.info("Concurrency test starting");
1016 final Instant startTime = Instant.now();
1017 List<Thread> threads = new ArrayList<>();
1018 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
1019 a1ClientFactory.setResponseDelay(Duration.ofMillis(2));
1021 addPolicyType("type1", "ric");
1022 addPolicyType("type2", "ric");
1024 final String NON_RESPONDING_RIC = "NonRespondingRic";
1025 Ric nonRespondingRic = addRic(NON_RESPONDING_RIC);
1026 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(NON_RESPONDING_RIC);
1027 a1Client.setErrorInject("errorInject");
1029 for (int i = 0; i < 10; ++i) {
1030 AsyncRestClient restClient = restClient();
1031 ConcurrencyTestRunnable test =
1032 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
1033 Thread thread = new Thread(test, "TestThread_" + i);
1035 threads.add(thread);
1038 for (Thread t : threads) {
1041 for (ConcurrencyTestRunnable test : tests) {
1042 assertThat(test.isFailed()).isFalse();
1044 assertThat(policies.size()).isZero();
1045 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
1047 assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
1048 nonRespondingRic.setState(RicState.AVAILABLE);
1051 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
1052 WebClientConfig config = this.applicationConfig.getWebClientConfig();
1053 config = WebClientConfig.builder() //
1054 .keyStoreType(config.getKeyStoreType()) //
1055 .keyStorePassword(config.getKeyStorePassword()) //
1056 .keyStore(config.getKeyStore()) //
1057 .keyPassword(config.getKeyPassword()) //
1058 .isTrustStoreUsed(useTrustValidation) //
1059 .trustStore(config.getTrustStore()) //
1060 .trustStorePassword(config.getTrustStorePassword()) //
1061 .httpProxyConfig(config.getHttpProxyConfig()) //
1064 AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
1065 return f.createRestClientNoHttpProxy(baseUrl);
1069 private String baseUrl() {
1070 return "https://localhost:" + port;
1073 private AsyncRestClient restClient(boolean useTrustValidation) {
1074 return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
1077 private AsyncRestClient restClient() {
1078 return restClient(false);
1081 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
1082 testErrorCode(request, expStatus, "", true);
1085 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
1086 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
1089 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
1090 testErrorCode(request, expStatus, responseContains, true);
1093 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
1094 boolean expectApplicationProblemJsonMediaType) {
1095 StepVerifier.create(request) //
1096 .expectSubscription() //
1097 .expectErrorMatches(
1098 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
1102 private void waitForRicState(String ricId, RicState state) throws ServiceException {
1103 Ric ric = rics.getRic(ricId);
1104 await().untilAsserted(() -> state.equals(ric.getState()));
1107 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
1108 boolean expectApplicationProblemJsonMediaType) {
1109 assertTrue(throwable instanceof WebClientResponseException);
1110 WebClientResponseException responseException = (WebClientResponseException) throwable;
1111 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
1112 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
1113 if (expectApplicationProblemJsonMediaType) {
1114 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
1119 private MockA1Client getA1Client(String ricId) throws ServiceException {
1120 return a1ClientFactory.getOrCreateA1Client(ricId);
1123 private PolicyType createPolicyType(String policyTypeName) {
1124 return PolicyType.builder() //
1125 .id(policyTypeName) //
1126 .schema("{\"title\":\"" + policyTypeName + "\"}") //
1130 private PolicyType addPolicyType(String policyTypeName, String ricId) {
1131 PolicyType type = createPolicyType(policyTypeName);
1132 policyTypes.put(type);
1133 addRic(ricId).addSupportedPolicyType(type);
1137 private Ric addRic(String ricId) {
1138 return addRic(ricId, null);
1141 private RicConfig ricConfig(String ricId, String managedElement) {
1142 List<String> mes = new ArrayList<>();
1143 if (managedElement != null) {
1144 mes.add(managedElement);
1146 return RicConfig.builder() //
1149 .managedElementIds(mes) //
1153 private Ric addRic(String ricId, String managedElement) {
1154 if (rics.get(ricId) != null) {
1155 return rics.get(ricId);
1158 RicConfig conf = ricConfig(ricId, managedElement);
1159 Ric ric = new Ric(conf);
1160 ric.setState(Ric.RicState.AVAILABLE);