ElasticSearchClient.java 11.8 KB
Newer Older
彭勇升 pengys 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.skywalking.oap.server.library.client.elasticsearch;

21 22 23
import java.io.IOException;
import java.util.*;
import java.util.function.BiConsumer;
彭勇升 pengys 已提交
24
import org.apache.commons.lang3.StringUtils;
25
import org.apache.http.HttpHost;
26
import org.apache.http.auth.*;
27 28
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
彭勇升 pengys 已提交
29
import org.apache.skywalking.oap.server.library.client.Client;
30
import org.elasticsearch.action.ActionListener;
31
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
32 33 34 35
import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest;
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.get.*;
彭勇升 pengys 已提交
36
import org.elasticsearch.action.index.IndexRequest;
37
import org.elasticsearch.action.search.*;
38
import org.elasticsearch.action.support.WriteRequest;
39
import org.elasticsearch.action.support.master.AcknowledgedResponse;
彭勇升 pengys 已提交
40
import org.elasticsearch.action.update.UpdateRequest;
41 42
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.*;
彭勇升 pengys 已提交
43
import org.elasticsearch.common.settings.Settings;
44
import org.elasticsearch.common.unit.*;
彭勇升 pengys 已提交
45
import org.elasticsearch.common.xcontent.XContentBuilder;
46 47
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.*;
彭勇升 pengys 已提交
48
import org.elasticsearch.search.builder.SearchSourceBuilder;
49
import org.slf4j.*;
彭勇升 pengys 已提交
50 51 52 53 54 55 56 57 58 59

/**
 * @author peng-yongsheng
 */
public class ElasticSearchClient implements Client {

    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchClient.class);

    private static final String TYPE = "type";
    private final String clusterNodes;
60
    private final String namespace;
61 62
    private final String user;
    private final String password;
彭勇升 pengys 已提交
63 64
    private RestHighLevelClient client;

65
    public ElasticSearchClient(String clusterNodes, String namespace, String user, String password) {
彭勇升 pengys 已提交
66 67
        this.clusterNodes = clusterNodes;
        this.namespace = namespace;
68 69
        this.user = user;
        this.password = password;
彭勇升 pengys 已提交
70 71
    }

72
    @Override public void connect() {
彭勇升 pengys 已提交
73
        List<HttpHost> pairsList = parseClusterNodes(clusterNodes);
74 75 76 77 78
        RestClientBuilder builder;
        if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            builder = RestClient.builder(pairsList.toArray(new HttpHost[0]))
79
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
80 81 82 83
        } else {
            builder = RestClient.builder(pairsList.toArray(new HttpHost[0]));
        }
        client = new RestHighLevelClient(builder);
