2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.aai.config;
22 import com.att.eelf.configuration.EELFLogger;
23 import com.att.eelf.configuration.EELFManager;
24 import com.netflix.client.config.DefaultClientConfigImpl;
25 import com.netflix.client.config.IClientConfig;
26 import com.netflix.loadbalancer.IPing;
27 import com.netflix.loadbalancer.Server;
28 import org.springframework.http.*;
29 import org.springframework.web.client.HttpClientErrorException;
30 import org.springframework.web.client.RestTemplate;
32 import java.io.IOException;
33 import java.net.InetSocketAddress;
34 import java.net.Socket;
35 import java.net.SocketAddress;
36 import java.util.Base64;
37 import java.util.Collections;
39 import java.util.Optional;
41 public class HttpPingImpl implements HttpPing, IPing {
43 private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpPingImpl.class);
45 private static final Base64.Encoder base64Encoder = Base64.getEncoder();
47 private static final HttpHeaders HTTP_HEADERS = new HttpHeaders();
49 // This is a workaround for the topics that the user
50 // does not have the access to read their own topic status
51 private static final String MR_STATUS_PATTERN = ".*\"mrstatus\":\\s*4002.*";
53 private static final int HTTPS_PORT = 3905;
54 private static final int DEFAULT_TIMEOUT = 2;
56 private String healthCheckEndpoint;
57 private String username;
58 private String password;
62 private final RestTemplate restTemplate;
64 public HttpPingImpl(String healthCheckEndpoint) {
65 this(new RestTemplate());
66 this.healthCheckEndpoint = healthCheckEndpoint;
67 this.timeout = DEFAULT_TIMEOUT;
70 public HttpPingImpl(RestTemplate restTemplate) {
71 this.restTemplate = restTemplate;
72 this.healthCheckEndpoint = "";
73 this.timeout = DEFAULT_TIMEOUT;
76 public HttpPingImpl() {
80 public HttpPingImpl(IClientConfig clientConfig) {
82 if (!(clientConfig instanceof DefaultClientConfigImpl)) {
83 throw new UnsupportedOperationException("Unable to support the client config implementation: " + clientConfig.getClass().getName());
86 DefaultClientConfigImpl defaultClientConfig = (DefaultClientConfigImpl) clientConfig;
88 Map<String, Object> map = defaultClientConfig.getProperties();
90 this.setCredentials(map.get("username").toString(), map.get("password").toString());
91 this.setHealthCheckEndpoint(map.get("health.endpoint").toString());
92 this.setTimeoutInSecs(Integer.valueOf(map.get("pingport.timeout").toString()));
94 this.restTemplate = new RestTemplate();
101 public void setHealthCheckEndpoint(String endpoint) {
102 this.healthCheckEndpoint = endpoint;
109 public String getHealthCheckEndpoint() {
110 return healthCheckEndpoint;
114 public void setCredentials(String username, String password) {
115 this.username = username;
116 this.password = password;
119 public void setTimeoutInSecs(int timeout) {
120 this.timeout = timeout;
124 public Optional<String> getAuthorization() {
126 if (username == null && password == null) {
127 return Optional.empty();
130 if (username == null || username.isEmpty()) {
131 logger.error("Username is null while the password is not correctly set");
132 return Optional.empty();
135 if (password == null || password.isEmpty()) {
136 logger.error("Password is null while the username is not correctly set");
137 return Optional.empty();
140 String auth = String.format("%s:%s", username, password);
141 return Optional.ofNullable("Basic " + base64Encoder.encodeToString(auth.getBytes()));
148 public boolean isAlive(Server server) {
152 // If unable to ping the port then return immediately
153 if (!pingPort(server)) {
157 if (server.getPort() == HTTPS_PORT) {
164 url = url + server.getId();
165 url = url + this.getHealthCheckEndpoint();
167 boolean isAlive = false;
169 Optional<String> authorization = getAuthorization();
171 HttpHeaders httpHeaders = new HttpHeaders();
172 httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
174 if (authorization.isPresent()) {
175 httpHeaders.add("Authorization", authorization.get());
178 HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
181 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
183 HttpStatus httpStatus = responseEntity.getStatusCode();
185 if (httpStatus == HttpStatus.OK) {
187 logger.info("Successfully established connection to the following url {}", url);
191 logger.warn("Unable to establish a connection the following url {} due to HTTP Code {}, and reason {}",
192 url, httpStatus.value(), httpStatus.getReasonPhrase());
194 } catch (HttpClientErrorException ex) {
195 HttpStatus httpStatus = ex.getStatusCode();
196 if (httpStatus == HttpStatus.FORBIDDEN) {
197 // This is a workaround being in play for the topics
198 // that are unable to read themselves for this user
199 // In the case of the username and password being
200 // wrong the response would be unauthorized (401) but if the
201 // user is authorized but unable to read this topic, then
202 // we get back the (403) with the message mrstatus 4002
203 // This is a temporary workaround to properly identify which server is down
204 String body = ex.getResponseBodyAsString();
205 if (body.matches(MR_STATUS_PATTERN)) {
207 logger.info("Successfully connected by workaround due to unable to read own topic {}", url);
210 logger.warn("Unable to establish a connection to {} due to {}", server.getHostPort(), ex.getMessage());
213 logger.warn("Unable to establish a connection to {} due to {}", server.getHostPort(), ex.getMessage());
215 } catch (Exception ex) {
216 logger.warn("Unable to establish a connection to {} due to {}", server.getHostPort(), ex.getMessage());
223 * Returns true if it can connect to the host and port within
224 * the given timeout from the given server parameter
226 * @param server - server that will be taken from the src/main/resources/application.yml file
227 * @return true if it can make a successful socket connection to the port on the host
229 public boolean pingPort(Server server) {
231 String host = server.getHost();
232 Integer port = server.getPort();
234 boolean success = false;
235 SocketAddress socketAddress = new InetSocketAddress(host, port);
237 try (Socket socket = new Socket()) {
238 socket.connect(socketAddress, timeout * 1000);
239 if (socket.isConnected()) {
242 } catch (IOException e) {
243 logger.warn("Unable to connect to the host {} on port {} due to {}", host, port, e.getLocalizedMessage());