73e421be54587a66db9202167c977b9535d0aad3
[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(value = { //
77             @ApiResponse(code = 200, message = "OK", response = ServiceStatusList.class), //
78             @ApiResponse(code = 404, message = "Service is not found", response = ErrorResponse.ErrorInfo.class)})
79     public ResponseEntity<Object> getServices(//
80             @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false, value = "The identity of the service") //
81             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String name) {
82         if (name != null && this.services.get(name) == null) {
83             return ErrorResponse.create("Service not found", HttpStatus.NOT_FOUND);
84         }
85
86         Collection<ServiceStatus> servicesStatus = new ArrayList<>();
87         for (Service s : this.services.getAll()) {
88             if (name == null || name.equals(s.getName())) {
89                 servicesStatus.add(toServiceStatus(s));
90             }
91         }
92
93         String res = gson.toJson(new ServiceStatusList(servicesStatus));
94         return new ResponseEntity<>(res, HttpStatus.OK);
95     }
96
97     private ServiceStatus toServiceStatus(Service s) {
98         return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(),
99                 s.getCallbackUrl());
100     }
101
102     private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo)
103             throws ServiceException, MalformedURLException {
104         if (registrationInfo.serviceId.isEmpty()) {
105             throw new ServiceException("Missing mandatory parameter 'serviceName'");
106         }
107         if (registrationInfo.keepAliveIntervalSeconds < 0) {
108             throw new ServiceException("Keepalive interval shoul be greater or equal to 0");
109         }
110         if (!registrationInfo.callbackUrl.isEmpty()) {
111             new URL(registrationInfo.callbackUrl);
112         }
113     }
114
115     private static final String REGISTER_SERVICE_DETAILS = "Registering a service is needed to:" //
116             + "<ul>" //
117             + "<li>Get callbacks.</li>" //
118             + "<li>Activate supervision of the service. If a service is inactive, its policies will be deleted.</li>"//
119             + "</ul>" //
120     ;
121
122     @ApiOperation(value = "Register a service", notes = REGISTER_SERVICE_DETAILS)
123     @ApiResponses(value = { //
124             @ApiResponse(code = 200, message = "Service updated"),
125             @ApiResponse(code = 201, message = "Service created"), //
126             @ApiResponse(code = 400, message = "The ServiceRegistrationInfo is not accepted",
127                     response = ErrorResponse.ErrorInfo.class)})
128     @PutMapping(Consts.V2_API_ROOT + "/services")
129     public ResponseEntity<Object> putService(//
130             @RequestBody ServiceRegistrationInfo registrationInfo) {
131         try {
132             validateRegistrationInfo(registrationInfo);
133             final boolean isCreate = this.services.get(registrationInfo.serviceId) == null;
134             this.services.put(toService(registrationInfo));
135             return new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK);
136         } catch (Exception e) {
137             return ErrorResponse.create(e, HttpStatus.BAD_REQUEST);
138         }
139     }
140
141     @ApiOperation(value = "Unregister a service")
142     @ApiResponses(value = { //
143             @ApiResponse(code = 204, message = "Service unregistered"),
144             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
145             @ApiResponse(code = 404, message = "Service not found", response = ErrorResponse.ErrorInfo.class)})
146     @DeleteMapping(Consts.V2_API_ROOT + "/services")
147     public ResponseEntity<Object> deleteService(//
148             @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The idenitity of the service") //
149             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) {
150         try {
151             Service service = removeService(serviceName);
152             // Remove the policies from the repo and let the consistency monitoring
153             // do the rest.
154             removePolicies(service);
155             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
156         } catch (ServiceException e) {
157             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
158         }
159     }
160
161     @ApiOperation(value = "Heartbeat indicates that the service is running")
162     @ApiResponses(value = { //
163             @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"), //
164             @ApiResponse(code = 404, message = "The service is not found, needs re-registration",
165                     response = ErrorResponse.ErrorInfo.class)})
166
167     @PutMapping(Consts.V2_API_ROOT + "/services/keepalive")
168     public ResponseEntity<Object> keepAliveService(//
169             @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The identity of the service") //
170             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) {
171         try {
172             services.getService(serviceName).keepAlive();
173             return new ResponseEntity<>(HttpStatus.OK);
174         } catch (ServiceException e) {
175             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
176         }
177     }
178
179     private Service removeService(String name) throws ServiceException {
180         Service service = this.services.getService(name); // Just to verify that it exists
181         this.services.remove(service.getName());
182         return service;
183     }
184
185     private void removePolicies(Service service) {
186         Collection<Policy> policyList = this.policies.getForService(service.getName());
187         for (Policy policy : policyList) {
188             this.policies.remove(policy);
189         }
190     }
191
192     private Service toService(ServiceRegistrationInfo s) {
193         return new Service(s.serviceId, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl);
194     }
195
196 }