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