彭勇升 pengys 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    }

    @Override public void shutdown() {
        try {
            client.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    private List<HttpHost> parseClusterNodes(String nodes) {
        List<HttpHost> httpHosts = new LinkedList<>();
        logger.info("elasticsearch cluster nodes: {}", nodes);
        String[] nodesSplit = nodes.split(",");
        for (String node : nodesSplit) {
            String host = node.split(":")[0];
            String port = node.split(":")[1];
            httpHosts.add(new HttpHost(host, Integer.valueOf(port)));
        }

        return httpHosts;
    }

    public boolean createIndex(String indexName, Settings settings,
        XContentBuilder mappingBuilder) throws IOException {
        indexName = formatIndexName(indexName);
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.settings(settings);
112 113
        request.mapping(mappingBuilder);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
114
        logger.debug("create {} index finished, isAcknowledged: {}", indexName, response.isAcknowledged());
彭勇升 pengys 已提交
115 116 117 118 119 120
        return response.isAcknowledged();
    }

    public boolean deleteIndex(String indexName) throws IOException {
        indexName = formatIndexName(indexName);
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
121
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
122
        logger.debug("delete {} index finished, isAcknowledged: {}", indexName, response.isAcknowledged());
彭勇升 pengys 已提交
123 124 125 126 127
        return response.isAcknowledged();
    }

    public boolean isExistsIndex(String indexName) throws IOException {
        indexName = formatIndexName(indexName);
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        GetIndexRequest request = new GetIndexRequest(indexName);
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }

    public boolean isExistsTemplate(String indexName) throws IOException {
        indexName = formatIndexName(indexName);
        IndexTemplatesExistRequest request = new IndexTemplatesExistRequest(indexName);
        return client.indices().existsTemplate(request, RequestOptions.DEFAULT);
    }

    public boolean createTemplate(String indexName, Settings settings,
        XContentBuilder mappingBuilder) throws IOException {
        indexName = formatIndexName(indexName);

        org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest request = new PutIndexTemplateRequest(indexName);
        request.patterns(Collections.singletonList(indexName + "*"));
        request.settings(settings);
        request.mapping("_doc", mappingBuilder);

        AcknowledgedResponse response = client.indices().putTemplate(request, RequestOptions.DEFAULT);
        logger.debug("create {} template finished, isAcknowledged: {}", indexName, response.isAcknowledged());
        return response.isAcknowledged();
    }

    public boolean deleteTemplate(String indexName) throws IOException {
        indexName = formatIndexName(indexName);

        DeleteIndexTemplateRequest request = new DeleteIndexTemplateRequest();
        request.name(indexName);
        AcknowledgedResponse deleteTemplateAcknowledge = client.indices().deleteTemplate(request, RequestOptions.DEFAULT);
        return deleteTemplateAcknowledge.isAcknowledged();
彭勇升 pengys 已提交
159 160 161 162 163 164 165
    }

    public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder) throws IOException {
        indexName = formatIndexName(indexName);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(TYPE);
        searchRequest.source(searchSourceBuilder);
166
        return client.search(searchRequest, RequestOptions.DEFAULT);
彭勇升 pengys 已提交
167 168 169 170 171
    }

    public GetResponse get(String indexName, String id) throws IOException {
        indexName = formatIndexName(indexName);
        GetRequest request = new GetRequest(indexName, TYPE, id);
172
        return client.get(request, RequestOptions.DEFAULT);
彭勇升 pengys 已提交
173 174
    }

彭勇升 pengys 已提交
175 176 177 178
    public MultiGetResponse multiGet(String indexName, List<String> ids) throws IOException {
        final String newIndexName = formatIndexName(indexName);
        MultiGetRequest request = new MultiGetRequest();
        ids.forEach(id -> request.add(newIndexName, TYPE, id));
179
        return client.mget(request, RequestOptions.DEFAULT);
彭勇升 pengys 已提交
180 181
    }

182 183 184
    public void forceInsert(String indexName, String id, XContentBuilder source) throws IOException {
        IndexRequest request = prepareInsert(indexName, id, source);
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
185
        client.index(request, RequestOptions.DEFAULT);
186 187 188 189 190 191
    }

    public void forceUpdate(String indexName, String id, XContentBuilder source, long version) throws IOException {
        UpdateRequest request = prepareUpdate(indexName, id, source);
        request.version(version);
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
192
        client.update(request, RequestOptions.DEFAULT);
193 194 195 196 197
    }

    public void forceUpdate(String indexName, String id, XContentBuilder source) throws IOException {
        UpdateRequest request = prepareUpdate(indexName, id, source);
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
198
        client.update(request, RequestOptions.DEFAULT);
199 200
    }

彭勇升 pengys 已提交
201 202 203 204 205 206 207 208 209 210
    public IndexRequest prepareInsert(String indexName, String id, XContentBuilder source) {
        indexName = formatIndexName(indexName);
        return new IndexRequest(indexName, TYPE, id).source(source);
    }

    public UpdateRequest prepareUpdate(String indexName, String id, XContentBuilder source) {
        indexName = formatIndexName(indexName);
        return new UpdateRequest(indexName, TYPE, id).doc(source);
    }

211
    public int delete(String indexName, String timeBucketColumnName, long endTimeBucket) throws IOException {
彭勇升 pengys 已提交
212
        indexName = formatIndexName(indexName);
213 214 215 216 217 218 219 220

        DeleteByQueryRequest request = new DeleteByQueryRequest();
        request.indices(indexName);
        request.setQuery(QueryBuilders.rangeQuery(timeBucketColumnName).lte(endTimeBucket));

        BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
        logger.debug("Delete data from index {}, deleted {}", indexName, response.getDeleted());
        return 200;
彭勇升 pengys 已提交
221 222
    }

223
    public String formatIndexName(String indexName) {
224 225
        if (StringUtils.isNotEmpty(namespace)) {
            return namespace + "_" + indexName;
彭勇升 pengys 已提交
226 227 228 229 230 231 232 233 234
        }
        return indexName;
    }

    public BulkProcessor createBulkProcessor(int bulkActions, int bulkSize, int flushInterval,
        int concurrentRequests) {
        BulkProcessor.Listener listener = new BulkProcessor.Listener() {
            @Override
            public void beforeBulk(long executionId, BulkRequest request) {
235 236
                int numberOfActions = request.numberOfActions();
                logger.debug("Executing bulk [{}] with {} requests", executionId, numberOfActions);
彭勇升 pengys 已提交
237 238 239
            }

            @Override
240 241 242 243 244 245 246
            public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
                if (response.hasFailures()) {
                    logger.warn("Bulk [{}] executed with failures", executionId);
                } else {
                    logger.debug("Bulk [{}] completed in {} milliseconds",
                        executionId, response.getTook().getMillis());
                }
彭勇升 pengys 已提交
247 248 249 250
            }

            @Override
            public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
251
                logger.error("Failed to execute bulk", failure);
彭勇升 pengys 已提交
252 253 254
            }
        };

255 256 257 258
        BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer =
            (request, bulkListener) -> client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener);

        return BulkProcessor.builder(bulkConsumer, listener)
彭勇升 pengys 已提交
259 260 261 262 263 264 265 266
            .setBulkActions(bulkActions)
            .setBulkSize(new ByteSizeValue(bulkSize, ByteSizeUnit.MB))
            .setFlushInterval(TimeValue.timeValueSeconds(flushInterval))
            .setConcurrentRequests(concurrentRequests)
            .setBackoffPolicy(BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3))
            .build();
    }
}