Initial fix for https call to plugins
[sdc.git] / catalog-fe / src / main / java / org / openecomp / sdc / fe / impl / PluginStatusBL.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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
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.openecomp.sdc.fe.impl;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import org.apache.http.HttpStatus;
26 import org.apache.http.client.config.RequestConfig;
27 import org.apache.http.client.methods.CloseableHttpResponse;
28 import org.apache.http.client.methods.HttpHead;
29 import org.apache.http.config.Registry;
30 import org.apache.http.config.RegistryBuilder;
31 import org.apache.http.conn.socket.ConnectionSocketFactory;
32 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
33 import org.apache.http.conn.ssl.NoopHostnameVerifier;
34 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
35 import org.apache.http.impl.client.CloseableHttpClient;
36 import org.apache.http.impl.client.HttpClients;
37 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
38
39 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import org.openecomp.sdc.exception.InvalidArgumentException;
41 import org.openecomp.sdc.fe.config.ConfigurationManager;
42 import org.openecomp.sdc.fe.config.PluginsConfiguration;
43 import org.openecomp.sdc.fe.config.PluginsConfiguration.Plugin;
44 import org.openecomp.sdc.fe.utils.JettySSLUtils;
45
46 import java.io.IOException;
47 import java.security.GeneralSecurityException;
48
49 public class PluginStatusBL {
50
51     private static final Logger log = Logger.getLogger(PluginStatusBL.class.getName());
52         private static final String MAX_CONNECTION_POOL = "maxOutgoingConnectionPoolTotal";
53         private static final String MAX_ROUTE_POOL = "maxOutgoingPerRoute";
54     private final Gson gson;
55     private CloseableHttpClient client;
56     private final PluginsConfiguration pluginsConfiguration;
57     private RequestConfig requestConfig;
58
59     public PluginStatusBL() {
60         this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration();
61         this.gson = new GsonBuilder().setPrettyPrinting().create();
62                 // check if we have secure connections in the plugin list, if not - we won't bother with it
63                 try {
64                         this.client = getPooledClient(this.hasSecuredPlugins());
65                 } catch (Exception e){
66                         log.error("Could not initialize the Https client: {}", e.getMessage());
67                         log.debug("Exception:",e);
68                 }
69     }
70
71     public PluginStatusBL(CloseableHttpClient client) {
72         this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration();
73         this.client = client;
74
75         this.gson = new GsonBuilder().setPrettyPrinting().create();
76
77     }
78
79         private boolean hasSecuredPlugins() {
80                 if (this.getPluginsList() != null) {
81             return pluginsConfiguration.getPluginsList().stream()
82                     .anyMatch(plugin -> plugin.getPluginDiscoveryUrl().toLowerCase().startsWith("https"));
83                 }
84                 return false;
85
86         }
87
88         private CloseableHttpClient getPooledClient(boolean isSecured) throws GeneralSecurityException, IOException {
89                 final PoolingHttpClientConnectionManager  poolingConnManager;
90                 if (!isSecured) {
91                         poolingConnManager
92                                         = new PoolingHttpClientConnectionManager();
93                 } else {
94                         SSLConnectionSocketFactory s = new SSLConnectionSocketFactory(
95                     JettySSLUtils.getSslContext(),
96                                         new NoopHostnameVerifier());
97
98                         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
99                                         .register("http", new PlainConnectionSocketFactory())
100                                         .register("https", s)
101                                         .build();
102                         poolingConnManager
103                                         = new PoolingHttpClientConnectionManager(registry);
104                 }
105                 int maxTotal = System.getProperties().containsKey(MAX_CONNECTION_POOL) ? Integer.parseInt(System.getProperty(MAX_CONNECTION_POOL)) : 5;
106                 int routeMax = System.getProperties().containsKey(MAX_ROUTE_POOL) ? Integer.parseInt(System.getProperty(MAX_ROUTE_POOL)) : 20;
107                 poolingConnManager.setMaxTotal(maxTotal);
108                 poolingConnManager.setDefaultMaxPerRoute(routeMax);
109                 return HttpClients.custom().setConnectionManager(poolingConnManager).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
110         }
111
112     public String getPluginsList() {
113         String result = null;
114
115         if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) {
116             log.warn("Configuration of type {} was not found", PluginsConfiguration.class);
117             throw new InvalidArgumentException("the plugin configuration was not read successfully.");
118
119         } else {
120             log.debug("The value returned from getConfig is {}", pluginsConfiguration);
121
122             result = gson.toJson(pluginsConfiguration.getPluginsList());
123         }
124         return result;
125     }
126
127     public String getPluginAvailability(String pluginId) {
128         String result = null;
129
130         if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) {
131             log.warn("Configuration of type {} was not found", PluginsConfiguration.class);
132             throw new InvalidArgumentException("the plugin configuration was not read successfully.");
133
134         } else {
135             log.debug("The value returned from getConfig is {}", pluginsConfiguration);
136             Integer connectionTimeout = pluginsConfiguration.getConnectionTimeout();
137             this.requestConfig = RequestConfig.custom()
138                     .setSocketTimeout(connectionTimeout)
139                     .setConnectTimeout(connectionTimeout)
140                     .setConnectionRequestTimeout(connectionTimeout).build();
141
142
143             Plugin wantedPlugin = pluginsConfiguration.getPluginsList().stream()
144                     .filter(plugin -> plugin.getPluginId().equals(pluginId))
145                     .findAny()
146                     .orElse(null);
147
148             if (wantedPlugin != null) {
149                 result = gson.toJson(checkPluginAvailability(wantedPlugin));
150             }
151         }
152         return result;
153     }
154
155     private boolean checkPluginAvailability(Plugin plugin) {
156         boolean result = false;
157         log.debug("sending head request to id:{} url:{}", plugin.getPluginId(), plugin.getPluginDiscoveryUrl());
158         HttpHead head = new HttpHead(plugin.getPluginDiscoveryUrl());
159
160         head.setConfig(this.requestConfig);
161                 if (this.client == null) {
162                         log.debug("The plugin {} will not run because https is not configured on the FE server",plugin.getPluginId());
163                         return false;
164                 }
165         try (CloseableHttpResponse response = this.client.execute(head)) {
166             result = response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
167             log.debug("The plugin {} is {} with result {}", plugin.getPluginId(), (result ? "online" : "offline"), result);
168         } catch (IOException e) {
169             log.debug("The plugin {} is offline", plugin.getPluginId());
170             log.debug("Exception:", e);
171         }
172
173         return result;
174     }
175
176 }