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