2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.JsonArray;
30 import com.google.gson.JsonElement;
31 import com.google.gson.JsonParser;
33 import java.time.Duration;
34 import java.time.Instant;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.concurrent.atomic.AtomicInteger;
39 import org.junit.jupiter.api.AfterEach;
40 import org.junit.jupiter.api.BeforeEach;
41 import org.junit.jupiter.api.Test;
42 import org.junit.jupiter.api.extension.ExtendWith;
43 import org.oransc.policyagent.clients.AsyncRestClient;
44 import org.oransc.policyagent.configuration.ApplicationConfig;
45 import org.oransc.policyagent.configuration.ImmutableRicConfig;
46 import org.oransc.policyagent.configuration.RicConfig;
47 import org.oransc.policyagent.controllers.PolicyInfo;
48 import org.oransc.policyagent.controllers.ServiceRegistrationInfo;
49 import org.oransc.policyagent.controllers.ServiceStatus;
50 import org.oransc.policyagent.exceptions.ServiceException;
51 import org.oransc.policyagent.repository.ImmutablePolicy;
52 import org.oransc.policyagent.repository.ImmutablePolicyType;
53 import org.oransc.policyagent.repository.Lock.LockType;
54 import org.oransc.policyagent.repository.Policies;
55 import org.oransc.policyagent.repository.Policy;
56 import org.oransc.policyagent.repository.PolicyType;
57 import org.oransc.policyagent.repository.PolicyTypes;
58 import org.oransc.policyagent.repository.Ric;
59 import org.oransc.policyagent.repository.Ric.RicState;
60 import org.oransc.policyagent.repository.Rics;
61 import org.oransc.policyagent.repository.Services;
62 import org.oransc.policyagent.tasks.RicSupervision;
63 import org.oransc.policyagent.tasks.ServiceSupervision;
64 import org.oransc.policyagent.utils.MockA1Client;
65 import org.oransc.policyagent.utils.MockA1ClientFactory;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.boot.test.context.SpringBootTest;
70 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
71 import org.springframework.boot.test.context.TestConfiguration;
72 import org.springframework.boot.web.server.LocalServerPort;
73 import org.springframework.context.ApplicationContext;
74 import org.springframework.context.annotation.Bean;
75 import org.springframework.http.HttpEntity;
76 import org.springframework.http.HttpHeaders;
77 import org.springframework.http.HttpStatus;
78 import org.springframework.http.MediaType;
79 import org.springframework.http.ResponseEntity;
80 import org.springframework.test.context.junit.jupiter.SpringExtension;
81 import org.springframework.web.client.RestTemplate;
82 import org.springframework.web.reactive.function.client.WebClientResponseException;
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
87 @ExtendWith(SpringExtension.class)
88 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
89 public class ApplicationTest {
90 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
93 ApplicationContext context;
99 private Policies policies;
102 private PolicyTypes policyTypes;
105 MockA1ClientFactory a1ClientFactory;
108 RicSupervision supervision;
113 private static Gson gson = new GsonBuilder() //
117 public static class MockApplicationConfig extends ApplicationConfig {
119 public String getLocalConfigurationFilePath() {
120 return ""; // No config file loaded for the test
125 * Overrides the BeanFactory.
128 static class TestBeanFactory {
129 private final PolicyTypes policyTypes = new PolicyTypes();
130 private final Services services = new Services();
131 private final Policies policies = new Policies();
132 MockA1ClientFactory a1ClientFactory = null;
135 public ApplicationConfig getApplicationConfig() {
136 return new MockApplicationConfig();
140 MockA1ClientFactory getA1ClientFactory() {
141 if (a1ClientFactory == null) {
142 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
144 return this.a1ClientFactory;
148 public PolicyTypes getPolicyTypes() {
149 return this.policyTypes;
153 Policies getPolicies() {
154 return this.policies;
158 Services getServices() {
159 return this.services;
163 public ServiceSupervision getServiceSupervision() {
164 Duration checkInterval = Duration.ofMillis(1);
165 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
173 public void reset() {
181 public void verifyNoRicLocks() {
182 for (Ric ric : this.rics.getRics()) {
183 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
184 ric.getLock().unlockBlocking();
185 assertThat(ric.getLock().getLockCounter()).isEqualTo(0);
186 assertThat(ric.getState()).isEqualTo(Ric.RicState.IDLE);
191 public void testGetRics() throws Exception {
193 this.addPolicyType("type1", "kista_1");
194 String url = "/rics?policyType=type1";
195 String rsp = restClient().get(url).block();
196 assertThat(rsp).contains("kista_1");
198 // Non existing policy type
199 url = "/rics?policyType=XXXX";
200 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
204 public void testRecovery() throws Exception {
205 addRic("ric").setState(Ric.RicState.UNDEFINED);
206 String ricName = "ric";
207 Policy policy2 = addPolicy("policyId2", "typeName", "service", ricName);
209 getA1Client(ricName).putPolicy(policy2); // put it in the RIC
210 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
212 String policyId = "policyId";
213 Policy policy = addPolicy(policyId, "typeName", "service", ricName); // This should be created in the RIC
214 supervision.checkAllRics(); // The created policy should be put in the RIC
215 await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ricName).getState()));
216 await().untilAsserted(() -> RicState.IDLE.equals(rics.getRic(ricName).getState()));
218 Policies ricPolicies = getA1Client(ricName).getPolicies();
219 assertThat(ricPolicies.size()).isEqualTo(1);
220 Policy ricPolicy = ricPolicies.get(policyId);
221 assertThat(ricPolicy.json()).isEqualTo(policy.json());
225 public void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
226 String ricName = "ric1";
227 String managedElementId = "kista_1";
228 addRic(ricName, managedElementId);
230 String url = "/ric?managedElementId=" + managedElementId;
231 String rsp = restClient().get(url).block();
232 assertThat(rsp).isEqualTo(ricName);
234 // test GET RIC for ManagedElement that does not exist
235 url = "/ric?managedElementId=" + "junk";
236 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
239 private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId) {
240 String url = "/policy?type=" + policyTypeName + "&instance=" + policyInstanceId + "&ric=" + ricName
241 + "&service=" + serviceName;
246 public void testPutPolicy() throws Exception {
247 String serviceName = "service1";
248 String ricName = "ric1";
249 String policyTypeName = "type1";
250 String policyInstanceId = "instance1";
252 putService(serviceName);
253 addPolicyType(policyTypeName, ricName);
255 String url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
256 final String policyBody = jsonString();
257 this.rics.getRic(ricName).setState(Ric.RicState.IDLE);
259 restClient().put(url, policyBody).block();
261 Policy policy = policies.getPolicy(policyInstanceId);
262 assertThat(policy).isNotNull();
263 assertThat(policy.id()).isEqualTo(policyInstanceId);
264 assertThat(policy.ownerServiceName()).isEqualTo(serviceName);
265 assertThat(policy.ric().name()).isEqualTo("ric1");
268 String rsp = restClient().get(url).block();
269 assertThat(rsp.contains(policyInstanceId)).isTrue();
271 // Test of error codes
272 url = putPolicyUrl(serviceName, ricName + "XX", policyTypeName, policyInstanceId);
273 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
275 url = putPolicyUrl(serviceName, ricName, policyTypeName + "XX", policyInstanceId);
276 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
278 url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
279 this.rics.getRic(ricName).setState(Ric.RicState.SYNCHRONIZING);
280 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
281 this.rics.getRic(ricName).setState(Ric.RicState.IDLE);
285 public void testRefuseToUpdatePolicy() throws Exception {
286 // Test that only the json can be changed for a already created policy
287 // In this case service is attempted to be changed
289 this.addRic("ricXXX");
290 this.addPolicy("instance1", "type1", "service1", "ric1");
292 // Try change ric1 -> ricXXX
293 String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
294 testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.METHOD_NOT_ALLOWED);
298 public void testGetPolicy() throws Exception {
299 String url = "/policy?instance=id";
300 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
302 String rsp = restClient().get(url).block();
303 assertThat(rsp).isEqualTo(policy.json());
306 policies.remove(policy);
307 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
312 public void testDeletePolicy() throws Exception {
313 addPolicy("id", "typeName", "service1", "ric1");
314 assertThat(policies.size()).isEqualTo(1);
316 String url = "/policy?instance=id";
317 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
319 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
320 assertThat(policies.size()).isEqualTo(0);
322 // Delete a non existing policy
323 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
327 public void testGetPolicySchemas() throws Exception {
328 addPolicyType("type1", "ric1");
329 addPolicyType("type2", "ric2");
331 String url = "/policy_schemas";
332 String rsp = this.restClient().get(url).block();
333 assertThat(rsp).contains("type1");
334 assertThat(rsp).contains("[{\"title\":\"type2\"}");
336 List<String> info = parseSchemas(rsp);
337 assertThat(info.size()).isEqualTo(2);
339 url = "/policy_schemas?ric=ric1";
340 rsp = restClient().get(url).block();
341 assertThat(rsp).contains("type1");
342 info = parseSchemas(rsp);
343 assertThat(info.size()).isEqualTo(1);
345 // Get schema for non existing RIC
346 url = "/policy_schemas?ric=ric1XXX";
347 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
351 public void testGetPolicySchema() throws Exception {
352 addPolicyType("type1", "ric1");
353 addPolicyType("type2", "ric2");
355 String url = "/policy_schema?id=type1";
356 String rsp = restClient().get(url).block();
358 assertThat(rsp).contains("type1");
359 assertThat(rsp).contains("title");
361 // Get non existing schema
362 url = "/policy_schema?id=type1XX";
363 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
367 public void testGetPolicyTypes() throws Exception {
368 addPolicyType("type1", "ric1");
369 addPolicyType("type2", "ric2");
371 String url = "/policy_types";
372 String rsp = restClient().get(url).block();
373 assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
375 url = "/policy_types?ric=ric1";
376 rsp = restClient().get(url).block();
377 assertThat(rsp).isEqualTo("[\"type1\"]");
379 // Get policy types for non existing RIC
380 url = "/policy_types?ric=ric1XXX";
381 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
385 public void testGetPolicies() throws Exception {
387 addPolicy("id1", "type1", "service1");
389 String url = "/policies";
390 String rsp = restClient().get(url).block();
392 List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
393 assertThat(info).size().isEqualTo(1);
394 PolicyInfo policyInfo = info.get(0);
395 assert (policyInfo.validate());
396 assertThat(policyInfo.id).isEqualTo("id1");
397 assertThat(policyInfo.type).isEqualTo("type1");
398 assertThat(policyInfo.service).isEqualTo("service1");
402 public void testGetPoliciesFilter() throws Exception {
403 addPolicy("id1", "type1", "service1");
404 addPolicy("id2", "type1", "service2");
405 addPolicy("id3", "type2", "service1");
407 String url = "/policies?type=type1";
408 String rsp = restClient().get(url).block();
410 assertThat(rsp).contains("id1");
411 assertThat(rsp).contains("id2");
412 assertThat(rsp.contains("id3")).isFalse();
414 url = "/policies?type=type1&service=service2";
415 rsp = restClient().get(url).block();
417 assertThat(rsp.contains("id1")).isFalse();
418 assertThat(rsp).contains("id2");
419 assertThat(rsp.contains("id3")).isFalse();
421 // Test get policies for non existing type
422 url = "/policies?type=type1XXX";
423 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
425 // Test get policies for non existing RIC
426 url = "/policies?ric=XXX";
427 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
431 public void testPutAndGetService() throws Exception {
433 putService("name", 0);
436 String url = "/services?name=name";
437 String rsp = restClient().get(url).block();
438 List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
439 assertThat(info.size()).isEqualTo(1);
440 ServiceStatus status = info.iterator().next();
441 assertThat(status.keepAliveIntervalSeconds).isEqualTo(0);
442 assertThat(status.serviceName).isEqualTo("name");
446 rsp = restClient().get(url).block();
447 assertThat(rsp.contains("name")).isTrue();
451 url = "/services/keepalive?name=name";
452 ResponseEntity<String> entity = restClient().postForEntity(url, null).block();
453 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
456 assertThat(services.size()).isEqualTo(1);
457 url = "/services?name=name";
458 restClient().delete(url).block();
459 assertThat(services.size()).isEqualTo(0);
461 // Keep alive, no registerred service
462 testErrorCode(restClient().post("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
464 // PUT servive with crap payload
465 testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
466 testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
468 // GET non existing servive
469 testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
473 public void testServiceSupervision() throws Exception {
474 putService("service1", 1);
475 addPolicyType("type1", "ric1");
477 String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
478 final String policyBody = jsonString();
479 restClient().put(url, policyBody).block();
481 assertThat(policies.size()).isEqualTo(1);
482 assertThat(services.size()).isEqualTo(1);
484 // Timeout after ~1 second
485 await().untilAsserted(() -> assertThat(policies.size()).isEqualTo(0));
486 assertThat(services.size()).isEqualTo(0);
490 public void testGetPolicyStatus() throws Exception {
491 addPolicy("id", "typeName", "service1", "ric1");
492 assertThat(policies.size()).isEqualTo(1);
494 String url = "/policy_status?instance=id";
495 String rsp = restClient().get(url).block();
496 assertThat(rsp.equals("OK")).isTrue();
498 // GET non existing policy status
499 url = "/policy_status?instance=XXX";
500 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
503 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
505 Policy p = ImmutablePolicy.builder().id(id) //
506 .json(jsonString()) //
507 .ownerServiceName(service) //
508 .ric(rics.getRic(ric)) //
509 .type(addPolicyType(typeName, ric)) //
510 .lastModified("lastModified").build();
515 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
516 return addPolicy(id, typeName, service, "ric");
519 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
520 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, "callbackUrl");
522 String json = gson.toJson(service);
526 private void putService(String name) {
530 private void putService(String name, long keepAliveIntervalSeconds) {
531 String url = "/service";
532 String body = createServiceJson(name, keepAliveIntervalSeconds);
533 restClient().put(url, body).block();
536 private String baseUrl() {
537 return "http://localhost:" + port;
540 private String jsonString() {
541 return "{\n \"servingCellNrcgi\": \"1\"\n }";
544 private static class ConcurrencyTestRunnable implements Runnable {
545 private final RestTemplate restTemplate = new RestTemplate();
546 private final String baseUrl;
547 static AtomicInteger nextCount = new AtomicInteger(0);
548 private final int count;
549 private final RicSupervision supervision;
551 ConcurrencyTestRunnable(String baseUrl, RicSupervision supervision) {
552 this.baseUrl = baseUrl;
553 this.count = nextCount.incrementAndGet();
554 this.supervision = supervision;
559 for (int i = 0; i < 100; ++i) {
561 this.supervision.checkAllRics();
563 String name = "policy:" + count + ":" + i;
569 private void putPolicy(String name) {
570 String putUrl = baseUrl + "/policy?type=type1&instance=" + name + "&ric=ric1&service=service1";
571 restTemplate.put(putUrl, createJsonHttpEntity("{}"));
574 private void deletePolicy(String name) {
575 String deleteUrl = baseUrl + "/policy?instance=" + name;
576 restTemplate.delete(deleteUrl);
581 public void testConcurrency() throws Exception {
582 final Instant startTime = Instant.now();
583 List<Thread> threads = new ArrayList<>();
585 addPolicyType("type1", "ric1");
587 for (int i = 0; i < 100; ++i) {
588 Thread t = new Thread(new ConcurrencyTestRunnable(baseUrl(), this.supervision), "TestThread_" + i);
592 for (Thread t : threads) {
595 assertThat(policies.size()).isEqualTo(0);
596 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
599 private AsyncRestClient restClient() {
600 return new AsyncRestClient(baseUrl());
603 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
604 StepVerifier.create(request) //
605 .expectSubscription() //
606 .expectErrorMatches(t -> checkWebClientError(t, expStatus)) //
610 private boolean checkWebClientError(Throwable t, HttpStatus expStatus) {
611 assertTrue(t instanceof WebClientResponseException);
612 WebClientResponseException e = (WebClientResponseException) t;
613 assertThat(e.getStatusCode()).isEqualTo(expStatus);
617 private MockA1Client getA1Client(String ricName) throws ServiceException {
618 return a1ClientFactory.getOrCreateA1Client(ricName);
621 private PolicyType addPolicyType(String policyTypeName, String ricName) {
622 PolicyType type = ImmutablePolicyType.builder() //
623 .name(policyTypeName) //
624 .schema("{\"title\":\"" + policyTypeName + "\"}") //
627 policyTypes.put(type);
628 addRic(ricName).addSupportedPolicyType(type);
632 private Ric addRic(String ricName) {
633 return addRic(ricName, null);
636 private Ric addRic(String ricName, String managedElement) {
637 if (rics.get(ricName) != null) {
638 return rics.get(ricName);
640 List<String> mes = new ArrayList<>();
641 if (managedElement != null) {
642 mes.add(managedElement);
644 RicConfig conf = ImmutableRicConfig.builder() //
647 .managedElementIds(mes) //
649 Ric ric = new Ric(conf);
650 ric.setState(Ric.RicState.IDLE);
655 private static HttpEntity<String> createJsonHttpEntity(String content) {
656 HttpHeaders headers = new HttpHeaders();
657 headers.setContentType(MediaType.APPLICATION_JSON);
658 return new HttpEntity<String>(content, headers);
661 private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
662 List<T> result = new ArrayList<>();
663 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
664 for (JsonElement jsonElement : jsonArr) {
665 T o = gson.fromJson(jsonElement.toString(), clazz);
671 private static List<String> parseSchemas(String jsonString) {
672 JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
673 List<String> result = new ArrayList<>();
674 for (JsonElement schemaObject : arrayOfSchema) {
675 result.add(schemaObject.toString());