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