4bf543ed0048df4672bc3617d4eabd3bf3a797d3
[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.lang.invoke.MethodHandles;
35 import java.net.MalformedURLException;
36 import java.net.URL;
37 import java.time.Duration;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Map;
41
42 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
43 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
44 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
45 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
46 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
47 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.http.MediaType;
53 import org.springframework.http.ResponseEntity;
54 import org.springframework.web.bind.annotation.DeleteMapping;
55 import org.springframework.web.bind.annotation.GetMapping;
56 import org.springframework.web.bind.annotation.PathVariable;
57 import org.springframework.web.bind.annotation.PutMapping;
58 import org.springframework.web.bind.annotation.RequestBody;
59 import org.springframework.web.bind.annotation.RequestHeader;
60 import org.springframework.web.bind.annotation.RequestParam;
61 import org.springframework.web.bind.annotation.RestController;
62
63 @RestController("ServiceControllerV2")
64 @Tag( //
65         name = ServiceController.API_NAME, //
66         description = ServiceController.API_DESCRIPTION //
67
68 )
69 public class ServiceController {
70
71     public static final String API_NAME = "Service Registry and Supervision";
72     public static final String API_DESCRIPTION = "";
73
74     private final Services services;
75     private final Policies policies;
76
77     private static Gson gson = new GsonBuilder().create();
78
79     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
80
81     @Autowired
82     private PolicyController policyController;
83
84     ServiceController(Services services, Policies policies) {
85         this.services = services;
86         this.policies = policies;
87     }
88
89     private static final String GET_SERVICE_DETAILS =
90             "Either information about a registered service with given identity or all registered services are returned.";
91
92     @GetMapping(path = Consts.V2_API_ROOT + "/services", produces = MediaType.APPLICATION_JSON_VALUE) //
93     @Operation(summary = "Returns service information", description = GET_SERVICE_DETAILS) //
94     @ApiResponses(value = { //
95             @ApiResponse(responseCode = "200", //
96                     description = "OK", //
97                     content = @Content(schema = @Schema(implementation = ServiceStatusList.class))), //
98             @ApiResponse(responseCode = "404", //
99                     description = "Service is not found", //
100                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
101     })
102     public ResponseEntity<Object> getServices(//
103             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, description = "The identity of the service") //
104             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String name) {
105         if (name != null && this.services.get(name) == null) {
106             return ErrorResponse.create("Service not found", HttpStatus.NOT_FOUND);
107         }
108
109         Collection<ServiceStatus> servicesStatus = new ArrayList<>();
110         for (Service s : this.services.getAll()) {
111             if (name == null || name.equals(s.getName())) {
112                 servicesStatus.add(toServiceStatus(s));
113             }
114         }
115
116         String res = gson.toJson(new ServiceStatusList(servicesStatus));
117         return new ResponseEntity<>(res, HttpStatus.OK);
118     }
119
120     private ServiceStatus toServiceStatus(Service s) {
121         return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(),
122                 s.getCallbackUrl());
123     }
124
125     private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo)
126             throws ServiceException, MalformedURLException {
127         if (registrationInfo.serviceId.isEmpty()) {
128             throw new ServiceException("Missing mandatory parameter 'service-id'");
129         }
130         if (registrationInfo.keepAliveIntervalSeconds < 0) {
131             throw new ServiceException("Keepalive interval shoul be greater or equal to 0");
132         }
133         if (!registrationInfo.callbackUrl.isEmpty()) {
134             new URL(registrationInfo.callbackUrl);
135         }
136     }
137
138     private static final String REGISTER_SERVICE_DETAILS = "Registering a service is needed to:" //
139             + "<ul>" //
140             + "<li>Get callbacks about available NearRT RICs.</li>" //
141             + "<li>Activate supervision of the service. If a service is inactive, its policies will automatically be deleted.</li>"//
142             + "</ul>" //
143             + "Policies can be created even if the service is not registerred. This is a feature which it is optional to use.";
144
145     @PutMapping(Consts.V2_API_ROOT + "/services")
146     @Operation(summary = "Register a service", description = REGISTER_SERVICE_DETAILS)
147     @ApiResponses(value = { //
148             @ApiResponse(responseCode = "200", description = "Service updated"),
149             @ApiResponse(responseCode = "201", description = "Service created"), //
150             @ApiResponse(responseCode = "400", //
151                     description = "The ServiceRegistrationInfo is not accepted", //
152                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))})
153
154     public ResponseEntity<Object> putService(//
155             @RequestBody ServiceRegistrationInfo registrationInfo) {
156         try {
157             validateRegistrationInfo(registrationInfo);
158             final boolean isCreate = this.services.get(registrationInfo.serviceId) == null;
159             this.services.put(toService(registrationInfo));
160             return new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK);
161         } catch (Exception e) {
162             return ErrorResponse.create(e, HttpStatus.BAD_REQUEST);
163         }
164     }
165
166     @DeleteMapping(Consts.V2_API_ROOT + "/services/{service_id:.+}")
167     @Operation(summary = "Unregister a service")
168     @ApiResponses(value = { //
169             @ApiResponse(responseCode = "204", description = "Service unregistered"),
170             @ApiResponse(responseCode = "200", description = "Not used", //
171                     content = @Content(schema = @Schema(implementation = VoidResponse.class))),
172             @ApiResponse(responseCode = "404", description = "Service not found", //
173                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))
174
175     })
176     public ResponseEntity<Object> deleteService(//
177             @PathVariable("service_id") String serviceId, @RequestHeader Map<String, String> headers) {
178         try {
179             Service service = removeService(serviceId);
180             removePolicies(service, headers);
181             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
182         } catch (ServiceException | NullPointerException e) {
183             logger.warn("Exception caught during service deletion while deleting service {}: {}", serviceId, e.getMessage());
184             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
185         }
186     }
187
188     @Operation(summary = "Heartbeat indicates that the service is running",
189             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)")
190     @ApiResponses(value = { //
191             @ApiResponse(responseCode = "200", description = "Service supervision timer refreshed, OK"), //
192             @ApiResponse(responseCode = "404", description = "The service is not found, needs re-registration",
193                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))
194
195     })
196
197     @PutMapping(Consts.V2_API_ROOT + "/services/{service_id}/keepalive")
198     public ResponseEntity<Object> keepAliveService(//
199             @PathVariable(Consts.SERVICE_ID_PARAM) String serviceId) {
200         try {
201             services.getService(serviceId).keepAlive();
202             return new ResponseEntity<>(HttpStatus.OK);
203         } catch (ServiceException e) {
204             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
205         }
206     }
207
208     private Service removeService(String name) throws ServiceException {
209         Service service = this.services.getService(name); // Just to verify that it exists
210         logger.trace("Service name to be deleted: {}", service.getName());
211         this.services.remove(service.getName());
212         return service;
213     }
214
215     private void removePolicies(Service service, Map<String, String> headers) {
216         Collection<Policy> policyList = this.policies.getForService(service.getName());
217         logger.trace("Policies to be deleted: {}", policyList);
218         for (Policy policy : policyList) {
219             try {
220                 policyController.deletePolicy(policy.getId(), headers).doOnNext(resp -> {
221                     if (resp.getStatusCode().is2xxSuccessful()) {
222                         logger.trace("Deleting Policy '{}' when deleting Service '{}'", policy.getId(),
223                                 service.getName());
224                     } else {
225                         logger.warn("Possible problem deleting Policy '{}' when deleting Service '{}'. Continuing, "
226                                 + "but might trigger a re-sync with affected ric '{}'. Repsonse: \"{}\"",
227                                 policy.getId(), service.getName(), policy.getRic().getConfig().getRicId(),
228                                 resp.toString());
229                     }
230                 }).subscribe();
231             } catch (Exception e) {
232                 logger.warn("Problem deleting Policy '{}' when deleting Service '{}'."
233                         + " Continuing, but might trigger a re-sync with affected ric '{}'. Problem: \"{}\"",
234                         policy.getId(), service.getName(), policy.getRic().getConfig().getRicId(), e.getMessage());
235             }
236         }
237     }
238
239     private Service toService(ServiceRegistrationInfo s) {
240         return new Service(s.serviceId, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl);
241     }
242
243 }