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.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;
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;
94 import reactor.core.publisher.Mono;
95 import reactor.test.StepVerifier;
96 import reactor.util.annotation.Nullable;
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", //
105 "app.s3.bucket=" // If this is set, S3 will be used to store data.
107 class ApplicationTest {
108 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
111 ApplicationContext context;
117 private Policies policies;
120 private PolicyTypes policyTypes;
123 MockA1ClientFactory a1ClientFactory;
126 RicSupervision supervision;
129 ApplicationConfig applicationConfig;
135 RappSimulatorController rAppSimulator;
138 RefreshConfigTask refreshConfigTask;
141 SecurityContext securityContext;
143 private static Gson gson = new GsonBuilder().create();
146 * Overrides the BeanFactory.
149 static class TestBeanFactory {
152 A1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
153 return new MockA1ClientFactory(appConfig, types);
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);
164 public ServletWebServerFactory servletContainer() {
165 return new TomcatServletWebServerFactory();
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);
185 static void clearTestDir() {
187 FileSystemUtils.deleteRecursively(Path.of("/tmp/pmstest"));
188 } catch (Exception e) {
189 logger.warn("Could test directory : {}", e.getMessage());
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);
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();
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"))) {
220 void testPersistencyPolicies() throws Exception {
221 Ric ric = this.addRic("ric1");
222 PolicyType type = this.addPolicyType("type1", ric.id());
224 final int noOfPolicies = 100;
225 for (int i = 0; i < noOfPolicies; ++i) {
226 addPolicy("id" + i, type.getId(), "service", ric.id());
231 Policies policies = new Policies(this.applicationConfig);
232 policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
233 assertThat(policies.size()).isEqualTo(noOfPolicies);
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);
245 void testPersistencyPolicyTypes() throws Exception {
246 Ric ric = this.addRic("ric1");
247 this.addPolicyType("type1", ric.id());
250 PolicyTypes types = new PolicyTypes(this.applicationConfig);
251 types.restoreFromDatabase().blockLast();
252 assertThat(types.size()).isEqualTo(1);
255 @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
256 private void waitforS3() throws Exception {
257 if (applicationConfig.isS3Enabled()) {
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);
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());
277 // check that the service can be deleted
278 this.services.remove(SERVICE);
279 servicesRestored = new Services(this.applicationConfig);
280 assertThat(servicesRestored.size()).isZero();
284 void testAddingRicFromConfiguration() throws Exception {
285 // Test adding the RIC from configuration
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);
293 putService("service");
295 refreshConfigTask.handleUpdatedRicConfig( //
296 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
298 waitForRicState(RIC, RicState.AVAILABLE);
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);
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);
314 void testAddingRicFromConfiguration_nonRespondingRic() throws Exception {
315 putService("service");
317 final String RIC = "NonRespondingRic";
318 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(RIC);
319 doReturn(MockA1Client.monoError("error", HttpStatus.BAD_GATEWAY)).when(a1Client).getPolicyTypeIdentities();
321 refreshConfigTask.handleUpdatedRicConfig( //
322 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
325 waitForRicState(RIC, RicState.UNAVAILABLE);
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());
331 // Run a synch and check that the AVAILABLE notification is received
332 a1ClientFactory.reset();
333 supervision.checkAllRics();
334 waitForRicState(RIC, RicState.AVAILABLE);
336 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
340 void testTrustValidation() {
343 String rsp = restClient(true).get("/rics").block(); // restClient(true) enables trust validation
344 assertThat(rsp).contains("ric1");
349 void testGetRics() throws Exception {
351 this.addPolicyType("type1", "ric1");
352 String url = "/rics?policytype_id=type1";
353 String rsp = restClient().get(url).block();
354 assertThat(rsp).contains("ric1");
356 // nameless type for ORAN A1 1.1
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");
366 rsp = restClient().get("/rics").block();
367 assertThat(rsp).contains("ric2") //
370 // Non existing policy type
371 url = "/rics?policytype_id=XXXX";
372 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
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);
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");
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
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
396 // Wait until synch is completed
397 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
398 waitForRicState(ric1Name, RicState.AVAILABLE);
399 waitForRicState("ric2", RicState.AVAILABLE);
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());
406 // Both types should be in the Policy Management Service's storage after the
408 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
409 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
413 void testGetRic() throws Exception {
414 String ricId = "ric1";
415 String managedElementId = "kista_1";
416 addRic(ricId, managedElementId);
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);
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);
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);
433 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
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;
442 info.serviceId = serviceName;
443 info.policyData = gson.fromJson(jsonString(), Object.class);
446 info.isTransient = isTransient;
448 info.statusNotificationUri = "statusNotificationUri";
449 return gson.toJson(info);
452 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
453 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false);
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";
463 putService(serviceName);
464 addPolicyType(policyTypeName, ricId);
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);
471 restClient().put(url, policyBody).block();
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();
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();
486 url = "/policy-instances";
487 String rsp = restClient().get(url).block();
488 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
490 url = "/policies/" + policyInstanceId;
491 rsp = restClient().get(url).block();
492 assertThat(rsp).contains(policyBody);
494 // Test of error codes
496 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
497 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
499 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
500 addPolicyType(policyTypeName + "XX", "otherRic");
501 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
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);
511 * Test that HttpStatus and body from failing REST call to A1 is passed on to
514 * @throws ServiceException
516 void testErrorFromRic() throws ServiceException {
517 putService("service1");
518 addPolicyType("type1", "ric1");
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);
525 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
526 responseBodyBytes, StandardCharsets.UTF_8, null);
527 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
530 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
531 String url = "/policies";
532 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
535 this.addPolicy("instance1", "type1", "service1", "ric1");
536 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
537 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
542 void testPutTypelessPolicy() throws Exception {
543 putService("service1");
544 addPolicyType("", "ric1");
545 String body = putPolicyBody("service1", "ric1", "", "id1");
546 restClient().put("/policies", body).block();
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();
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
561 this.addRic("ricXXX");
562 this.addPolicy("instance1", "type1", "service1", "ric1");
563 this.addPolicy("instance2", "type1", "service1", "ricXXX");
565 // Try change ric1 -> ricXXX
566 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
567 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
571 void testGetPolicy() throws Exception {
572 String url = "/policies/id";
573 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
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());
581 policies.remove(policy);
582 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
587 void testDeletePolicy() throws Exception {
588 String policyId = "id.1";
589 addPolicy(policyId, "typeName", "service1", "ric1");
590 assertThat(policies.size()).isEqualTo(1);
592 String url = "/policies/" + policyId;
593 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
595 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
596 assertThat(policies.size()).isZero();
598 // Delete a non existing policy
599 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
603 void testGetPolicyType() throws Exception {
604 String typeId = "AC.D";
605 addPolicyType(typeId, "ric1");
607 waitForRicState("ric1", RicState.AVAILABLE);
609 String url = "/policy-types/" + typeId;
611 String rsp = this.restClient().get(url).block();
613 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
614 assertThat(info.schema).isNotNull();
616 // Get non existing schema
617 url = "/policy-types/JUNK";
618 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
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);
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");
639 addPolicyType("junk", "ric2");
640 addPolicyType("junk_a.b.c", "ric2");
642 String url = "/policy-types";
643 String rsp = restClient().get(url).block();
644 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
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);
651 // Get policy types for non existing RIC
652 url = "/policy-types?ric_id=ric1XXX";
653 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
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);
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);
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");
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");
672 url = "/policy-types?compatible_with_version=1.5.0";
673 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "type_name");
677 void testGetPolicyInstances() throws Exception {
678 addPolicy("id1", "type1", "service1");
680 String url = "/policy-instances";
681 String rsp = restClient().get(url).block();
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");
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");
699 String url = "/policy-instances?policytype_id=type1";
700 String rsp = restClient().get(url).block();
702 assertThat(rsp).contains("id1") //
704 .doesNotContain("id3");
706 url = "/policy-instances?policytype_id=type1&service_id=service2";
707 rsp = restClient().get(url).block();
709 assertThat(rsp).doesNotContain("id1") //
711 .doesNotContain("id3");
713 url = "/policy-instances?type_name=type1";
714 rsp = restClient().get(url).block();
715 assertThat(rsp).contains("id1") //
717 .doesNotContain("id3") //
720 // Test get policies for non existing type
721 url = "/policy-instances?policytype_id=type1XXX";
722 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
724 // Test get policies for non existing RIC
725 url = "/policy-instances?ric_id=XXX";
726 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
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");
736 String url = "/policies?policytype_id=type1";
737 String rsp = restClient().get(url).block();
739 assertThat(rsp).contains("id1") //
741 .doesNotContain("id3");
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");
748 url = "/policies?policytype_name=type1&service_id=service1";
749 rsp = restClient().get(url).block();
750 assertThat(rsp).contains("id1") //
753 assertThat(gson.fromJson(rsp, PolicyIdList.class).policyIds).hasSize(3);
755 // Test get policy ids for non existing type
756 url = "/policies?policytype_id=type1XXX";
757 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
759 // Test get policy ids for non existing RIC
760 url = "/policies?ric_id=XXX";
761 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
765 void testPutAndGetService() throws Exception {
767 String serviceName = "ac.dc";
768 putService(serviceName, 0, HttpStatus.CREATED);
769 putService(serviceName, 0, HttpStatus.OK);
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);
782 rsp = restClient().get(url).block();
783 assertThat(rsp).as("Response contains service name").contains(serviceName);
787 url = "/services/" + serviceName + "/keepalive";
788 ResponseEntity<?> entity = restClient().putForEntity(url).block();
789 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
792 assertThat(services.size()).isEqualTo(1);
793 url = "/services/" + serviceName;
794 restClient().delete(url).block();
795 assertThat(services.size()).isZero();
797 // Keep alive, no registered service
798 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
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,
805 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
806 HttpStatus.BAD_REQUEST, false);
808 // GET non existing service
809 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
813 void testServiceSupervision() throws Exception {
814 putService("service1", 1, HttpStatus.CREATED);
815 addPolicyType("type1", "ric1");
817 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
818 restClient().put("/policies", policyBody).block();
820 assertThat(policies.size()).isEqualTo(1);
821 assertThat(services.size()).isEqualTo(1);
823 // Timeout after ~1 second
824 await().untilAsserted(() -> assertThat(policies.size()).isZero());
825 assertThat(services.size()).isZero();
829 void testGetPolicyStatus() throws Exception {
830 addPolicy("id", "typeName", "service1", "ric1");
831 assertThat(policies.size()).isEqualTo(1);
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");
838 // GET non existing policy status
839 url = "/policies/XXX/status";
840 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
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("{}");
853 void testGetServiceStatus() throws Exception {
854 String url = "/status";
855 String rsp = restClient().get(url).block();
856 assertThat(rsp).contains("hunky dory");
858 rsp = restClient(baseUrl(), false).get(url).block(); // V1 status is used by a readinessProbe
859 assertThat(rsp).isEqualTo("hunky dory");
863 void testServiceNotification() throws Exception {
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);
870 putService("junkService");
871 Service junkService = this.services.get("junkService");
872 junkService.setCallbackUrl("https://junk");
873 putService("service");
875 Ric ric = addRic("ric1");
876 ric.setState(Ric.RicState.UNAVAILABLE);
877 supervision.checkAllRics();
878 waitForRicState("ric1", RicState.AVAILABLE);
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);
886 var headers = receivedCallbacks.receivedHeaders.get(0);
887 assertThat(headers).containsEntry("authorization", "Bearer " + AUTH_TOKEN);
889 Files.delete(authFile);
892 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
894 Policy policy = Policy.builder() //
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") //
904 policies.put(policy);
908 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
909 return addPolicy(id, typeName, service, "ric");
912 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
913 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
914 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
917 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
918 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
920 String json = gson.toJson(service);
924 private void putService(String name) {
925 putService(name, 0, null);
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(), "");
937 private String jsonString() {
938 return "{\"servingCellNrcgi\":\"1\"}";
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));
949 addPolicyType("type1", "ric");
950 addPolicyType("type2", "ric");
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");
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);
966 for (Thread t : threads) {
969 for (ConcurrencyTestRunnable test : tests) {
970 assertThat(test.isFailed()).isFalse();
972 assertThat(policies.size()).isZero();
973 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
975 assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
976 nonRespondingRic.setState(RicState.AVAILABLE);
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()) //
992 AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
993 return f.createRestClientNoHttpProxy(baseUrl);
997 private String baseUrl() {
998 return "https://localhost:" + port;
1001 private AsyncRestClient restClient(boolean useTrustValidation) {
1002 return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
1005 private AsyncRestClient restClient() {
1006 return restClient(false);
1009 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
1010 testErrorCode(request, expStatus, "", true);
1013 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
1014 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
1017 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
1018 testErrorCode(request, expStatus, responseContains, true);
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)) //
1030 private void waitForRicState(String ricId, RicState state) throws ServiceException {
1031 Ric ric = rics.getRic(ricId);
1032 await().untilAsserted(() -> state.equals(ric.getState()));
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);
1047 private MockA1Client getA1Client(String ricId) throws ServiceException {
1048 return a1ClientFactory.getOrCreateA1Client(ricId);
1051 private PolicyType createPolicyType(String policyTypeName) {
1052 return PolicyType.builder() //
1053 .id(policyTypeName) //
1054 .schema("{\"title\":\"" + policyTypeName + "\"}") //
1058 private PolicyType addPolicyType(String policyTypeName, String ricId) {
1059 PolicyType type = createPolicyType(policyTypeName);
1060 policyTypes.put(type);
1061 addRic(ricId).addSupportedPolicyType(type);
1065 private Ric addRic(String ricId) {
1066 return addRic(ricId, null);
1069 private RicConfig ricConfig(String ricId, String managedElement) {
1070 List<String> mes = new ArrayList<>();
1071 if (managedElement != null) {
1072 mes.add(managedElement);
1074 return RicConfig.builder() //
1077 .managedElementIds(mes) //
1081 private Ric addRic(String ricId, String managedElement) {
1082 if (rics.get(ricId) != null) {
1083 return rics.get(ricId);
1086 RicConfig conf = ricConfig(ricId, managedElement);
1087 Ric ric = new Ric(conf);
1088 ric.setState(Ric.RicState.AVAILABLE);