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