383e4f7fc0249152d07c6009d0ca66a293ebb437
[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 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.ApiParam;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
31
32 import java.net.MalformedURLException;
33 import java.net.URL;
34 import java.time.Duration;
35 import java.util.ArrayList;
36 import java.util.Collection;
37
38 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
39 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
40 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
41 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
42 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
43 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.http.HttpStatus;
46 import org.springframework.http.MediaType;
47 import org.springframework.http.ResponseEntity;
48 import org.springframework.web.bind.annotation.DeleteMapping;
49 import org.springframework.web.bind.annotation.GetMapping;
50 import org.springframework.web.bind.annotation.PutMapping;
51 import org.springframework.web.bind.annotation.RequestBody;
52 import org.springframework.web.bind.annotation.RequestParam;
53 import org.springframework.web.bind.annotation.RestController;
54
55 @RestController("ServiceControllerV2")
56 @Api(tags = Consts.V2_API_NAME)
57 public class ServiceController {
58
59     private final Services services;
60     private final Policies policies;
61
62     private static Gson gson = new GsonBuilder() //
63         .create(); //
64
65     @Autowired
66     ServiceController(Services services, Policies policies) {
67         this.services = services;
68         this.policies = policies;
69     }
70
71     private static final String GET_SERVICE_DETAILS =
72         "Either information about a registered service with given identity or all registered services are returned.";
73
74     @GetMapping(path = Consts.V2_API_ROOT + "/services", produces = MediaType.APPLICATION_JSON_VALUE)
75     @ApiOperation(value = "Returns service information", notes = GET_SERVICE_DETAILS)
76     @ApiResponses(
77         value = { //
78             @ApiResponse(code = 200, message = "OK", response = ServiceStatusList.class), //
79             @ApiResponse(code = 404, message = "Service is not found", response = ErrorResponse.ErrorInfo.class)})
80     public ResponseEntity<Object> getServices(//
81         @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false, value = "The identity of the service") //
82         @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String name) {
83         if (name != null && this.services.get(name) == null) {
84             return ErrorResponse.create("Service not found", HttpStatus.NOT_FOUND);
85         }
86
87         Collection<ServiceStatus> servicesStatus = new ArrayList<>();
88         for (Service s : this.services.getAll()) {
89             if (name == null || name.equals(s.getName())) {
90                 servicesStatus.add(toServiceStatus(s));
91             }
92         }
93
94         String res = gson.toJson(new ServiceStatusList(servicesStatus));
95         return new ResponseEntity<>(res, HttpStatus.OK);
96     }
97
98     private ServiceStatus toServiceStatus(Service s) {
99         return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(),
100             s.getCallbackUrl());
101     }
102
103     private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo)
104         throws ServiceException, MalformedURLException {
105         if (registrationInfo.serviceId.isEmpty()) {
106             throw new ServiceException("Missing mandatory parameter 'serviceName'");
107         }
108         if (registrationInfo.keepAliveIntervalSeconds < 0) {
109             throw new ServiceException("Keepalive interval shoul be greater or equal to 0");
110         }
111         if (!registrationInfo.callbackUrl.isEmpty()) {
112             new URL(registrationInfo.callbackUrl);
113         }
114     }
115
116     private static final String REGISTER_SERVICE_DETAILS = "Registering a service is needed to:" //
117         + "<ul>" //
118         + "<li>Get callbacks.</li>" //
119         + "<li>Activate supervision of the service. If a service is inactive, its policies will be deleted.</li>"//
120         + "</ul>" //
121     ;
122
123     @ApiOperation(value = "Register a service", notes = REGISTER_SERVICE_DETAILS)
124     @ApiResponses(
125         value = { //
126             @ApiResponse(code = 200, message = "Service updated"),
127             @ApiResponse(code = 201, message = "Service created"), //
128             @ApiResponse(
129                 code = 400,
130                 message = "The ServiceRegistrationInfo is not accepted",
131                 response = ErrorResponse.ErrorInfo.class)})
132     @PutMapping(Consts.V2_API_ROOT + "/services")
133     public ResponseEntity<Object> putService(//
134         @RequestBody ServiceRegistrationInfo registrationInfo) {
135         try {
136             validateRegistrationInfo(registrationInfo);
137             final boolean isCreate = this.services.get(registrationInfo.serviceId) == null;
138             this.services.put(toService(registrationInfo));
139             return new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK);
140         } catch (Exception e) {
141             return ErrorResponse.create(e, HttpStatus.BAD_REQUEST);
142         }
143     }
144
145     @ApiOperation(value = "Unregister a service")
146     @ApiResponses(
147         value = { //
148             @ApiResponse(code = 204, message = "Service unregistered"),
149             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
150             @ApiResponse(code = 404, message = "Service not found", response = ErrorResponse.ErrorInfo.class)})
151     @DeleteMapping(Consts.V2_API_ROOT + "/services")
152     public ResponseEntity<Object> deleteService(//
153         @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The idenitity of the service") //
154         @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) {
155         try {
156             Service service = removeService(serviceName);
157             // Remove the policies from the repo and let the consistency monitoring
158             // do the rest.
159             removePolicies(service);
160             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
161         } catch (ServiceException e) {
162             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
163         }
164     }
165
166     @ApiOperation(value = "Heartbeat indicates that the service is running")
167     @ApiResponses(
168         value = { //
169             @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"), //
170             @ApiResponse(
171                 code = 404,
172                 message = "The service is not found, needs re-registration",
173                 response = ErrorResponse.ErrorInfo.class)})
174
175     @PutMapping(Consts.V2_API_ROOT + "/services/keepalive")
176     public ResponseEntity<Object> keepAliveService(//
177         @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The identity of the service") //
178         @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) {
179         try {
180             services.getService(serviceName).keepAlive();
181             return new ResponseEntity<>(HttpStatus.OK);
182         } catch (ServiceException e) {
183             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
184         }
185     }
186
187     private Service removeService(String name) throws ServiceException {
188         Service service = this.services.getService(name); // Just to verify that it exists
189         this.services.remove(service.getName());
190         return service;
191     }
192
193     private void removePolicies(Service service) {
194         Collection<Policy> policyList = this.policies.getForService(service.getName());
195         for (Policy policy : policyList) {
196             this.policies.remove(policy);
197         }
198     }
199
200     private Service toService(ServiceRegistrationInfo s) {
201         return new Service(s.serviceId, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl);
202     }
203
204 }