CSIT Fix for SDC-2585
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / es / ElasticSearchClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.be.dao.es;
22
23 import org.apache.commons.lang.SystemUtils;
24 import org.elasticsearch.client.Client;
25 import org.elasticsearch.client.transport.TransportClient;
26 import org.elasticsearch.common.settings.Settings;
27 import org.elasticsearch.common.transport.InetSocketTransportAddress;
28 import org.elasticsearch.node.Node;
29 import org.elasticsearch.node.NodeBuilder;
30 import org.openecomp.sdc.common.log.wrappers.Logger;
31 import org.springframework.beans.factory.annotation.Value;
32 import org.springframework.stereotype.Component;
33
34 import javax.annotation.PostConstruct;
35 import javax.annotation.PreDestroy;
36 import java.net.InetSocketAddress;
37 import java.net.MalformedURLException;
38 import java.net.URISyntaxException;
39 import java.net.URL;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44
45 /**
46  * Prepare the node to work with elastic search.
47  * 
48  * @author luc boutier
49  */
50 @Component("elasticsearch-client")
51 public class ElasticSearchClient {
52
53         private static Logger log = Logger.getLogger(ElasticSearchClient.class.getName());
54
55         private Node node;
56         private boolean isLocal;
57         private String clusterName;
58         private Client client;
59
60         String serverHost;
61         String serverPort;
62
63         ArrayList<String> nodes = new ArrayList<>();
64
65         private boolean isTransportClient;
66
67         @PostConstruct
68         public void initialize() throws URISyntaxException {
69
70                 URL url = null;
71                 Settings settings = null;
72                 URL systemResourceElasticsearchPath = ClassLoader.getSystemResource("elasticsearch.yml");
73
74                 if (systemResourceElasticsearchPath != null) {
75                         log.debug("try to create URI for {}", systemResourceElasticsearchPath.toString());
76                         Path classpathConfig = Paths.get(systemResourceElasticsearchPath.toURI());
77                         settings = Settings.settingsBuilder().loadFromPath(classpathConfig).build();
78                 }
79                 String configHome = System.getProperty("config.home");
80                 if (configHome != null && !configHome.isEmpty()) {
81                         try {
82                                 if (SystemUtils.IS_OS_WINDOWS) {
83                                         url = new URL("file:///" + configHome + "/elasticsearch.yml");
84                                 } else {
85                                         url = new URL("file:" + configHome + "/elasticsearch.yml");
86                                 }
87
88                                 log.debug("URL {}", url);
89                                 settings = Settings.settingsBuilder().loadFromPath(Paths.get(url.toURI())).build();
90                         } catch (MalformedURLException | URISyntaxException e1) {
91                                 log.error("Failed to create URL in order to load elasticsearch yml");
92                                 System.err.println("Failed to create URL in order to load elasticsearch yml from " + configHome);
93                         }
94                 }
95                 if (settings == null) {
96                         log.error("Failed to find settings of elasticsearch yml");
97                         System.err.println("Failed to create URL in order to load elasticsearch yml from " + configHome);
98                 }
99                 if (isTransportClient()) {
100                         log.info("******* ElasticSearchClient type is Transport Client *****");
101                         TransportClient transportClient = TransportClient.builder().settings(settings)
102                                         .build();
103
104                         String[] nodesArray = transportClient.settings().getAsArray("transport.client.initial_nodes");
105                         for (String host : nodesArray) {
106                                 int port = 9300;
107
108                                 // or parse it from the host string...
109                                 String[] splitHost = host.split(":", 2);
110                                 if (splitHost.length == 2) {
111                                         host = splitHost[0];
112                                         port = Integer.parseInt(splitHost[1]);
113                                 }
114
115                                 transportClient.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(host, port)));
116
117                         }
118                         this.client = transportClient;
119                         serverHost = Arrays.toString(nodesArray);
120
121                 } else {
122                         log.info("******* ElasticSearchClient type is Node Client *****");
123                         this.node = NodeBuilder.nodeBuilder().settings(settings).client(!isLocal).clusterName(this.clusterName)
124                                         .local(isLocal).node();
125                         this.client = node.client();
126
127                         serverHost = this.client.settings().get("discovery.zen.ping.unicast.hosts");
128                         if (serverHost == null) {
129                                 serverHost = "['localhost:9200']";
130                         }
131
132                 }
133
134                 serverPort = this.client.settings().get("http.port");
135                 if (serverPort == null) {
136                         serverPort = "9200";
137                 }
138
139                 log.info("Initialized ElasticSearch client for cluster <{}> with nodes: {}", this.clusterName, serverHost);
140         }
141
142         @PreDestroy
143         public void close() {
144                 if (client != null) {
145                         client.close();
146                 }
147                 if (node != null) {
148                         node.close();
149                 }
150                 log.info("Closed ElasticSearch client for cluster <{}>", this.clusterName);
151         }
152
153         /**
154          * Get the elastic search client.
155          * 
156          * @return The elastic search client.
157          */
158         public Client getClient() {
159                 return this.client;
160         }
161
162         public String getServerHost() {
163                 return serverHost;
164         }
165
166         public String getServerPort() {
167                 return serverPort;
168         }
169
170         @Value("#{elasticsearchConfig['cluster.name']}")
171         public void setClusterName(final String clusterName) {
172                 this.clusterName = clusterName;
173         }
174
175         @Value("#{elasticsearchConfig['elasticSearch.local']}")
176         public void setLocal(final String strIsLocal) {
177                 if (strIsLocal != null && !strIsLocal.isEmpty())
178                         this.isLocal = Boolean.parseBoolean(strIsLocal);
179         }
180
181         public boolean isTransportClient() {
182                 return isTransportClient;
183         }
184
185         @Value("#{elasticsearchConfig['elasticSearch.transportclient']}")
186         public void setTransportClient(final String strIsTransportclient) {
187                 if (strIsTransportclient != null && !strIsTransportclient.isEmpty())
188                         this.isTransportClient = Boolean.parseBoolean(strIsTransportclient);
189         }
190
191 }