aboutsummaryrefslogtreecommitdiffstats
path: root/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/MicroServiceResource.java
blob: 7ade6fa6003893e40c62df9e89236e83fdb3217a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*******************************************************************************
 * Copyright 2016-2017 ZTE, Inc. and others.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package org.onap.msb.apiroute.resources;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.onap.msb.apiroute.api.DiscoverInfo;
import org.onap.msb.apiroute.api.MicroServiceFullInfo;
import org.onap.msb.apiroute.api.exception.ExtendedInternalServerErrorException;
import org.onap.msb.apiroute.health.ConsulLinkHealthCheck;
import org.onap.msb.apiroute.health.RedisHealthCheck;
import org.onap.msb.apiroute.wrapper.util.ConfigUtil;
import org.onap.msb.apiroute.wrapper.util.HttpClientUtil;
import org.onap.msb.apiroute.wrapper.util.RouteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheck.Result;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Path("/services")
// @Api(tags = {"MSB-Service Resource"})
@Produces(MediaType.APPLICATION_JSON)
public class MicroServiceResource {
    private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceResource.class);

    @Context
    UriInfo uriInfo; // actual uri info

    @GET
    @Path("/")
    @ApiOperation(value = "get all microservices ", code = HttpStatus.SC_OK, response = MicroServiceFullInfo.class,
                    responseContainer = "List")
    @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    message = "get microservice List  fail", response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response getMicroService() {
        String resourceUrl = "/";
        return routeHttpGet2DiscoveryService(resourceUrl);
    }

    @POST
    @Path("/")
    @ApiOperation(value = "add one microservice ", code = HttpStatus.SC_CREATED, response = MicroServiceFullInfo.class)
    @ApiResponses(value = {
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add microservice fail",
                                    response = String.class),
                    @ApiResponse(code = HttpStatus.SC_BAD_REQUEST,
                                    message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response addMicroService(
                    @ApiParam(value = "MicroServiceInfo Instance Info",
                                    required = true) MicroServiceFullInfo microServiceInfo,
                    @Context HttpServletRequest request,
                    @ApiParam(value = "createOrUpdate",
                                    required = false) @QueryParam("createOrUpdate") @DefaultValue("true") boolean createOrUpdate,
                    @ApiParam(value = "port", required = false) @QueryParam("port") @DefaultValue("") String port)
                    throws Exception {
        return routeRegistration2DiscoveryService(microServiceInfo);
    }

    @GET
    @Path("/{serviceName}/version/{version}")
    @ApiOperation(value = "get one microservice ", code = HttpStatus.SC_OK, response = MicroServiceFullInfo.class)
    @ApiResponses(value = {
                    @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found",
                                    response = String.class),
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get microservice fail",
                                    response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response getMicroService(
                    @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName,
                    @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version) {
        String resourceUrl = new StringBuilder("/").append(serviceName).append("/version/").append(version).toString();
        return routeHttpGet2DiscoveryService(resourceUrl);
    }

    @PUT
    @Path("/{serviceName}/version/{version}")
    @ApiOperation(value = "update one microservice by serviceName and version", code = HttpStatus.SC_CREATED,
                    response = MicroServiceFullInfo.class)
    @ApiResponses(value = {
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update microservice fail",
                                    response = String.class),
                    @ApiResponse(code = HttpStatus.SC_BAD_REQUEST,
                                    message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response updateMicroService(
                    @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName,
                    @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version,
                    @ApiParam(value = "microservice Instance Info",
                                    required = true) MicroServiceFullInfo microServiceInfo,
                    @Context HttpServletRequest request) {

        String resourceUrl = new StringBuilder("/").append(serviceName).append("/version/").append(version).toString();
        return routeHttpPut2DiscoveryService(resourceUrl, microServiceInfo);
    }

    @DELETE
    @Path("/{serviceName}/version/{version}/nodes/{ip}/{port}")
    @ApiOperation(value = "delete single node by serviceName and version and node", code = HttpStatus.SC_NO_CONTENT)
    @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete node succeed "),
                    @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "node not found", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete node fail",
                                    response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response deleteNode(
                    @ApiParam(value = "microservice serviceName",
                                    required = true) @PathParam("serviceName") String serviceName,
                    @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"",
                                    required = false) @PathParam("version") @DefaultValue("") String version,
                    @ApiParam(value = "ip") @PathParam("ip") String ip,
                    @ApiParam(value = "port") @PathParam("port") String port) {

        String resourceUrl = new StringBuilder("/").append(serviceName).append("/version/").append(version)
                        .append("/nodes/").append(ip).append("/").append(port).toString();
        return routeHttpDelete2DiscoveryService(resourceUrl);
    }

    @DELETE
    @Path("/{serviceName}/version/{version}")
    @ApiOperation(value = "delete one full microservice by serviceName and version", code = HttpStatus.SC_NO_CONTENT)
    @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete microservice succeed "),
                    @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found",
                                    response = String.class),
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete microservice fail",
                                    response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response deleteMicroService(
                    @ApiParam(value = "microservice serviceName",
                                    required = true) @PathParam("serviceName") String serviceName,
                    @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"",
                                    required = false) @PathParam("version") @DefaultValue("") String version) {
        String resourceUrl = new StringBuilder("/").append(serviceName).append("/version/").append(version).toString();
        return routeHttpDelete2DiscoveryService(resourceUrl);
    }

    @PUT
    @Path("/{serviceName}/version/{version}/status/{status}")
    @ApiOperation(value = "update  microservice status by serviceName and version", code = HttpStatus.SC_CREATED,
                    response = MicroServiceFullInfo.class)
    @ApiResponses(value = {
                    @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY,
                                    message = "Unprocessable MicroServiceInfo Entity ", response = String.class),
                    @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found",
                                    response = String.class),
                    @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail",
                                    response = String.class)})
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response updateServiceStatus(
                    @ApiParam(value = "microservice serviceName",
                                    required = true) @PathParam("serviceName") String serviceName,
                    @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"",
                                    required = false) @PathParam("version") @DefaultValue("") String version,
                    @ApiParam(value = "status,1:abled  0:disabled") @PathParam("status") String status) {
        String resourceUrl = new StringBuilder("/").append(serviceName).append("/version/").append(version)
                        .append("/status/").append(status).toString();
        return this.routeHttpPut2DiscoveryService(resourceUrl);
    }

    /**
     * @param discoveryUrl
     * @return
     */
    private Response routeHttpDelete2DiscoveryService(String resourceUrl) {
        String discoveryServiceUrl = getDiscoveryServiceUrl();
        String fullUrl = new StringBuilder(discoveryServiceUrl).append(resourceUrl).toString();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpDelete httpDelete = new HttpDelete(fullUrl);
            httpResponse = httpClient.execute(httpDelete);
            return cloneHttpResponse(httpResponse);
        } catch (Exception e) {
            throw new ExtendedInternalServerErrorException(e.getMessage());
        } finally {
            HttpClientUtil.closeHttpClient(httpClient, httpResponse);
        }
    }

    /**
     * @param discoveryUrl
     * @return
     */
    private Response routeHttpPut2DiscoveryService(String resourceUrl, Object bean) {
        String discoveryServiceUrl = getDiscoveryServiceUrl();
        String fullUrl = new StringBuilder(discoveryServiceUrl).append(resourceUrl).toString();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPut httpPut = HttpClientUtil.createHttpPut(fullUrl, bean);
            httpClient = HttpClients.createDefault();
            httpResponse = httpClient.execute(httpPut);
            return cloneHttpResponse(httpResponse);
        } catch (Exception e) {
            throw new ExtendedInternalServerErrorException(e.getMessage());
        } finally {
            HttpClientUtil.closeHttpClient(httpClient, httpResponse);
        }
    }

    /**
     * @param discoveryUrl
     * @return
     */
    private Response routeHttpPut2DiscoveryService(String resourceUrl) {
        String discoveryServiceUrl = getDiscoveryServiceUrl();
        String fullUrl = new StringBuilder(discoveryServiceUrl).append(resourceUrl).toString();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPut httpPut = HttpClientUtil.createHttpPut(fullUrl);
            httpClient = HttpClients.createDefault();
            httpResponse = httpClient.execute(httpPut);
            return cloneHttpResponse(httpResponse);
        } catch (Exception e) {
            throw new ExtendedInternalServerErrorException(e.getMessage());
        } finally {
            HttpClientUtil.closeHttpClient(httpClient, httpResponse);
        }
    }

    /**
     * @param discoveryUrl
     * @return
     */
    private Response routeHttpGet2DiscoveryService(String resourceUrl) {
        String discoveryServiceUrl = getDiscoveryServiceUrl();
        String fullUrl = new StringBuilder(discoveryServiceUrl).append(resourceUrl).toString();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpGet httpGet = HttpClientUtil.createHttpGet(fullUrl);
            httpClient = HttpClients.createDefault();
            httpResponse = httpClient.execute(httpGet);
            return cloneHttpResponse(httpResponse);
        } catch (Exception e) {
            throw new ExtendedInternalServerErrorException(e.getMessage());
        } finally {
            HttpClientUtil.closeHttpClient(httpClient, httpResponse);
        }
    }

    /**
     * @param microServiceFullInfo
     * @param registrationUrl
     * @return
     */
    private Response routeRegistration2DiscoveryService(MicroServiceFullInfo microServiceFullInfo) {
        String registrationUrl = getDiscoveryServiceUrl();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost httpPost = HttpClientUtil.createHttpPost(registrationUrl, microServiceFullInfo);
            httpClient = HttpClients.createDefault();
            httpResponse = httpClient.execute(httpPost);
            return cloneHttpResponse(httpResponse);
        } catch (Exception e) {
            throw new ExtendedInternalServerErrorException(e.getMessage());
        } finally {
            HttpClientUtil.closeHttpClient(httpClient, httpResponse);
        }
    }

    /**
     * @param httpResponse
     * @return
     * @throws IOException
     */
    private Response cloneHttpResponse(CloseableHttpResponse httpResponse) throws IOException {
        String jsonString = EntityUtils.toString(httpResponse.getEntity());
        Response response = Response.status(httpResponse.getStatusLine().getStatusCode()).entity(jsonString).build();
        return response;
    }

    /**
     * @return
     */
    private String getDiscoveryServiceUrl() {
        DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo();
        String registrationUrl = new StringBuilder().append("http://").append(discoverInfo)
                        .append(RouteUtil.MSB_ROUTE_URL).toString();
        return registrationUrl;
    }

    // Discovery service doesn't provide this API, so requests to this URL are not routed to
    // discovery service
    @GET
    @Path("/health")
    @ApiOperation(value = "apigateway healthy check ", code = HttpStatus.SC_OK, response = String.class)
    @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "check fail",
                    response = String.class)})
    @Produces(MediaType.TEXT_PLAIN)
    @Timed
    public Response health() {

        // redis
        Result rst = RedisHealthCheck.getResult();
        if (!rst.isHealthy()) {
            LOGGER.warn("health check failed:" + rst.getMessage());
            throw new ExtendedInternalServerErrorException(rst.getMessage());
        }

        // consul
        rst = ConsulLinkHealthCheck.getResult();
        if (!rst.isHealthy()) {
            LOGGER.warn("health check failed:" + rst.getMessage());
            throw new ExtendedInternalServerErrorException(rst.getMessage());
        }

        return Response.ok("apigateway healthy check:ok").build();
    }
}