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