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;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonArray;
29 import com.google.gson.JsonElement;
30 import com.google.gson.JsonParser;
32 import java.io.IOException;
33 import java.time.Duration;
34 import java.time.Instant;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Vector;
38 import java.util.concurrent.atomic.AtomicInteger;
40 import org.junit.jupiter.api.AfterEach;
41 import org.junit.jupiter.api.BeforeEach;
42 import org.junit.jupiter.api.Test;
43 import org.junit.jupiter.api.extension.ExtendWith;
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.RepositorySupervision;
63 import org.oransc.policyagent.utils.MockA1Client;
64 import org.oransc.policyagent.utils.MockA1ClientFactory;
65 import org.springframework.beans.factory.annotation.Autowired;
66 import org.springframework.boot.test.context.SpringBootTest;
67 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
68 import org.springframework.boot.test.context.TestConfiguration;
69 import org.springframework.boot.web.server.LocalServerPort;
70 import org.springframework.context.ApplicationContext;
71 import org.springframework.context.annotation.Bean;
72 import org.springframework.http.HttpEntity;
73 import org.springframework.http.HttpHeaders;
74 import org.springframework.http.HttpMethod;
75 import org.springframework.http.HttpStatus;
76 import org.springframework.http.HttpStatus.Series;
77 import org.springframework.http.MediaType;
78 import org.springframework.http.ResponseEntity;
79 import org.springframework.http.client.ClientHttpResponse;
80 import org.springframework.test.context.junit.jupiter.SpringExtension;
81 import org.springframework.web.client.ResponseErrorHandler;
82 import org.springframework.web.client.RestTemplate;
84 @ExtendWith(SpringExtension.class)
85 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
86 public class ApplicationTest {
88 ApplicationContext context;
94 private Policies policies;
97 private PolicyTypes policyTypes;
100 MockA1ClientFactory a1ClientFactory;
103 RepositorySupervision supervision;
108 private static Gson gson = new GsonBuilder() //
112 public static class MockApplicationConfig extends ApplicationConfig {
114 public String getLocalConfigurationFilePath() {
115 return ""; // No config file loaded for the test
120 * Overrides the BeanFactory.
123 static class TestBeanFactory {
124 private final PolicyTypes policyTypes = new PolicyTypes();
127 public ApplicationConfig getApplicationConfig() {
128 return new MockApplicationConfig();
132 MockA1ClientFactory getA1ClientFactory() {
133 return new MockA1ClientFactory(this.policyTypes);
137 public PolicyTypes getPolicyTypes() {
138 return this.policyTypes;
145 private final RestTemplate restTemplate = new RestTemplate();
147 public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
150 public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
151 return (httpResponse.getStatusCode().series() == Series.CLIENT_ERROR
152 || httpResponse.getStatusCode().series() == Series.SERVER_ERROR);
156 public void handleError(ClientHttpResponse httpResponse) throws IOException {
157 System.out.println("Error " + httpResponse.toString());
161 private void setRestErrorhandler() {
162 restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
166 public void reset() {
174 public void verifyNoRicLocks() {
175 for (Ric ric : this.rics.getRics()) {
176 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
177 ric.getLock().unlock();
178 assertThat(ric.getLock().getLockCounter()).isEqualTo(0);
179 assertThat(ric.getState()).isEqualTo(Ric.RicState.IDLE);
184 public void testGetRics() throws Exception {
186 String url = baseUrl() + "/rics";
187 String rsp = this.restTemplate.getForObject(url, String.class);
188 System.out.println(rsp);
189 assertThat(rsp).contains("kista_1");
191 url = baseUrl() + "/rics?policyType=STD_PolicyModelUnconstrained_0.2.0";
192 rsp = this.restTemplate.getForObject(url, String.class);
193 assertThat(rsp).isEqualTo("[]");
197 public void testRecovery() throws Exception {
198 addRic("ric").setState(Ric.RicState.UNDEFINED);
199 String ricName = "ric";
200 Policy policy2 = addPolicy("policyId2", "typeName", "service", ricName);
202 getA1Client(ricName).putPolicy(policy2); // put it in the RIC
203 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
205 String policyId = "policyId";
206 Policy policy = addPolicy(policyId, "typeName", "service", ricName); // This should be created in the RIC
207 supervision.checkAllRics(); // The created policy should be put in the RIC
208 await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ricName).getState()));
209 await().untilAsserted(() -> RicState.IDLE.equals(rics.getRic(ricName).getState()));
211 Policies ricPolicies = getA1Client(ricName).getPolicies();
212 assertThat(ricPolicies.size()).isEqualTo(1);
213 Policy ricPolicy = ricPolicies.get(policyId);
214 assertThat(ricPolicy.json()).isEqualTo(policy.json());
218 public void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
219 addRic("notCorrectRic1");
220 addRic("notCorrectRic2");
221 addRic("notCorrectRic3");
222 addRic("notCorrectRic4");
223 addRic("notCorrectRic5");
224 addRic("notCorrectRic6");
226 String ricName = "ric1";
227 Ric ric = addRic(ricName);
228 String managedElementId = "kista_1";
229 ric.addManagedElement(managedElementId);
231 String url = baseUrl() + "/ric?managedElementId=" + managedElementId;
232 String rsp = this.restTemplate.getForObject(url, String.class);
234 assertThat(rsp).isEqualTo(ricName);
238 public void testGetRicForManagedElementThatDoesNotExist() throws Exception {
239 this.setRestErrorhandler();
240 String url = baseUrl() + "/ric?managedElementId=kista_1";
241 ResponseEntity<String> entity = this.restTemplate.getForEntity(url, String.class);
242 assertThat(entity.getStatusCode().equals(HttpStatus.NOT_FOUND));
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 = baseUrl() + "/policy?type=" + policyTypeName + "&instance=" + policyInstanceId + "&ric=" + ricName
256 + "&service=" + serviceName;
257 final String json = jsonString();
258 this.rics.getRic(ricName).setState(Ric.RicState.IDLE);
260 this.restTemplate.put(url, createJsonHttpEntity(json));
262 Policy policy = policies.getPolicy(policyInstanceId);
263 assertThat(policy).isNotNull();
264 assertThat(policy.id()).isEqualTo(policyInstanceId);
265 assertThat(policy.ownerServiceName()).isEqualTo(serviceName);
266 assertThat(policy.ric().name()).isEqualTo("ric1");
268 url = baseUrl() + "/policies";
269 String rsp = this.restTemplate.getForObject(url, String.class);
270 assertThat(rsp.contains(policyInstanceId)).isTrue();
275 public void testRefuseToUpdatePolicy() throws Exception {
276 // Test that only the json can be changed for a already created policy
277 // In this case service is attempted to be changed
279 this.addRic("ricXXX");
281 this.addPolicy("instance1", "type1", "service1", "ric1");
282 this.setRestErrorhandler();
283 String urlWrongRic = baseUrl() + "/policy?type=type1&instance=instance1&ric=ricXXX&service=service1";
284 ResponseEntity<String> entity = this.putForEntity(urlWrongRic, jsonString());
285 assertThat(entity.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED));
287 Policy policy = policies.getPolicy("instance1");
288 assertThat(policy.ric().name()).isEqualTo("ric1"); // Not changed
292 public void testGetPolicy() throws Exception {
293 String url = baseUrl() + "/policy?instance=id";
294 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
296 String rsp = this.restTemplate.getForObject(url, String.class);
297 assertThat(rsp).isEqualTo(policy.json());
300 policies.remove(policy);
301 ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class);
302 assertThat(rsp.getStatusCodeValue()).isEqualTo(HttpStatus.NO_CONTENT.value());
307 public void testDeletePolicy() throws Exception {
308 String url = baseUrl() + "/policy?instance=id";
309 addPolicy("id", "typeName", "service1", "ric1");
310 assertThat(policies.size()).isEqualTo(1);
312 this.restTemplate.delete(url);
314 assertThat(policies.size()).isEqualTo(0);
318 public void testGetPolicySchemas() throws Exception {
319 addPolicyType("type1", "ric1");
320 addPolicyType("type2", "ric2");
322 String url = baseUrl() + "/policy_schemas";
323 String rsp = this.restTemplate.getForObject(url, String.class);
324 System.out.println("*** " + rsp);
325 assertThat(rsp).contains("type1");
326 assertThat(rsp).contains("[{\"title\":\"type2\"}");
328 List<String> info = parseSchemas(rsp);
329 assertThat(info.size()).isEqualTo(2);
331 url = baseUrl() + "/policy_schemas?ric=ric1";
332 rsp = this.restTemplate.getForObject(url, String.class);
333 assertThat(rsp).contains("type1");
334 info = parseSchemas(rsp);
335 assertThat(info.size()).isEqualTo(1);
339 public void testGetPolicySchema() throws Exception {
340 addPolicyType("type1", "ric1");
341 addPolicyType("type2", "ric2");
343 String url = baseUrl() + "/policy_schema?id=type1";
344 String rsp = this.restTemplate.getForObject(url, String.class);
345 System.out.println(rsp);
346 assertThat(rsp).contains("type1");
347 assertThat(rsp).contains("title");
351 public void testGetPolicyTypes() throws Exception {
352 addPolicyType("type1", "ric1");
353 addPolicyType("type2", "ric2");
355 String url = baseUrl() + "/policy_types";
356 String rsp = this.restTemplate.getForObject(url, String.class);
357 assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
359 url = baseUrl() + "/policy_types?ric=ric1";
360 rsp = this.restTemplate.getForObject(url, String.class);
361 assertThat(rsp).isEqualTo("[\"type1\"]");
365 public void testGetPolicies() throws Exception {
367 String url = baseUrl() + "/policies";
368 addPolicy("id1", "type1", "service1");
370 String rsp = this.restTemplate.getForObject(url, String.class);
371 System.out.println(rsp);
372 List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
373 assertThat(info).size().isEqualTo(1);
374 PolicyInfo policyInfo = info.get(0);
375 assert (policyInfo.validate());
376 assertThat(policyInfo.id).isEqualTo("id1");
377 assertThat(policyInfo.type).isEqualTo("type1");
378 assertThat(policyInfo.service).isEqualTo("service1");
382 public void testGetPoliciesFilter() throws Exception {
383 addPolicy("id1", "type1", "service1");
384 addPolicy("id2", "type1", "service2");
385 addPolicy("id3", "type2", "service1");
387 String url = baseUrl() + "/policies?type=type1";
388 String rsp = this.restTemplate.getForObject(url, String.class);
389 System.out.println(rsp);
390 assertThat(rsp).contains("id1");
391 assertThat(rsp).contains("id2");
392 assertThat(rsp.contains("id3")).isFalse();
394 url = baseUrl() + "/policies?type=type1&service=service2";
395 rsp = this.restTemplate.getForObject(url, String.class);
396 System.out.println(rsp);
397 assertThat(rsp.contains("id1")).isFalse();
398 assertThat(rsp).contains("id2");
399 assertThat(rsp.contains("id3")).isFalse();
403 public void testPutAndGetService() throws Exception {
408 String url = baseUrl() + "/services?serviceName=name";
409 String rsp = this.restTemplate.getForObject(url, String.class);
410 List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
411 assertThat(info.size()).isEqualTo(1);
412 ServiceStatus status = info.iterator().next();
413 assertThat(status.keepAliveIntervalSeconds).isEqualTo(1);
414 assertThat(status.serviceName).isEqualTo("name");
417 url = baseUrl() + "/services";
418 rsp = this.restTemplate.getForObject(url, String.class);
419 assertThat(rsp.contains("name")).isTrue();
420 System.out.println(rsp);
423 url = baseUrl() + "/services/keepalive?name=name";
424 ResponseEntity<String> entity = this.restTemplate.postForEntity(url, null, String.class);
425 assertThat(entity.getStatusCode().equals(HttpStatus.OK));
428 assertThat(services.size()).isEqualTo(1);
429 url = baseUrl() + "/services?name=name";
430 this.restTemplate.delete(url);
431 assertThat(services.size()).isEqualTo(0);
433 // Keep alive, no registerred service
434 url = baseUrl() + "/services/keepalive?name=name";
435 setRestErrorhandler();
436 entity = this.restTemplate.postForEntity(url, null, String.class);
437 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
441 public void testGetPolicyStatus() throws Exception {
442 addPolicy("id", "typeName", "service1", "ric1");
443 assertThat(policies.size()).isEqualTo(1);
445 String url = baseUrl() + "/policy_status?instance=id";
446 String rsp = this.restTemplate.getForObject(url, String.class);
447 assertThat(rsp.equals("OK")).isTrue();
450 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
452 Policy p = ImmutablePolicy.builder().id(id) //
453 .json(jsonString()) //
454 .ownerServiceName(service) //
455 .ric(rics.getRic(ric)) //
456 .type(addPolicyType(typeName, ric)) //
457 .lastModified("lastModified").build();
462 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
463 return addPolicy(id, typeName, service, "ric");
466 private String createServiceJson(String name) {
467 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, 1, "callbackUrl");
469 String json = gson.toJson(service);
473 private void putService(String name) {
474 String url = baseUrl() + "/service";
475 HttpEntity<String> entity = createJsonHttpEntity(createServiceJson(name));
476 this.restTemplate.put(url, entity);
479 private String baseUrl() {
480 return "http://localhost:" + port;
483 private String jsonString() {
484 return "{\n \"servingCellNrcgi\": \"1\"\n }";
487 private static class ConcurrencyTestRunnable implements Runnable {
488 private final RestTemplate restTemplate = new RestTemplate();
489 private final String baseUrl;
490 static AtomicInteger nextCount = new AtomicInteger(0);
491 private final int count;
492 private final RepositorySupervision supervision;
494 ConcurrencyTestRunnable(String baseUrl, RepositorySupervision supervision) {
495 this.baseUrl = baseUrl;
496 this.count = nextCount.incrementAndGet();
497 this.supervision = supervision;
501 for (int i = 0; i < 100; ++i) {
503 this.supervision.checkAllRics();
505 String name = "policy:" + count + ":" + i;
511 private void putPolicy(String name) {
512 String putUrl = baseUrl + "/policy?type=type1&instance=" + name + "&ric=ric1&service=service1";
513 this.restTemplate.put(putUrl, createJsonHttpEntity("{}"));
516 private void deletePolicy(String name) {
517 String deleteUrl = baseUrl + "/policy?instance=" + name;
518 this.restTemplate.delete(deleteUrl);
523 public void testConcurrency() throws Exception {
524 final Instant startTime = Instant.now();
525 List<Thread> threads = new ArrayList<>();
527 addPolicyType("type1", "ric1");
529 for (int i = 0; i < 100; ++i) {
530 Thread t = new Thread(new ConcurrencyTestRunnable(baseUrl(), this.supervision), "TestThread_" + i);
534 for (Thread t : threads) {
537 assertThat(policies.size()).isEqualTo(0);
538 System.out.println("Concurrency test took " + Duration.between(startTime, Instant.now()));
541 private MockA1Client getA1Client(String ricName) throws ServiceException {
542 return a1ClientFactory.getOrCreateA1Client(ricName);
545 private PolicyType addPolicyType(String policyTypeName, String ricName) {
546 PolicyType type = ImmutablePolicyType.builder() //
547 .name(policyTypeName) //
548 .schema("{\"title\":\"" + policyTypeName + "\"}") //
551 policyTypes.put(type);
552 addRic(ricName).addSupportedPolicyType(type);
556 private Ric addRic(String ricName) {
557 if (rics.get(ricName) != null) {
558 return rics.get(ricName);
560 Vector<String> mes = new Vector<>();
561 RicConfig conf = ImmutableRicConfig.builder() //
564 .managedElementIds(mes) //
566 Ric ric = new Ric(conf);
567 ric.setState(Ric.RicState.IDLE);
572 private static HttpEntity<String> createJsonHttpEntity(String content) {
573 HttpHeaders headers = new HttpHeaders();
574 headers.setContentType(MediaType.APPLICATION_JSON);
575 return new HttpEntity<String>(content, headers);
578 private ResponseEntity<String> putForEntity(String url, String jsonBody) {
579 return restTemplate.exchange(url, HttpMethod.PUT, createJsonHttpEntity(jsonBody), String.class);
582 private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
583 List<T> result = new ArrayList<>();
584 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
585 for (JsonElement jsonElement : jsonArr) {
586 T o = gson.fromJson(jsonElement.toString(), clazz);
592 private static List<String> parseSchemas(String jsonString) {
593 JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
594 List<String> result = new ArrayList<>();
595 for (JsonElement schemaObject : arrayOfSchema) {
596 result.add(schemaObject.toString());