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