5ef70aa92c95b1487aefc9c635585a141d481fbd
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
22
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;
29
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
32
33 import java.nio.charset.StandardCharsets;
34 import java.time.Duration;
35 import java.time.Instant;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.List;
39
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.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
45 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
46 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
47 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
48 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
49 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
50 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
62 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
63 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
64 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
65 import org.onap.ccsdk.oran.a1policymanagementservice.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.embedded.tomcat.TomcatServletWebServerFactory;
73 import org.springframework.boot.web.server.LocalServerPort;
74 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
75 import org.springframework.context.ApplicationContext;
76 import org.springframework.context.annotation.Bean;
77 import org.springframework.http.HttpStatus;
78 import org.springframework.http.MediaType;
79 import org.springframework.http.ResponseEntity;
80 import org.springframework.test.context.TestPropertySource;
81 import org.springframework.test.context.junit.jupiter.SpringExtension;
82 import org.springframework.web.reactive.function.client.WebClientResponseException;
83
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
86 import reactor.util.annotation.Nullable;
87
88 @ExtendWith(SpringExtension.class)
89 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
90 @TestPropertySource(
91     properties = { //
92         "server.ssl.key-store=./config/keystore.jks", //
93         "app.webclient.trust-store=./config/truststore.jks"})
94 class ApplicationTest {
95     private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
96
97     @Autowired
98     ApplicationContext context;
99
100     @Autowired
101     private Rics rics;
102
103     @Autowired
104     private Policies policies;
105
106     @Autowired
107     private PolicyTypes policyTypes;
108
109     @Autowired
110     MockA1ClientFactory a1ClientFactory;
111
112     @Autowired
113     RicSupervision supervision;
114
115     @Autowired
116     ApplicationConfig applicationConfig;
117
118     @Autowired
119     Services services;
120
121     private static Gson gson = new GsonBuilder() //
122         .serializeNulls() //
123         .create(); //
124
125     public static class MockApplicationConfig extends ApplicationConfig {
126         @Override
127         public String getLocalConfigurationFilePath() {
128             return ""; // No config file loaded for the test
129         }
130     }
131
132     /**
133      * Overrides the BeanFactory.
134      */
135     @TestConfiguration
136     static class TestBeanFactory {
137         private final PolicyTypes policyTypes = new PolicyTypes();
138         private final Services services = new Services();
139         private final Policies policies = new Policies();
140         MockA1ClientFactory a1ClientFactory = null;
141
142         @Bean
143         public ApplicationConfig getApplicationConfig() {
144             return new MockApplicationConfig();
145         }
146
147         @Bean
148         MockA1ClientFactory getA1ClientFactory() {
149             if (a1ClientFactory == null) {
150                 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
151             }
152             return this.a1ClientFactory;
153         }
154
155         @Bean
156         public PolicyTypes getPolicyTypes() {
157             return this.policyTypes;
158         }
159
160         @Bean
161         Policies getPolicies() {
162             return this.policies;
163         }
164
165         @Bean
166         Services getServices() {
167             return this.services;
168         }
169
170         @Bean
171         public ServiceSupervision getServiceSupervision() {
172             Duration checkInterval = Duration.ofMillis(1);
173             return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
174         }
175
176         @Bean
177         public ServletWebServerFactory servletContainer() {
178             return new TomcatServletWebServerFactory();
179         }
180
181     }
182
183     @LocalServerPort
184     private int port;
185
186     @BeforeEach
187     void reset() {
188         rics.clear();
189         policies.clear();
190         policyTypes.clear();
191         services.clear();
192         a1ClientFactory.reset();
193     }
194
195     @AfterEach
196     void verifyNoRicLocks() {
197         for (Ric ric : this.rics.getRics()) {
198             ric.getLock().lockBlocking(LockType.EXCLUSIVE);
199             ric.getLock().unlockBlocking();
200             assertThat(ric.getLock().getLockCounter()).isZero();
201             assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
202         }
203     }
204
205     @Test
206     void testGetRics() throws Exception {
207         addRic("ric1");
208         this.addPolicyType("type1", "ric1");
209         String url = "/rics?policytype_id=type1";
210         String rsp = restClient().get(url).block();
211         assertThat(rsp).contains("ric1");
212
213         // nameless type for ORAN A1 1.1
214         addRic("ric2");
215         this.addPolicyType("", "ric2");
216         url = "/rics?policytype_id=";
217
218         // This tests also validation of trusted certs restClient(true)
219         rsp = restClient(true).get(url).block();
220         assertThat(rsp).contains("ric2") //
221             .doesNotContain("ric1") //
222             .contains("AVAILABLE");
223
224         // All RICs
225         rsp = restClient().get("/rics").block();
226         assertThat(rsp).contains("ric2") //
227             .contains("ric1");
228
229         // Non existing policy type
230         url = "/rics?policytype_id=XXXX";
231         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
232     }
233
234     @Test
235     void testSynchronization() throws Exception {
236         // Two polictypes will be put in the NearRT RICs
237         PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
238         nearRtRicPolicyTypes.put(createPolicyType("typeName"));
239         nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
240         this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
241
242         // One type and one instance added to the Policy Management Service's storage
243         final String ric1Name = "ric1";
244         Ric ric1 = addRic(ric1Name);
245         Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
246         Ric ric2 = addRic("ric2");
247
248         getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
249         policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
250
251         String policyId = "policyId";
252         Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
253         supervision.checkAllRics(); // The created policy should be put in the RIC
254
255         // Wait until synch is completed
256         await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ric1Name).getState()));
257         await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic(ric1Name).getState()));
258         await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic("ric2").getState()));
259
260         Policies ricPolicies = getA1Client(ric1Name).getPolicies();
261         assertThat(ricPolicies.size()).isEqualTo(1);
262         Policy ricPolicy = ricPolicies.get(policyId);
263         assertThat(ricPolicy.json()).isEqualTo(policy.json());
264
265         // Both types should be in the Policy Management Service's storage after the
266         // synch
267         assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
268         assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
269     }
270
271     @Test
272     void testGetRic() throws Exception {
273         String ricId = "ric1";
274         String managedElementId = "kista_1";
275         addRic(ricId, managedElementId);
276
277         String url = "/ric?managed_element_id=" + managedElementId;
278         String rsp = restClient().get(url).block();
279         RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
280         assertThat(ricInfo.ricId).isEqualTo(ricId);
281
282         url = "/ric?ric_id=" + ricId;
283         rsp = restClient().get(url).block();
284         ricInfo = gson.fromJson(rsp, RicInfo.class);
285         assertThat(ricInfo.ricId).isEqualTo(ricId);
286
287         // test GET RIC for ManagedElement that does not exist
288         url = "/ric?managed_element_id=" + "junk";
289         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
290
291         url = "/ric";
292         testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
293     }
294
295     private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
296         boolean isTransient) {
297         String url;
298         if (policyTypeName.isEmpty()) {
299             url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName;
300         } else {
301             url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName
302                 + "&policytype_id=" + policyTypeName;
303         }
304         if (isTransient) {
305             url += "&transient=true";
306         }
307         return url;
308     }
309
310     private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
311         return putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, false);
312     }
313
314     @Test
315     void testPutPolicy() throws Exception {
316         String serviceName = "service1";
317         String ricId = "ric1";
318         String policyTypeName = "type1";
319         String policyInstanceId = "instance1";
320
321         putService(serviceName);
322         addPolicyType(policyTypeName, ricId);
323
324         // PUT a transient policy
325         String url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, true);
326         final String policyBody = jsonString();
327         this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
328
329         restClient().put(url, policyBody).block();
330
331         Policy policy = policies.getPolicy(policyInstanceId);
332         assertThat(policy).isNotNull();
333         assertThat(policy.id()).isEqualTo(policyInstanceId);
334         assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
335         assertThat(policy.ric().id()).isEqualTo("ric1");
336         assertThat(policy.isTransient()).isTrue();
337
338         // Put a non transient policy
339         url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
340         restClient().put(url, policyBody).block();
341         policy = policies.getPolicy(policyInstanceId);
342         assertThat(policy.isTransient()).isFalse();
343
344         url = "/policies";
345         String rsp = restClient().get(url).block();
346         assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
347
348         url = "/policy?policy_id=" + policyInstanceId;
349         rsp = restClient().get(url).block();
350         assertThat(rsp).isEqualTo(policyBody);
351
352         // Test of error codes
353         url = putPolicyUrl(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
354         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
355
356         url = putPolicyUrl(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
357         addPolicyType(policyTypeName + "XX", "otherRic");
358         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
359
360         url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
361         this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
362         testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
363         this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
364     }
365
366     @Test
367     /**
368      * Test that HttpStatus and body from failing REST call to A1 is passed on to
369      * the caller.
370      *
371      * @throws ServiceException
372      */
373     void testErrorFromRic() throws ServiceException {
374         putService("service1");
375         addPolicyType("type1", "ric1");
376
377         String url = putPolicyUrl("service1", "ric1", "type1", "id1");
378         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
379         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
380         String responseBody = "Refused";
381         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
382
383         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
384             responseBodyBytes, StandardCharsets.UTF_8, null);
385         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
386
387         // PUT Policy
388         testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
389
390         // DELETE POLICY
391         this.addPolicy("instance1", "type1", "service1", "ric1");
392         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
393         testErrorCode(restClient().delete("/policy?policy_id=instance1"), httpStatus, responseBody);
394
395         // GET STATUS
396         this.addPolicy("instance1", "type1", "service1", "ric1");
397         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
398         testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus, responseBody);
399
400         // Check that empty response body is OK
401         a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
402         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
403         testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus);
404     }
405
406     @Test
407     void testPutTypelessPolicy() throws Exception {
408         putService("service1");
409         addPolicyType("", "ric1");
410         String url = putPolicyUrl("service1", "ric1", "", "id1");
411         restClient().put(url, jsonString()).block();
412
413         String rsp = restClient().get("/policies").block();
414         PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
415         assertThat(info.policies).hasSize(1);
416         PolicyInfo policyInfo = info.policies.iterator().next();
417         assertThat(policyInfo.policyId).isEqualTo("id1");
418         assertThat(policyInfo.policyTypeId).isEmpty();
419     }
420
421     @Test
422     void testRefuseToUpdatePolicy() throws Exception {
423         // Test that only the json can be changed for a already created policy
424         // In this case service is attempted to be changed
425         this.addRic("ric1");
426         this.addRic("ricXXX");
427         this.addPolicy("instance1", "type1", "service1", "ric1");
428         this.addPolicy("instance2", "type1", "service1", "ricXXX");
429
430         // Try change ric1 -> ricXXX
431         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
432         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
433     }
434
435     @Test
436     void testGetPolicy() throws Exception {
437         String url = "/policy?policy_id=id";
438         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
439         {
440             String rsp = restClient().get(url).block();
441             assertThat(rsp).isEqualTo(policy.json());
442         }
443         {
444             policies.remove(policy);
445             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
446         }
447     }
448
449     @Test
450     void testDeletePolicy() throws Exception {
451         addPolicy("id", "typeName", "service1", "ric1");
452         assertThat(policies.size()).isEqualTo(1);
453
454         String url = "/policy?policy_id=id";
455         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
456
457         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
458         assertThat(policies.size()).isZero();
459
460         // Delete a non existing policy
461         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
462     }
463
464     @Test
465     void testGetPolicySchemas() throws Exception {
466         addPolicyType("type1", "ric1");
467         addPolicyType("type2", "ric2");
468
469         String url = "/policy-schemas";
470         String rsp = this.restClient().get(url).block();
471         assertThat(rsp).contains("type1") //
472             .contains("[{\"title\":\"type2\"}");
473
474         PolicySchemaList info = parseSchemas(rsp);
475         assertThat(info.schemas).hasSize(2);
476
477         url = "/policy-schemas?ric_id=ric1";
478         rsp = restClient().get(url).block();
479         assertThat(rsp).contains("type1");
480         info = parseSchemas(rsp);
481         assertThat(info.schemas).hasSize(1);
482
483         // Schema for type
484         url = "/policy-schemas?policytype_id=type1";
485         rsp = restClient().get(url).block();
486         assertThat(rsp).contains("type1") //
487             .contains("title");
488
489         // Both type and ric specified
490         url = "/policy-schemas?ric_id=ric1&policytype_id=type1";
491         rsp = restClient().get(url).block();
492         PolicySchemaList list = gson.fromJson(rsp, PolicySchemaList.class);
493         assertThat(list.schemas).hasSize(1);
494
495         url = "/policy-schemas?ric_id=ric1&policytype_id=type2";
496         rsp = restClient().get(url).block();
497         list = gson.fromJson(rsp, PolicySchemaList.class);
498         assertThat(list.schemas).isEmpty();
499
500         // Get schema for non existing RIC
501         url = "/policy-schemas?ric_id=ric1XXX";
502         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
503
504         // Get non existing schema
505         url = "/policy-schemas?policytype_id=type1XX";
506         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
507     }
508
509     String createPolicyTypesJson(String... types) {
510         List<String> list = new ArrayList<>();
511         Collections.addAll(list, types);
512         PolicyTypeIdList ids = new PolicyTypeIdList(list);
513         return gson.toJson(ids);
514     }
515
516     @Test
517     void testGetPolicyTypes() throws Exception {
518         addPolicyType("type1", "ric1");
519         addPolicyType("type2", "ric2");
520
521         String url = "/policy-types";
522         String rsp = restClient().get(url).block();
523         String expResp = createPolicyTypesJson("type2", "type1");
524         assertThat(rsp).isEqualTo(expResp);
525
526         url = "/policy-types?ric_id=ric1";
527         rsp = restClient().get(url).block();
528         expResp = createPolicyTypesJson("type1");
529         assertThat(rsp).isEqualTo(expResp);
530
531         // Get policy types for non existing RIC
532         url = "/policy-types?ric_id=ric1XXX";
533         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
534     }
535
536     @Test
537     void testGetPolicies() throws Exception {
538         addPolicy("id1", "type1", "service1");
539
540         String url = "/policies";
541         String rsp = restClient().get(url).block();
542         logger.info(rsp);
543         PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
544         assertThat(info.policies).hasSize(1);
545         PolicyInfo policyInfo = info.policies.iterator().next();
546         assert (policyInfo.validate());
547         assertThat(policyInfo.policyId).isEqualTo("id1");
548         assertThat(policyInfo.policyTypeId).isEqualTo("type1");
549         assertThat(policyInfo.serviceId).isEqualTo("service1");
550     }
551
552     @Test
553     void testGetPoliciesFilter() throws Exception {
554         addPolicy("id1", "type1", "service1");
555         addPolicy("id2", "type1", "service2");
556         addPolicy("id3", "type2", "service1");
557
558         String url = "/policies?policytype_id=type1";
559         String rsp = restClient().get(url).block();
560         logger.info(rsp);
561         assertThat(rsp).contains("id1") //
562             .contains("id2") //
563             .doesNotContain("id3");
564
565         url = "/policies?policytype_id=type1&service_id=service2";
566         rsp = restClient().get(url).block();
567         logger.info(rsp);
568         assertThat(rsp).doesNotContain("id1") //
569             .contains("id2") //
570             .doesNotContain("id3");
571
572         // Test get policies for non existing type
573         url = "/policies?policytype_id=type1XXX";
574         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
575
576         // Test get policies for non existing RIC
577         url = "/policies?ric_id=XXX";
578         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
579     }
580
581     @Test
582     void testGetPolicyIdsFilter() throws Exception {
583         addPolicy("id1", "type1", "service1", "ric1");
584         addPolicy("id2", "type1", "service2", "ric1");
585         addPolicy("id3", "type2", "service1", "ric1");
586
587         String url = "/policy-ids?policytype_id=type1";
588         String rsp = restClient().get(url).block();
589         logger.info(rsp);
590         assertThat(rsp).contains("id1") //
591             .contains("id2") //
592             .doesNotContain("id3");
593
594         url = "/policy-ids?policytype_id=type1&service_id=service1&ric=ric1";
595         rsp = restClient().get(url).block();
596         PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
597         assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
598
599         // Test get policy ids for non existing type
600         url = "/policy-ids?policytype_id=type1XXX";
601         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
602
603         // Test get policy ids for non existing RIC
604         url = "/policy-ids?ric_id=XXX";
605         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
606     }
607
608     @Test
609     void testPutAndGetService() throws Exception {
610         // PUT
611         String serviceName = "name";
612         putService(serviceName, 0, HttpStatus.CREATED);
613         putService(serviceName, 0, HttpStatus.OK);
614
615         // GET one service
616         String url = "/services?service_id=name";
617         String rsp = restClient().get(url).block();
618         ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
619         assertThat(info.statusList).hasSize(1);
620         ServiceStatus status = info.statusList.iterator().next();
621         assertThat(status.keepAliveIntervalSeconds).isZero();
622         assertThat(status.serviceId).isEqualTo(serviceName);
623
624         // GET (all)
625         url = "/services";
626         rsp = restClient().get(url).block();
627         assertThat(rsp).as("Response contains service name").contains(serviceName);
628         logger.info(rsp);
629
630         // Keep alive
631         url = "/services/keepalive?service_id=name";
632         ResponseEntity<?> entity = restClient().putForEntity(url).block();
633         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
634
635         // DELETE service
636         assertThat(services.size()).isEqualTo(1);
637         url = "/services?service_id=name";
638         restClient().delete(url).block();
639         assertThat(services.size()).isZero();
640
641         // Keep alive, no registered service
642         testErrorCode(restClient().put("/services/keepalive?service_id=name", ""), HttpStatus.NOT_FOUND);
643
644         // PUT service with bad payload
645         testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
646         testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
647         testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
648             false);
649         testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
650             HttpStatus.BAD_REQUEST, false);
651
652         // GET non existing service
653         testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
654     }
655
656     @Test
657     void testServiceSupervision() throws Exception {
658         putService("service1", 1, HttpStatus.CREATED);
659         addPolicyType("type1", "ric1");
660
661         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
662         final String policyBody = jsonString();
663         restClient().put(url, policyBody).block();
664
665         assertThat(policies.size()).isEqualTo(1);
666         assertThat(services.size()).isEqualTo(1);
667
668         // Timeout after ~1 second
669         await().untilAsserted(() -> assertThat(policies.size()).isZero());
670         assertThat(services.size()).isZero();
671     }
672
673     @Test
674     void testGetPolicyStatus() throws Exception {
675         addPolicy("id", "typeName", "service1", "ric1");
676         assertThat(policies.size()).isEqualTo(1);
677
678         String url = "/policy-status?policy_id=id";
679         String rsp = restClient().get(url).block();
680         assertThat(rsp).isEqualTo("OK");
681
682         // GET non existing policy status
683         url = "/policy-status?policy_id=XXX";
684         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
685     }
686
687     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
688         addRic(ric);
689         Policy policy = ImmutablePolicy.builder() //
690             .id(id) //
691             .json(jsonString()) //
692             .ownerServiceId(service) //
693             .ric(rics.getRic(ric)) //
694             .type(addPolicyType(typeName, ric)) //
695             .lastModified(Instant.now()) //
696             .isTransient(false) //
697             .build();
698         policies.put(policy);
699         return policy;
700     }
701
702     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
703         return addPolicy(id, typeName, service, "ric");
704     }
705
706     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
707         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
708     }
709
710     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
711         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
712
713         String json = gson.toJson(service);
714         return json;
715     }
716
717     private void putService(String name) {
718         putService(name, 0, null);
719     }
720
721     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
722         String url = "/services";
723         String body = createServiceJson(name, keepAliveIntervalSeconds);
724         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
725         if (expectedStatus != null) {
726             assertEquals(expectedStatus, resp.getStatusCode(), "");
727         }
728     }
729
730     private String baseUrl() {
731         return "https://localhost:" + port + Consts.V2_API_ROOT;
732     }
733
734     private String jsonString() {
735         return "{\"servingCellNrcgi\":\"1\"}";
736     }
737
738     @Test
739     void testConcurrency() throws Exception {
740         final Instant startTime = Instant.now();
741         List<Thread> threads = new ArrayList<>();
742         List<ConcurrencyTestRunnable> tests = new ArrayList<>();
743         a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
744         addRic("ric");
745         addPolicyType("type1", "ric");
746         addPolicyType("type2", "ric");
747
748         for (int i = 0; i < 10; ++i) {
749             AsyncRestClient restClient = restClient();
750             ConcurrencyTestRunnable test =
751                 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
752             Thread thread = new Thread(test, "TestThread_" + i);
753             thread.start();
754             threads.add(thread);
755             tests.add(test);
756         }
757         for (Thread t : threads) {
758             t.join();
759         }
760         for (ConcurrencyTestRunnable test : tests) {
761             assertThat(test.isFailed()).isFalse();
762         }
763         assertThat(policies.size()).isZero();
764         logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
765     }
766
767     private AsyncRestClient restClient(boolean useTrustValidation) {
768         WebClientConfig config = this.applicationConfig.getWebClientConfig();
769         config = ImmutableWebClientConfig.builder() //
770             .keyStoreType(config.keyStoreType()) //
771             .keyStorePassword(config.keyStorePassword()) //
772             .keyStore(config.keyStore()) //
773             .keyPassword(config.keyPassword()) //
774             .isTrustStoreUsed(useTrustValidation) //
775             .trustStore(config.trustStore()) //
776             .trustStorePassword(config.trustStorePassword()) //
777             .build();
778
779         return new AsyncRestClient(baseUrl(), config);
780     }
781
782     private AsyncRestClient restClient() {
783         return restClient(false);
784     }
785
786     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
787         testErrorCode(request, expStatus, "", true);
788     }
789
790     private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
791         testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
792     }
793
794     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
795         testErrorCode(request, expStatus, responseContains, true);
796     }
797
798     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
799         boolean expectApplicationProblemJsonMediaType) {
800         StepVerifier.create(request) //
801             .expectSubscription() //
802             .expectErrorMatches(
803                 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
804             .verify();
805     }
806
807     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
808         boolean expectApplicationProblemJsonMediaType) {
809         assertTrue(throwable instanceof WebClientResponseException);
810         WebClientResponseException responseException = (WebClientResponseException) throwable;
811         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
812         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
813         if (expectApplicationProblemJsonMediaType) {
814             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
815         }
816         return true;
817     }
818
819     private MockA1Client getA1Client(String ricId) throws ServiceException {
820         return a1ClientFactory.getOrCreateA1Client(ricId);
821     }
822
823     private PolicyType createPolicyType(String policyTypeName) {
824         return ImmutablePolicyType.builder() //
825             .id(policyTypeName) //
826             .schema("{\"title\":\"" + policyTypeName + "\"}") //
827             .build();
828     }
829
830     private PolicyType addPolicyType(String policyTypeName, String ricId) {
831         PolicyType type = createPolicyType(policyTypeName);
832         policyTypes.put(type);
833         addRic(ricId).addSupportedPolicyType(type);
834         return type;
835     }
836
837     private Ric addRic(String ricId) {
838         return addRic(ricId, null);
839     }
840
841     private Ric addRic(String ricId, String managedElement) {
842         if (rics.get(ricId) != null) {
843             return rics.get(ricId);
844         }
845         List<String> mes = new ArrayList<>();
846         if (managedElement != null) {
847             mes.add(managedElement);
848         }
849         RicConfig conf = ImmutableRicConfig.builder() //
850             .ricId(ricId) //
851             .baseUrl(ricId) //
852             .managedElementIds(mes) //
853             .controllerName("") //
854             .build();
855         Ric ric = new Ric(conf);
856         ric.setState(Ric.RicState.AVAILABLE);
857         this.rics.put(ric);
858         return ric;
859     }
860
861     private static PolicySchemaList parseSchemas(String jsonString) {
862         return gson.fromJson(jsonString, PolicySchemaList.class);
863     }
864 }