578e5c80d29d82d2a5b68a6c5c51d01562a6f0ba
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / controllers / ServiceController.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.time.Duration;
32 import java.util.ArrayList;
33 import java.util.Collection;
34
35 import org.oransc.policyagent.exceptions.ServiceException;
36 import org.oransc.policyagent.repository.Policies;
37 import org.oransc.policyagent.repository.Policy;
38 import org.oransc.policyagent.repository.Service;
39 import org.oransc.policyagent.repository.Services;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.http.HttpStatus;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.web.bind.annotation.DeleteMapping;
44 import org.springframework.web.bind.annotation.GetMapping;
45 import org.springframework.web.bind.annotation.PostMapping;
46 import org.springframework.web.bind.annotation.PutMapping;
47 import org.springframework.web.bind.annotation.RequestBody;
48 import org.springframework.web.bind.annotation.RequestParam;
49 import org.springframework.web.bind.annotation.RestController;
50
51 @RestController
52 @Api(tags = "Service registry and supervision")
53 public class ServiceController {
54
55     private final Services services;
56     private final Policies policies;
57
58     private static Gson gson = new GsonBuilder() //
59         .create(); //
60
61     @Autowired
62     ServiceController(Services services, Policies policies) {
63         this.services = services;
64         this.policies = policies;
65     }
66
67     @GetMapping("/services")
68     @ApiOperation(value = "Returns service information")
69     @ApiResponses(
70         value = { //
71             @ApiResponse(code = 200, message = "OK", response = ServiceStatus.class, responseContainer = "List"), //
72             @ApiResponse(code = 404, message = "Service is not found", response = String.class)})
73     public ResponseEntity<String> getServices(//
74         @RequestParam(name = "name", required = false) String name) {
75
76         if (name != null && this.services.get(name) == null) {
77             return new ResponseEntity<>("Service not found", HttpStatus.NOT_FOUND);
78         }
79
80         Collection<ServiceStatus> servicesStatus = new ArrayList<>();
81         for (Service s : this.services.getAll()) {
82             if (name == null || name.equals(s.getName())) {
83                 servicesStatus.add(toServiceStatus(s));
84             }
85         }
86
87         String res = gson.toJson(servicesStatus);
88         return new ResponseEntity<>(res, HttpStatus.OK);
89     }
90
91     private ServiceStatus toServiceStatus(Service s) {
92         return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(),
93             s.getCallbackUrl());
94     }
95
96     private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo) throws ServiceException {
97         if (registrationInfo.serviceName.isEmpty()) {
98             throw new ServiceException("Missing mandatory parameter 'serviceName'");
99         }
100     }
101
102     @ApiOperation(value = "Register a service")
103     @ApiResponses(
104         value = { //
105             @ApiResponse(code = 200, message = "Service updated", response = String.class),
106             @ApiResponse(code = 201, message = "Service created", response = String.class), //
107             @ApiResponse(code = 400, message = "Cannot parse the ServiceRegistrationInfo", response = String.class)})
108     @PutMapping("/service")
109     public ResponseEntity<String> putService(//
110         @RequestBody ServiceRegistrationInfo registrationInfo) {
111         try {
112             validateRegistrationInfo(registrationInfo);
113             final boolean isCreate = this.services.get(registrationInfo.serviceName) == null;
114             this.services.put(toService(registrationInfo));
115             return new ResponseEntity<>("OK", isCreate ? HttpStatus.CREATED : HttpStatus.OK);
116         } catch (Exception e) {
117             return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
118         }
119     }
120
121     @ApiOperation(value = "Delete a service")
122     @ApiResponses(
123         value = { //
124             @ApiResponse(code = 204, message = "OK"),
125             @ApiResponse(code = 404, message = "Service not found", response = String.class)})
126     @DeleteMapping("/services")
127     public ResponseEntity<String> deleteService(//
128         @RequestParam(name = "name", required = true) String serviceName) {
129         try {
130             Service service = removeService(serviceName);
131             // Remove the policies from the repo and let the consistency monitoring
132             // do the rest.
133             removePolicies(service);
134             return new ResponseEntity<>("OK", HttpStatus.NO_CONTENT);
135         } catch (Exception e) {
136             return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
137         }
138     }
139
140     @ApiOperation(value = "Heartbeat from a serice")
141     @ApiResponses(
142         value = { //
143             @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"),
144             @ApiResponse(code = 404, message = "The service is not found, needs re-registration")})
145     @PostMapping("/services/keepalive")
146     public ResponseEntity<String> keepAliveService(//
147         @RequestParam(name = "name", required = true) String serviceName) {
148         try {
149             services.getService(serviceName).keepAlive();
150             return new ResponseEntity<>("OK", HttpStatus.OK);
151         } catch (ServiceException e) {
152             return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
153         }
154     }
155
156     private Service removeService(String name) throws ServiceException {
157         Service service = this.services.getService(name); // Just to verify that it exists
158         this.services.remove(service.getName());
159         return service;
160     }
161
162     private void removePolicies(Service service) {
163         Collection<Policy> policyList = this.policies.getForService(service.getName());
164         for (Policy policy : policyList) {
165             this.policies.remove(policy);
166         }
167     }
168
169     private Service toService(ServiceRegistrationInfo s) {
170         return new Service(s.serviceName, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl);
171     }
172
173 }