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.AfterEach;
48 import org.junit.jupiter.api.Test;
49 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
50 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
51 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
52 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
53 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
54 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
55 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
56 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
57 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbackInfo;
58 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
67 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
68 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
69 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
70 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
71 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
72 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
73 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
74 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.boot.test.context.SpringBootTest;
79 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
80 import org.springframework.boot.test.context.TestConfiguration;
81 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
82 import org.springframework.boot.web.server.LocalServerPort;
83 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
84 import org.springframework.context.ApplicationContext;
85 import org.springframework.context.annotation.Bean;
86 import org.springframework.http.HttpStatus;
87 import org.springframework.http.MediaType;
88 import org.springframework.http.ResponseEntity;
89 import org.springframework.test.context.TestPropertySource;
90 import org.springframework.web.reactive.function.client.WebClientResponseException;
92 import reactor.core.publisher.Mono;
93 import reactor.test.StepVerifier;
94 import reactor.util.annotation.Nullable;
96 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
97 @TestPropertySource(properties = { //
98 "server.ssl.key-store=./src/test/resources/keystore.jks", //
99 "app.webclient.trust-store=./src/test/resources/truststore.jks", //
100 "app.webclient.trust-store-used=true", //
101 "app.vardata-directory=./target/testdata", //
104 class ApplicationTest {
105 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
108 ApplicationContext context;
114 private Policies policies;
117 private PolicyTypes policyTypes;
120 MockA1ClientFactory a1ClientFactory;
123 RicSupervision supervision;
126 ApplicationConfig applicationConfig;
132 RappSimulatorController rAppSimulator;
135 RefreshConfigTask refreshConfigTask;
138 SecurityContext securityContext;
140 private static Gson gson = new GsonBuilder().create();
143 * Overrides the BeanFactory.
146 static class TestBeanFactory {
149 A1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
150 return new MockA1ClientFactory(appConfig, types);
154 public ServiceSupervision getServiceSupervision(@Autowired Services services,
155 @Autowired A1ClientFactory a1ClientFactory, @Autowired Policies policies) {
156 Duration checkInterval = Duration.ofMillis(1);
157 return new ServiceSupervision(services, policies, a1ClientFactory, checkInterval);
161 public ServletWebServerFactory servletContainer() {
162 return new TomcatServletWebServerFactory();
175 a1ClientFactory.reset();
176 this.rAppSimulator.getTestResults().clear();
177 this.a1ClientFactory.setPolicyTypes(policyTypes); // Default same types in RIC and in this app
178 this.securityContext.setAuthTokenFilePath(null);
182 void verifyNoRicLocks() {
183 for (Ric ric : this.rics.getRics()) {
184 Lock.Grant grant = ric.getLock().lockBlocking(LockType.EXCLUSIVE, "");
185 grant.unlockBlocking();
186 assertThat(ric.getLock().getLockCounter()).isZero();
187 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
192 void generateApiDoc() throws IOException {
193 String url = "https://localhost:" + this.port + "/v3/api-docs";
194 ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
195 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
196 JSONObject jsonObj = new JSONObject(resp.getBody());
197 assertThat(jsonObj.remove("servers")).isNotNull();
199 String indented = (jsonObj).toString(4);
200 String docDir = "api/";
201 Files.createDirectories(Paths.get(docDir));
202 try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "pms-api.json"))) {
208 void testPersistencyPolicies() throws ServiceException {
209 Ric ric = this.addRic("ric1");
210 PolicyType type = this.addPolicyType("type1", ric.id());
212 final int noOfPolicies = 100;
213 for (int i = 0; i < noOfPolicies; ++i) {
214 addPolicy("id" + i, type.getId(), "service", ric.id());
218 Policies policies = new Policies(this.applicationConfig);
219 policies.restoreFromDatabase(ric, this.policyTypes);
220 assertThat(policies.size()).isEqualTo(noOfPolicies);
224 restClient().delete("/policies/id2").block();
225 Policies policies = new Policies(this.applicationConfig);
226 policies.restoreFromDatabase(ric, this.policyTypes);
227 assertThat(policies.size()).isEqualTo(noOfPolicies - 1);
232 void testPersistencyPolicyTypes() throws ServiceException {
233 Ric ric = this.addRic("ric1");
234 this.addPolicyType("type1", ric.id());
235 PolicyTypes types = new PolicyTypes(this.applicationConfig);
236 assertThat(types.size()).isEqualTo(1);
240 void testPersistencyService() throws ServiceException {
241 final String SERVICE = "serviceName";
242 putService(SERVICE, 1234, HttpStatus.CREATED);
243 assertThat(this.services.size()).isEqualTo(1);
244 Service service = this.services.getService(SERVICE);
246 Services servicesRestored = new Services(this.applicationConfig);
247 Service serviceRestored = servicesRestored.getService(SERVICE);
248 assertThat(servicesRestored.size()).isEqualTo(1);
249 assertThat(serviceRestored.getCallbackUrl()).isEqualTo(service.getCallbackUrl());
250 assertThat(serviceRestored.getKeepAliveInterval()).isEqualTo(service.getKeepAliveInterval());
252 // check that the service can be deleted
253 this.services.remove(SERVICE);
254 servicesRestored = new Services(this.applicationConfig);
255 assertThat(servicesRestored.size()).isZero();
259 void testAddingRicFromConfiguration() throws Exception {
260 // Test adding the RIC from configuration
262 final String RIC = "ric1";
263 final String TYPE = "type123";
264 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
265 nearRtRicPolicyTypes.put(createPolicyType(TYPE));
266 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
268 putService("service");
270 refreshConfigTask.handleUpdatedRicConfig( //
271 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
273 waitForRicState(RIC, RicState.AVAILABLE);
275 // Test that the type has been synched
276 Ric addedRic = this.rics.getRic(RIC);
277 assertThat(addedRic.getSupportedPolicyTypes()).hasSize(1);
278 assertThat(addedRic.getSupportedPolicyTypes().iterator().next().getId()).isEqualTo(TYPE);
280 // Check that a service callback for the AVAILABLE RIC is invoked
281 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
282 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
283 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
284 assertThat(callbackInfo.ricId).isEqualTo(RIC);
285 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
289 void testAddingRicFromConfiguration_nonRespondingRic() throws Exception {
290 putService("service");
292 final String RIC = "NonRespondingRic";
293 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(RIC);
294 doReturn(MockA1Client.monoError("error", HttpStatus.BAD_GATEWAY)).when(a1Client).getPolicyTypeIdentities();
296 refreshConfigTask.handleUpdatedRicConfig( //
297 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
300 waitForRicState(RIC, RicState.UNAVAILABLE);
302 // Check that no service callback for the UNAVAILABLE RIC is invoked
303 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
304 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).isEmpty());
306 // Run a synch and check that the AVAILABLE notification is received
307 a1ClientFactory.reset();
308 supervision.checkAllRics();
309 waitForRicState(RIC, RicState.AVAILABLE);
311 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
315 void testTrustValidation() {
317 String rsp = restClient(true).get("/rics").block(); // restClient(true) enables trust validation
318 assertThat(rsp).contains("ric1");
322 void testGetRics() throws Exception {
324 this.addPolicyType("type1", "ric1");
325 String url = "/rics?policytype_id=type1";
326 String rsp = restClient().get(url).block();
327 assertThat(rsp).contains("ric1");
329 // nameless type for ORAN A1 1.1
331 this.addPolicyType("", "ric2");
332 url = "/rics?policytype_id=";
333 rsp = restClient().get(url).block();
334 assertThat(rsp).contains("ric2") //
335 .doesNotContain("ric1") //
336 .contains("AVAILABLE");
339 rsp = restClient().get("/rics").block();
340 assertThat(rsp).contains("ric2") //
343 // Non existing policy type
344 url = "/rics?policytype_id=XXXX";
345 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
349 void testSynchronization() throws Exception {
350 // Two polictypes will be put in the NearRT RICs
351 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
352 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
353 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
354 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
356 // One type and one instance added to the Policy Management Service's storage
357 final String ric1Name = "ric1";
358 Ric ric1 = addRic(ric1Name);
359 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
360 Ric ric2 = addRic("ric2");
362 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
363 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
365 String policyId = "policyId";
366 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
367 supervision.checkAllRics(); // The created policy should be put in the RIC
369 // Wait until synch is completed
370 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
371 waitForRicState(ric1Name, RicState.AVAILABLE);
372 waitForRicState("ric2", RicState.AVAILABLE);
374 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
375 assertThat(ricPolicies.size()).isEqualTo(1);
376 Policy ricPolicy = ricPolicies.get(policyId);
377 assertThat(ricPolicy.getJson()).isEqualTo(policy.getJson());
379 // Both types should be in the Policy Management Service's storage after the
381 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
382 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
386 void testGetRic() throws Exception {
387 String ricId = "ric1";
388 String managedElementId = "kista_1";
389 addRic(ricId, managedElementId);
391 String url = "/rics/ric?managed_element_id=" + managedElementId;
392 String rsp = restClient().get(url).block();
393 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
394 assertThat(ricInfo.ricId).isEqualTo(ricId);
396 url = "/rics/ric?ric_id=" + ricId;
397 rsp = restClient().get(url).block();
398 ricInfo = gson.fromJson(rsp, RicInfo.class);
399 assertThat(ricInfo.ricId).isEqualTo(ricId);
401 // test GET RIC for ManagedElement that does not exist
402 url = "/rics/ric?managed_element_id=" + "junk";
403 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
406 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
409 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
410 boolean isTransient) {
411 PolicyInfo info = new PolicyInfo();
412 info.policyId = policyInstanceId;
413 info.policyTypeId = policyTypeName;
415 info.serviceId = serviceName;
416 info.policyData = gson.fromJson(jsonString(), Object.class);
419 info.isTransient = isTransient;
421 info.statusNotificationUri = "statusNotificationUri";
422 return gson.toJson(info);
425 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
426 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false);
430 void testPutPolicy() throws Exception {
431 String serviceName = "service.1";
432 String ricId = "ric.1";
433 String policyTypeName = "type1_1.2.3";
434 String policyInstanceId = "instance_1.2.3";
436 putService(serviceName);
437 addPolicyType(policyTypeName, ricId);
439 // PUT a transient policy
440 String url = "/policies";
441 String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true);
442 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
444 restClient().put(url, policyBody).block();
446 Policy policy = policies.getPolicy(policyInstanceId);
447 assertThat(policy).isNotNull();
448 assertThat(policy.getId()).isEqualTo(policyInstanceId);
449 assertThat(policy.getOwnerServiceId()).isEqualTo(serviceName);
450 assertThat(policy.getRic().id()).isEqualTo(ricId);
451 assertThat(policy.isTransient()).isTrue();
453 // Put a non transient policy
454 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
455 restClient().put(url, policyBody).block();
456 policy = policies.getPolicy(policyInstanceId);
457 assertThat(policy.isTransient()).isFalse();
459 url = "/policy-instances";
460 String rsp = restClient().get(url).block();
461 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
463 url = "/policies/" + policyInstanceId;
464 rsp = restClient().get(url).block();
465 assertThat(rsp).contains(policyBody);
467 // Test of error codes
469 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
470 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
472 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
473 addPolicyType(policyTypeName + "XX", "otherRic");
474 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
476 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
477 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
478 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
479 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
484 * Test that HttpStatus and body from failing REST call to A1 is passed on to
487 * @throws ServiceException
489 void testErrorFromRic() throws ServiceException {
490 putService("service1");
491 addPolicyType("type1", "ric1");
493 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
494 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
495 String responseBody = "Refused";
496 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
498 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
499 responseBodyBytes, StandardCharsets.UTF_8, null);
500 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
503 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
504 String url = "/policies";
505 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
508 this.addPolicy("instance1", "type1", "service1", "ric1");
509 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
510 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
515 void testPutTypelessPolicy() throws Exception {
516 putService("service1");
517 addPolicyType("", "ric1");
518 String body = putPolicyBody("service1", "ric1", "", "id1");
519 restClient().put("/policies", body).block();
521 String rsp = restClient().get("/policy-instances").block();
522 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
523 assertThat(info.policies).hasSize(1);
524 PolicyInfo policyInfo = info.policies.iterator().next();
525 assertThat(policyInfo.policyId).isEqualTo("id1");
526 assertThat(policyInfo.policyTypeId).isEmpty();
530 void testRefuseToUpdatePolicy() throws Exception {
531 // Test that only the json can be changed for a already created policy
532 // In this case service is attempted to be changed
534 this.addRic("ricXXX");
535 this.addPolicy("instance1", "type1", "service1", "ric1");
536 this.addPolicy("instance2", "type1", "service1", "ricXXX");
538 // Try change ric1 -> ricXXX
539 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
540 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
544 void testGetPolicy() throws Exception {
545 String url = "/policies/id";
546 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
548 String rsp = restClient().get(url).block();
549 PolicyInfo info = gson.fromJson(rsp, PolicyInfo.class);
550 String policyStr = gson.toJson(info.policyData);
551 assertThat(policyStr).isEqualTo(policy.getJson());
554 policies.remove(policy);
555 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
560 void testDeletePolicy() throws Exception {
561 String policyId = "id.1";
562 addPolicy(policyId, "typeName", "service1", "ric1");
563 assertThat(policies.size()).isEqualTo(1);
565 String url = "/policies/" + policyId;
566 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
568 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
569 assertThat(policies.size()).isZero();
571 // Delete a non existing policy
572 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
576 void testGetPolicyType() throws Exception {
577 String typeId = "AC.D";
578 addPolicyType(typeId, "ric1");
580 waitForRicState("ric1", RicState.AVAILABLE);
582 String url = "/policy-types/" + typeId;
584 String rsp = this.restClient().get(url).block();
586 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
587 assertThat(info.schema).isNotNull();
589 // Get non existing schema
590 url = "/policy-types/JUNK";
591 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
594 String createPolicyTypesJson(String... types) {
595 List<String> list = new ArrayList<>();
596 Collections.addAll(list, types);
597 PolicyTypeIdList ids = new PolicyTypeIdList(list);
598 return gson.toJson(ids);
602 void testGetPolicyTypes() throws Exception {
603 String TYPE_ID_1 = "A_type1_1.9.0";
604 String TYPE_ID_2 = "A_type1_2.0.0";
605 String TYPE_ID_3 = "A_type1_1.5.0";
606 String TYPE_ID_4 = "type3_1.9.0";
607 addPolicyType(TYPE_ID_1, "ric1");
608 addPolicyType(TYPE_ID_2, "ric2");
609 addPolicyType(TYPE_ID_3, "ric2");
610 addPolicyType(TYPE_ID_4, "ric2");
612 addPolicyType("junk", "ric2");
613 addPolicyType("junk_a.b.c", "ric2");
615 String url = "/policy-types";
616 String rsp = restClient().get(url).block();
617 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
619 url = "/policy-types?ric_id=ric1";
620 rsp = restClient().get(url).block();
621 String expResp = createPolicyTypesJson(TYPE_ID_1);
622 assertThat(rsp).isEqualTo(expResp);
624 // Get policy types for non existing RIC
625 url = "/policy-types?ric_id=ric1XXX";
626 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
628 // All types with a type_name
629 url = "/policy-types?type_name=A_type1";
630 rsp = restClient().get(url).block();
631 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
633 // All types compatible with type1_1.5.0 (which is type1_1.9.0)
634 url = "/policy-types?type_name=A_type1&&compatible_with_version=1.5.0";
635 rsp = restClient().get(url).block();
636 expResp = createPolicyTypesJson(TYPE_ID_3, TYPE_ID_1);
637 assertThat(rsp).isEqualTo(expResp);
639 url = "/policy-types?type_name=A_type1&&compatible_with_version=junk";
640 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Version must contain major.minor.patch code");
642 url = "/policy-types?type_name=A_type1&&compatible_with_version=a.b.c";
643 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Syntax error in");
645 url = "/policy-types?compatible_with_version=1.5.0";
646 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "type_name");
650 void testGetPolicyInstances() throws Exception {
651 addPolicy("id1", "type1", "service1");
653 String url = "/policy-instances";
654 String rsp = restClient().get(url).block();
656 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
657 assertThat(info.policies).hasSize(1);
658 PolicyInfo policyInfo = info.policies.iterator().next();
659 assert (policyInfo.validate());
660 assertThat(policyInfo.policyId).isEqualTo("id1");
661 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
662 assertThat(policyInfo.serviceId).isEqualTo("service1");
666 void testGetPolicyInstancesFilter() throws Exception {
667 addPolicy("id1", "type1", "service1");
668 addPolicy("id2", "type1", "service2");
669 addPolicy("id3", "type2", "service1");
670 addPolicy("id4", "type1_1.0.0", "service1");
672 String url = "/policy-instances?policytype_id=type1";
673 String rsp = restClient().get(url).block();
675 assertThat(rsp).contains("id1") //
677 .doesNotContain("id3");
679 url = "/policy-instances?policytype_id=type1&service_id=service2";
680 rsp = restClient().get(url).block();
682 assertThat(rsp).doesNotContain("id1") //
684 .doesNotContain("id3");
686 url = "/policy-instances?type_name=type1";
687 rsp = restClient().get(url).block();
688 assertThat(rsp).contains("id1") //
690 .doesNotContain("id3") //
693 // Test get policies for non existing type
694 url = "/policy-instances?policytype_id=type1XXX";
695 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
697 // Test get policies for non existing RIC
698 url = "/policy-instances?ric_id=XXX";
699 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
703 void testGetPolicyIdsFilter() throws Exception {
704 addPolicy("id1", "type1", "service1", "ric1");
705 addPolicy("id2", "type1", "service2", "ric1");
706 addPolicy("id3", "type2", "service1", "ric1");
707 addPolicy("id4", "type1_1.0.0", "service1");
709 String url = "/policies?policytype_id=type1";
710 String rsp = restClient().get(url).block();
712 assertThat(rsp).contains("id1") //
714 .doesNotContain("id3");
716 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
717 rsp = restClient().get(url).block();
718 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
719 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
721 url = "/policies?policytype_name=type1&service_id=service1";
722 rsp = restClient().get(url).block();
723 assertThat(rsp).contains("id1") //
726 assertThat(gson.fromJson(rsp, PolicyIdList.class).policyIds).hasSize(3);
728 // Test get policy ids for non existing type
729 url = "/policies?policytype_id=type1XXX";
730 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
732 // Test get policy ids for non existing RIC
733 url = "/policies?ric_id=XXX";
734 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
738 void testPutAndGetService() throws Exception {
740 String serviceName = "ac.dc";
741 putService(serviceName, 0, HttpStatus.CREATED);
742 putService(serviceName, 0, HttpStatus.OK);
745 String url = "/services?service_id=" + serviceName;
746 String rsp = restClient().get(url).block();
747 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
748 assertThat(info.statusList).hasSize(1);
749 ServiceStatus status = info.statusList.iterator().next();
750 assertThat(status.keepAliveIntervalSeconds).isZero();
751 assertThat(status.serviceId).isEqualTo(serviceName);
755 rsp = restClient().get(url).block();
756 assertThat(rsp).as("Response contains service name").contains(serviceName);
760 url = "/services/" + serviceName + "/keepalive";
761 ResponseEntity<?> entity = restClient().putForEntity(url).block();
762 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
765 assertThat(services.size()).isEqualTo(1);
766 url = "/services/" + serviceName;
767 restClient().delete(url).block();
768 assertThat(services.size()).isZero();
770 // Keep alive, no registered service
771 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
773 // PUT service with bad payload
774 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
775 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
776 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
778 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
779 HttpStatus.BAD_REQUEST, false);
781 // GET non existing service
782 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
786 void testServiceSupervision() throws Exception {
787 putService("service1", 1, HttpStatus.CREATED);
788 addPolicyType("type1", "ric1");
790 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
791 restClient().put("/policies", policyBody).block();
793 assertThat(policies.size()).isEqualTo(1);
794 assertThat(services.size()).isEqualTo(1);
796 // Timeout after ~1 second
797 await().untilAsserted(() -> assertThat(policies.size()).isZero());
798 assertThat(services.size()).isZero();
802 void testGetPolicyStatus() throws Exception {
803 addPolicy("id", "typeName", "service1", "ric1");
804 assertThat(policies.size()).isEqualTo(1);
806 String url = "/policies/id/status";
807 String rsp = restClient().get(url).block();
808 PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
809 assertThat(info.status).isEqualTo("OK");
811 // GET non existing policy status
812 url = "/policies/XXX/status";
813 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
815 // GET STATUS, the NearRT RIC returns error
816 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
817 url = "/policies/id/status";
818 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
819 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
820 rsp = restClient().get(url).block();
821 info = gson.fromJson(rsp, PolicyStatusInfo.class);
822 assertThat(info.status).hasToString("{}");
826 void testGetServiceStatus() throws Exception {
827 String url = "/status";
828 String rsp = restClient().get(url).block();
829 assertThat(rsp).contains("hunky dory");
831 rsp = restClient(baseUrl(), false).get(url).block(); // V1 status is used by a readinessProbe
832 assertThat(rsp).isEqualTo("hunky dory");
836 void testServiceNotification() throws Exception {
838 final String AUTH_TOKEN = "testToken";
839 Path authFile = Files.createTempFile("pmsTestAuthToken", ".txt");
840 Files.write(authFile, AUTH_TOKEN.getBytes());
841 this.securityContext.setAuthTokenFilePath(authFile);
843 putService("junkService");
844 Service junkService = this.services.get("junkService");
845 junkService.setCallbackUrl("https://junk");
846 putService("service");
848 Ric ric = addRic("ric1");
849 ric.setState(Ric.RicState.UNAVAILABLE);
850 supervision.checkAllRics();
851 waitForRicState("ric1", RicState.AVAILABLE);
853 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
854 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
855 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
856 assertThat(callbackInfo.ricId).isEqualTo("ric1");
857 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
859 var headers = receivedCallbacks.receivedHeaders.get(0);
860 assertThat(headers).containsEntry("authorization", "Bearer " + AUTH_TOKEN);
862 Files.delete(authFile);
865 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
867 Policy policy = Policy.builder() //
869 .json(jsonString()) //
870 .ownerServiceId(service) //
871 .ric(rics.getRic(ric)) //
872 .type(addPolicyType(typeName, ric)) //
873 .lastModified(Instant.now()) //
874 .isTransient(false) //
875 .statusNotificationUri("/policy-status?id=XXX") //
877 policies.put(policy);
881 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
882 return addPolicy(id, typeName, service, "ric");
885 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
886 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
887 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
890 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
891 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
893 String json = gson.toJson(service);
897 private void putService(String name) {
898 putService(name, 0, null);
901 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
902 String url = "/services";
903 String body = createServiceJson(name, keepAliveIntervalSeconds);
904 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
905 if (expectedStatus != null) {
906 assertEquals(expectedStatus, resp.getStatusCode(), "");
910 private String jsonString() {
911 return "{\"servingCellNrcgi\":\"1\"}";
915 void testConcurrency() throws Exception {
916 logger.info("Concurrency test starting");
917 final Instant startTime = Instant.now();
918 List<Thread> threads = new ArrayList<>();
919 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
920 a1ClientFactory.setResponseDelay(Duration.ofMillis(2));
922 addPolicyType("type1", "ric");
923 addPolicyType("type2", "ric");
925 final String NON_RESPONDING_RIC = "NonRespondingRic";
926 Ric nonRespondingRic = addRic(NON_RESPONDING_RIC);
927 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(NON_RESPONDING_RIC);
928 a1Client.setErrorInject("errorInject");
930 for (int i = 0; i < 10; ++i) {
931 AsyncRestClient restClient = restClient();
932 ConcurrencyTestRunnable test =
933 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
934 Thread thread = new Thread(test, "TestThread_" + i);
939 for (Thread t : threads) {
942 for (ConcurrencyTestRunnable test : tests) {
943 assertThat(test.isFailed()).isFalse();
945 assertThat(policies.size()).isZero();
946 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
948 assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
949 nonRespondingRic.setState(RicState.AVAILABLE);
952 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
953 WebClientConfig config = this.applicationConfig.getWebClientConfig();
954 config = WebClientConfig.builder() //
955 .keyStoreType(config.getKeyStoreType()) //
956 .keyStorePassword(config.getKeyStorePassword()) //
957 .keyStore(config.getKeyStore()) //
958 .keyPassword(config.getKeyPassword()) //
959 .isTrustStoreUsed(useTrustValidation) //
960 .trustStore(config.getTrustStore()) //
961 .trustStorePassword(config.getTrustStorePassword()) //
962 .httpProxyConfig(config.getHttpProxyConfig()) //
965 AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
966 return f.createRestClientNoHttpProxy(baseUrl);
970 private String baseUrl() {
971 return "https://localhost:" + port;
974 private AsyncRestClient restClient(boolean useTrustValidation) {
975 return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
978 private AsyncRestClient restClient() {
979 return restClient(false);
982 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
983 testErrorCode(request, expStatus, "", true);
986 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
987 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
990 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
991 testErrorCode(request, expStatus, responseContains, true);
994 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
995 boolean expectApplicationProblemJsonMediaType) {
996 StepVerifier.create(request) //
997 .expectSubscription() //
999 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
1003 private void waitForRicState(String ricId, RicState state) throws ServiceException {
1004 Ric ric = rics.getRic(ricId);
1005 await().untilAsserted(() -> state.equals(ric.getState()));
1008 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
1009 boolean expectApplicationProblemJsonMediaType) {
1010 assertTrue(throwable instanceof WebClientResponseException);
1011 WebClientResponseException responseException = (WebClientResponseException) throwable;
1012 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
1013 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
1014 if (expectApplicationProblemJsonMediaType) {
1015 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
1020 private MockA1Client getA1Client(String ricId) throws ServiceException {
1021 return a1ClientFactory.getOrCreateA1Client(ricId);
1024 private PolicyType createPolicyType(String policyTypeName) {
1025 return PolicyType.builder() //
1026 .id(policyTypeName) //
1027 .schema("{\"title\":\"" + policyTypeName + "\"}") //
1031 private PolicyType addPolicyType(String policyTypeName, String ricId) {
1032 PolicyType type = createPolicyType(policyTypeName);
1033 policyTypes.put(type);
1034 addRic(ricId).addSupportedPolicyType(type);
1038 private Ric addRic(String ricId) {
1039 return addRic(ricId, null);
1042 private RicConfig ricConfig(String ricId, String managedElement) {
1043 List<String> mes = new ArrayList<>();
1044 if (managedElement != null) {
1045 mes.add(managedElement);
1047 return RicConfig.builder() //
1050 .managedElementIds(mes) //
1054 private Ric addRic(String ricId, String managedElement) {
1055 if (rics.get(ricId) != null) {
1056 return rics.get(ricId);
1059 RicConfig conf = ricConfig(ricId, managedElement);
1060 Ric ric = new Ric(conf);
1061 ric.setState(Ric.RicState.AVAILABLE);