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