Added a test for service supervision
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / controllers / PolicyController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent.controllers;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import io.swagger.annotations.ApiResponse;
29 import io.swagger.annotations.ApiResponses;
30
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.List;
34
35 import org.oransc.policyagent.clients.A1ClientFactory;
36 import org.oransc.policyagent.exceptions.ServiceException;
37 import org.oransc.policyagent.repository.ImmutablePolicy;
38 import org.oransc.policyagent.repository.Lock.LockType;
39 import org.oransc.policyagent.repository.Policies;
40 import org.oransc.policyagent.repository.Policy;
41 import org.oransc.policyagent.repository.PolicyType;
42 import org.oransc.policyagent.repository.PolicyTypes;
43 import org.oransc.policyagent.repository.Ric;
44 import org.oransc.policyagent.repository.Rics;
45 import org.oransc.policyagent.repository.Service;
46 import org.oransc.policyagent.repository.Services;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.http.HttpStatus;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.web.bind.annotation.DeleteMapping;
51 import org.springframework.web.bind.annotation.GetMapping;
52 import org.springframework.web.bind.annotation.PutMapping;
53 import org.springframework.web.bind.annotation.RequestBody;
54 import org.springframework.web.bind.annotation.RequestParam;
55 import org.springframework.web.bind.annotation.RestController;
56 import reactor.core.publisher.Mono;
57
58 @RestController
59 @Api(tags = "A1 Policy Management")
60 public class PolicyController {
61
62     @Autowired
63     private Rics rics;
64     @Autowired
65     private PolicyTypes policyTypes;
66     @Autowired
67     private Policies policies;
68     @Autowired
69     private A1ClientFactory a1ClientFactory;
70     @Autowired
71     private Services services;
72
73     private static Gson gson = new GsonBuilder() //
74         .serializeNulls() //
75         .create(); //
76
77     @GetMapping("/policy_schemas")
78     @ApiOperation(value = "Returns policy type schema definitions")
79     @ApiResponses(
80         value = {
81             @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
82             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
83     public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
84         synchronized (this.policyTypes) {
85             if (ricName == null) {
86                 Collection<PolicyType> types = this.policyTypes.getAll();
87                 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
88             } else {
89                 try {
90                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
91                     return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
92                 } catch (ServiceException e) {
93                     return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
94                 }
95             }
96         }
97     }
98
99     @GetMapping("/policy_schema")
100     @ApiOperation(value = "Returns one policy type schema definition")
101     @ApiResponses(
102         value = { //
103             @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
104             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
105     public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
106         try {
107             PolicyType type = policyTypes.getType(id);
108             return new ResponseEntity<>(type.schema(), HttpStatus.OK);
109         } catch (ServiceException e) {
110             return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
111         }
112     }
113
114     @GetMapping("/policy_types")
115     @ApiOperation(value = "Query policy type names")
116     @ApiResponses(
117         value = {
118             @ApiResponse(
119                 code = 200,
120                 message = "Policy type names",
121                 response = String.class,
122                 responseContainer = "List"),
123             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
124     public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
125         synchronized (this.policyTypes) {
126             if (ricName == null) {
127                 Collection<PolicyType> types = this.policyTypes.getAll();
128                 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
129             } else {
130                 try {
131                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
132                     return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
133                 } catch (ServiceException e) {
134                     return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
135                 }
136             }
137         }
138     }
139
140     @GetMapping("/policy")
141     @ApiOperation(value = "Returns a policy configuration") //
142     @ApiResponses(
143         value = { //
144             @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
145             @ApiResponse(code = 404, message = "Policy is not found")} //
146     )
147     public ResponseEntity<String> getPolicy( //
148         @RequestParam(name = "instance", required = true) String instance) {
149         try {
150             Policy p = policies.getPolicy(instance);
151             return new ResponseEntity<>(p.json(), HttpStatus.OK);
152         } catch (ServiceException e) {
153             return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
154         }
155     }
156
157     @DeleteMapping("/policy")
158     @ApiOperation(value = "Delete a policy", response = Object.class)
159     @ApiResponses(
160         value = { //
161             @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
162             @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
163             @ApiResponse(code = 423, message = "RIC is locked", response = String.class)})
164     public Mono<ResponseEntity<Object>> deletePolicy( //
165         @RequestParam(name = "instance", required = true) String id) {
166         Policy policy;
167         try {
168             policy = policies.getPolicy(id);
169             keepServiceAlive(policy.ownerServiceName());
170             if (policy.ric().getState() != Ric.RicState.IDLE) {
171                 return Mono.just(new ResponseEntity<>("Busy, recovering", HttpStatus.LOCKED));
172             }
173             Ric ric = policy.ric();
174             return ric.getLock().lock(LockType.SHARED) // //
175                 .flatMap(lock -> a1ClientFactory.createA1Client(policy.ric())) //
176                 .doOnNext(notUsed -> policies.remove(policy)) //
177                 .flatMap(client -> client.deletePolicy(policy)) //
178                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
179                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
180                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)));
181         } catch (ServiceException e) {
182             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
183         }
184     }
185
186     @PutMapping(path = "/policy")
187     @ApiOperation(value = "Put a policy", response = String.class)
188     @ApiResponses(
189         value = { //
190             @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
191             @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
192             @ApiResponse(code = 423, message = "RIC is locked", response = String.class), //
193             @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class), //
194             @ApiResponse(code = 405, message = "Change is not allowed", response = String.class)})
195     public Mono<ResponseEntity<Object>> putPolicy( //
196         @RequestParam(name = "type", required = true) String typeName, //
197         @RequestParam(name = "instance", required = true) String instanceId, //
198         @RequestParam(name = "ric", required = true) String ricName, //
199         @RequestParam(name = "service", required = true) String service, //
200         @RequestBody Object jsonBody) {
201
202         String jsonString = gson.toJson(jsonBody);
203         Ric ric = rics.get(ricName);
204         PolicyType type = policyTypes.get(typeName);
205         keepServiceAlive(service);
206         if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
207             Policy policy = ImmutablePolicy.builder() //
208                 .id(instanceId) //
209                 .json(jsonString) //
210                 .type(type) //
211                 .ric(ric) //
212                 .ownerServiceName(service) //
213                 .lastModified(getTimeStampUtc()) //
214                 .build();
215
216             final boolean isCreate = this.policies.get(policy.id()) == null;
217
218             return ric.getLock().lock(LockType.SHARED) //
219                 .flatMap(p -> validateModifiedPolicy(policy)) //
220                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
221                 .flatMap(client -> client.putPolicy(policy)) //
222                 .doOnNext(notUsed -> policies.put(policy)) //
223                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
224                 .doOnError(t -> ric.getLock().unlockBlocking()) //
225                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
226                 .onErrorResume(t -> Mono.just(new ResponseEntity<>(t.getMessage(), HttpStatus.METHOD_NOT_ALLOWED)));
227         }
228
229         return ric == null || type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND))
230             : Mono.just(new ResponseEntity<>(HttpStatus.LOCKED)); // Recovering
231     }
232
233     private Mono<Object> validateModifiedPolicy(Policy policy) {
234         // Check that ric is not updated
235         Policy current = this.policies.get(policy.id());
236         if (current != null && !current.ric().name().equals(policy.ric().name())) {
237             return Mono.error(new Exception("Policy cannot change RIC, policyId: " + current.id() + //
238                 ", RIC name: " + current.ric().name() + //
239                 ", new name: " + policy.ric().name()));
240         }
241         return Mono.just("OK");
242     }
243
244     @GetMapping("/policies")
245     @ApiOperation(value = "Query policies")
246     @ApiResponses(
247         value = {
248             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
249             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
250     public ResponseEntity<String> getPolicies( //
251         @RequestParam(name = "type", required = false) String type, //
252         @RequestParam(name = "ric", required = false) String ric, //
253         @RequestParam(name = "service", required = false) String service) //
254     {
255         if ((type != null && this.policyTypes.get(type) == null)) {
256             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
257         }
258         if ((ric != null && this.rics.get(ric) == null)) {
259             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
260         }
261         synchronized (policies) {
262             Collection<Policy> result = null;
263
264             if (type != null) {
265                 result = policies.getForType(type);
266                 result = filter(result, null, ric, service);
267             } else if (service != null) {
268                 result = policies.getForService(service);
269                 result = filter(result, type, ric, null);
270             } else if (ric != null) {
271                 result = filter(policies.getForRic(ric), type, null, service);
272             } else {
273                 result = policies.getAll();
274             }
275
276             String policiesJson;
277             try {
278                 policiesJson = policiesToJson(result);
279             } catch (ServiceException e) {
280                 return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
281             }
282             return new ResponseEntity<>(policiesJson, HttpStatus.OK);
283         }
284     }
285
286     @GetMapping("/policy_status")
287     @ApiOperation(value = "Returns a policy status") //
288     @ApiResponses(
289         value = { //
290             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
291             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
292     )
293     public Mono<ResponseEntity<String>> getPolicyStatus( //
294         @RequestParam(name = "instance", required = true) String instance) {
295         try {
296             Policy policy = policies.getPolicy(instance);
297
298             return a1ClientFactory.createA1Client(policy.ric()) //
299                 .flatMap(client -> client.getPolicyStatus(policy)) //
300                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)));
301         } catch (ServiceException e) {
302             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
303         }
304     }
305
306     private void keepServiceAlive(String name) {
307         Service s = this.services.get(name);
308         if (s != null) {
309             s.keepAlive();
310         }
311     }
312
313     private boolean include(String filter, String value) {
314         return filter == null || value.equals(filter);
315     }
316
317     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
318         if (type == null && ric == null && service == null) {
319             return collection;
320         }
321         List<Policy> filtered = new ArrayList<>();
322         for (Policy p : collection) {
323             if (include(type, p.type().name()) && include(ric, p.ric().name())
324                 && include(service, p.ownerServiceName())) {
325                 filtered.add(p);
326             }
327         }
328         return filtered;
329     }
330
331     private String policiesToJson(Collection<Policy> policies) throws ServiceException {
332         List<PolicyInfo> v = new ArrayList<>(policies.size());
333         for (Policy p : policies) {
334             PolicyInfo policyInfo = new PolicyInfo();
335             policyInfo.id = p.id();
336             policyInfo.json = fromJson(p.json());
337             policyInfo.ric = p.ric().name();
338             policyInfo.type = p.type().name();
339             policyInfo.service = p.ownerServiceName();
340             policyInfo.lastModified = p.lastModified();
341             if (!policyInfo.validate()) {
342                 throw new ServiceException("BUG, all fields must be set");
343             }
344             v.add(policyInfo);
345         }
346         return gson.toJson(v);
347     }
348
349     private Object fromJson(String jsonStr) {
350         return gson.fromJson(jsonStr, Object.class);
351     }
352
353     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
354         StringBuilder result = new StringBuilder();
355         result.append("[");
356         boolean first = true;
357         for (PolicyType t : types) {
358             if (!first) {
359                 result.append(",");
360             }
361             first = false;
362             result.append(t.schema());
363         }
364         result.append("]");
365         return result.toString();
366     }
367
368     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
369         List<String> v = new ArrayList<>(types.size());
370         for (PolicyType t : types) {
371             v.add(t.name());
372         }
373         return gson.toJson(v);
374     }
375
376     private String getTimeStampUtc() {
377         return java.time.Instant.now().toString();
378     }
379
380 }