You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2021/09/27 10:02:28 UTC
[GitHub] [flink] fapaul opened a new pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
fapaul opened a new pull request #17363:
URL: https://github.com/apache/flink/pull/17363
<!--
*Thank you very much for contributing to Apache Flink - we are happy that you want to help us improve Flink. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
*Please understand that we do not do this to make contributions to Flink a hassle. In order to uphold a high standard of quality for code contributions, while at the same time managing a large number of contributions, we need contributors to prepare the contributions well, and give reviewers enough contextual information for the review. Please also understand that contributions that do not follow this guide will take longer to review and thus typically be picked up with lower priority by the community.*
## Contribution Checklist
- Make sure that the pull request corresponds to a [JIRA issue](https://issues.apache.org/jira/projects/FLINK/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
- Name the pull request in the form "[FLINK-XXXX] [component] Title of the pull request", where *FLINK-XXXX* should be replaced by the actual issue number. Skip *component* if you are unsure about which is the best component.
Typo fixes that have no associated JIRA issue should be named following this pattern: `[hotfix] [docs] Fix typo in event time introduction` or `[hotfix] [javadocs] Expand JavaDoc for PuncuatedWatermarkGenerator`.
- Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
- Make sure that the change passes the automated tests, i.e., `mvn clean verify` passes. You can set up Azure Pipelines CI to do that following [this guide](https://cwiki.apache.org/confluence/display/FLINK/Azure+Pipelines#AzurePipelines-Tutorial:SettingupAzurePipelinesforaforkoftheFlinkrepository).
- Each pull request should address only one issue, not mix up code from multiple issues.
- Each commit in the pull request has a meaningful commit message (including the JIRA id)
- Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
**(The sections below can be removed for hotfixes of typos)**
-->
## What is the purpose of the change
Implement a sink for Elasticsearch 7 based on the new sink framework (FLIP-143)
214dffa needs no review it is only temporary until https://github.com/apache/flink/pull/17351 has been merged
## Verifying this change
*(Please pick either of the following options)*
- Added multiple IT cases covering the overall executions
## Does this pull request potentially affect one of the following parts:
- Dependencies (does it add or upgrade a dependency): (yes / **no**)
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (yes / **no**)
- The serializers: (yes / **no** / don't know)
- The runtime per-record code paths (performance sensitive): (yes / **no** / don't know)
- Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: (yes / **no** / don't know)
- The S3 file system connector: (yes / **no** / don't know)
## Documentation
- Does this pull request introduce a new feature? (**yes** / no)
- If yes, how is the feature documented? (not applicable / docs / JavaDocs / not documented)
https://issues.apache.org/jira/browse/FLINK-24326
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
}, {
"hash" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"triggerType" : "PUSH"
}, {
"hash" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24796",
"triggerID" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c12f95b1907cb375af2f3da22d59cba25e7fe01c Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776)
* 9b43b01e84d828b0dd6f1f121ffc736df8760743 UNKNOWN
* bee7c870c5607a28c2d2a652601e8efa5b92458d Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24796)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576)
* 6bd214da5083a1b9708f38f1138b492ea2b76bb4 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620)
* 7387899a9a9db33b69a0eaa0563c5c80f6209584 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r719484986
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
Let's create a follow-up on that. I feel that this is again a building block but I might be wrong because ES is not working on byte[] as other sinks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718431883
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestProcessor.java
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+class TestProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+
+ private final String index;
+ private final XContentBuilderProvider xContentBuilderProvider;
+ private final String dataFieldName;
+
+ public static TestProcessor jsonProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::jsonBuilder);
+ }
+
+ public static TestProcessor smileProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::smileBuilder);
+ }
+
Review comment:
Unfortunately, I do not see an easy way to provide a builder because users can produce multiple types of actions `Delete`, `Index` or `Update`, and the parameters are not compatible across elastic versions.
Any idea?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718222090
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
```suggestion
private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType = NONE;
...
enum FlushBackoffType {
NONE, ...;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r720245959
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
If we return a list of requests we loose the type information and would need to do the respective casts later, isn't this performance critical?
I understand what you are aiming for to make it more applicable to the other serialization schemas it would definitely help to have a return type.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716696452
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
Review comment:
Theoretically, you are correct but I am not sure we should hint the users to create _none_ ;)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718296315
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` an configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` a configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* d3a18adc8f5711046c47496d25374f4be4279520 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766)
* c12f95b1907cb375af2f3da22d59cba25e7fe01c UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718220854
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
The bom just aligns versions. I'd just make it available to all modules similar to junit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718203666
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
In the old sink, it was called `ElasticsearchFunction` which I found even worse. We can go with emitter.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718206431
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
Looking at Elasticsearch's APIs in the past I think it is a good idea to not make any ES API part of Flink's public API to easier support multiple versions.
I also feel that `Requests` or `BatchRequests` are not really correct here because it implies that you always add to a single request. The class was called `RequestIndexer` before so I have no hard feeling about finding a good replacement.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716688301
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
Add type NONE to avoid the nullable?
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
We should probably add that to the root pom.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
Well it also submits actions in between checkpoints, no?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
In a way the processor is like the `SerializationSchema`. How do they relate? Should we add some Processor builder similar to `KafkaSerializationSchema`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
This could be moved inside the enum's as a method `BackoffPolicy createBackoffPolicy(backoffDelay, maxRetryCount)`, especially if you add NONE.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
Review comment:
Internal?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
Review comment:
`getBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffEnabledButNotConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
Review comment:
`getBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
The name sounds more like an input processor where you process elements coming from ES. How about `ElasticsearchEmitter`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Is this internal?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
Review comment:
```suggestion
* Flink Sink to insert or update data in an Elasticsearch index. The sink supports the following
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
Review comment:
Why is this called json, when it's a map? Maybe, we should use an example where we just add a string?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
`Function` is already `Serializable` ;)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
I see that `RequestIndexer` is a thin wrapper around ES `BulkProcessor`. I'm wondering if we should simply expose that directly.
I think `RequestIndexer` is a misnomer and should be called `Requests` or `BatchRequest`.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchProcessor<IN> processor;
+ private final BulkProcessorConfig buildBulkProcessorConfig;
+ private final NetworkClientConfig networkClientConfig;
+ private final DeliveryGuarantee deliveryGuarantee;
+
+ ElasticsearchSink(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ DeliveryGuarantee deliveryGuarantee,
+ BulkProcessorConfig buildBulkProcessorConfig,
+ NetworkClientConfig networkClientConfig) {
+ this.hosts = checkNotNull(hosts);
+ checkState(!hosts.isEmpty(), "Hosts cannot be empty.");
Review comment:
`checkArg`
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
Review comment:
```suggestion
* <p>The following example shows the minimal setup to create a ElasticsearchSink that submits
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
Review comment:
```suggestion
* failure, it might happen that actions are lost if the bulk processor still has buffered
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
Review comment:
```suggestion
private ElasticsearchProcessor<IN> processor;
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
+
+ /**
+ * Sets the username used to authenticate the connection with the Elasticsearch cluster.
+ *
+ * @param username of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionUsername(String username) {
+ checkNotNull(username);
+ this.username = username;
+ return this;
+ }
+
+ /**
+ * Sets the password used to authenticate the conection with the Elasticsearch cluster.
+ *
+ * @param password of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPassword(String password) {
+ checkNotNull(password);
+ this.password = password;
+ return this;
+ }
+
+ /**
+ * Sets a prefix which used for every REST communication to the Elasticsearch cluster.
+ *
+ * @param prefix for the communication
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPathPrefix(String prefix) {
+ checkNotNull(prefix);
+ this.connectionPathPrefix = prefix;
+ return this;
+ }
+
+ /** @return {@link ElasticsearchSink} */
+ @SuppressWarnings("unchecked")
+ public ElasticsearchSink<IN> build() {
+ checkNotNull(hosts);
+ checkNotNull(processor);
+ return new ElasticsearchSink<IN>(
+ hosts,
+ (ElasticsearchProcessor<IN>) processor,
Review comment:
Get rid of this cast and use `<? super IN>` all the way.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
+
+ /**
+ * Sets the username used to authenticate the connection with the Elasticsearch cluster.
+ *
+ * @param username of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionUsername(String username) {
+ checkNotNull(username);
+ this.username = username;
+ return this;
+ }
+
+ /**
+ * Sets the password used to authenticate the conection with the Elasticsearch cluster.
+ *
+ * @param password of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPassword(String password) {
+ checkNotNull(password);
+ this.password = password;
+ return this;
+ }
+
+ /**
+ * Sets a prefix which used for every REST communication to the Elasticsearch cluster.
+ *
+ * @param prefix for the communication
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPathPrefix(String prefix) {
+ checkNotNull(prefix);
+ this.connectionPathPrefix = prefix;
+ return this;
+ }
+
+ /** @return {@link ElasticsearchSink} */
+ @SuppressWarnings("unchecked")
+ public ElasticsearchSink<IN> build() {
+ checkNotNull(hosts);
+ checkNotNull(processor);
+ return new ElasticsearchSink<IN>(
+ hosts,
+ (ElasticsearchProcessor<IN>) processor,
+ deliveryGuarantee,
+ buildBulkProcessorConfig(),
+ new NetworkClientConfig(username, password, connectionPathPrefix));
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T extends IN> ElasticsearchSinkBuilder<T> self() {
+ return (ElasticsearchSinkBuilder<T>) this;
+ }
+
+ private BulkProcessorConfig buildBulkProcessorConfig() {
+ if (bulkFlushBackoffType == null) {
+ checkState(
+ bulkFlushBackoffRetries == -1,
+ "Max number of backoff attempts cannot be used without backoff type.");
+ checkState(
+ bulkFlushBackOffDelay == -1,
+ "Delay (in milliseconds) between each backoff cannot be used "
+ + "without backoff type.");
+ return new BulkProcessorConfig(bulkFlushMaxActions, bulkFlushMaxMb, bulkFlushInterval);
Review comment:
Would be nice if we could enforce that with sub-builders. See Avro's SchemaBuilder for an example.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
Review comment:
```suggestion
* <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
* buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
* but actions might be sent to Elasticsearch multiple times when Flink restarts. These additional requests may cause inconsistent data in ElasticSearch right after the restart, but eventually everything will be consistent again.
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
Review comment:
This feels like we will add in one or another way to all the batchy sink builders :/ (so all of AsyncSink's implementations). I think this is the perfect time to extract some base builders (or maybe when adopting AsyncSink?)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
Review comment:
```suggestion
ackTime = System.currentTimeMillis();
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
Review comment:
Maybe, we should collect all issues and use `ExceptionUtils#firstOrSuppressed`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed.",
+ actionRequest),
+ failure);
+ } else {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed with status %s.",
+ actionRequest, restStatus.getStatus()),
+ failure);
+ }
+ }
+ },
+ "elasticsearchSuccessCallback");
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ throw new FlinkRuntimeException("Complete bulk has failed.", failure);
+ },
+ "elasticsearchErrorCallback");
+ }
+ }
+
+ private boolean isClosed() {
+ if (closed) {
+ LOG.warn("Writer was closed before all records were acknowledged by Elasticsearch.");
+ }
+ return closed;
+ }
+
+ private class DefaultRequestIndexer implements RequestIndexer {
+
+ @Override
+ public void add(DeleteRequest... deleteRequests) {
+ for (final DeleteRequest deleteRequest : deleteRequests) {
+ if (flushOnCheckpoint) {
Review comment:
Move out of loop.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
Review comment:
In Kafka, we use `FlinkRuntimeException`.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed.",
+ actionRequest),
+ failure);
+ } else {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed with status %s.",
+ actionRequest, restStatus.getStatus()),
+ failure);
+ }
+ }
+ },
Review comment:
Let's replace all non-trivial lambdas with method lambdas please.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffEnabledButNotConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {})
+ .setBulkFlushBackoffType(ElasticsearchSinkBase.FlushBackoffType.CONSTANT);
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ private static List<ElasticsearchSinkBuilder<?>> validBuilders() {
+ return Lists.newArrayList(
+ getBuilder(),
+ getBuilder().setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE),
+ getBuilder()
+ .setBulkFlushBackoffType(ElasticsearchSinkBase.FlushBackoffType.CONSTANT)
+ .setBulkFlushBackoffRetries(1)
+ .setBulkFlushBackoffDelay(1),
+ getBuilder().setConnectionUsername("username").setConnectionPassword("password"));
+ }
+
+ private static List<Consumer<ElasticsearchSinkBuilder<?>>> backoffConfigurations() {
+ return Lists.newArrayList(
+ (b) -> b.setBulkFlushBackoffDelay(1), (b) -> b.setBulkFlushBackoffRetries(1));
+ }
+
+ private static ElasticsearchSinkBuilder<?> getBuilder() {
Review comment:
`createBuilder` or `newBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
Review comment:
`MethodSource` is the worst option for parameters. The parameters are separated and only bound with a fragile string name. I need to switch between the parameter method and the actual method to understand what's being tested.
`EnumSource` or `CsvSource` are much better imho. Maybe it would be better to use a [dynamic test](https://www.baeldung.com/junit5-dynamic-tests)? Then you would also avoid the consumer thingy which feels quaint here.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
Review comment:
I don't understand the second part of the check.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
Review comment:
Here we should also flush for `!flushOnCheckpoint && flush`. That means we always count pending elements.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
Review comment:
I think we should allow arbitrary `CredentialsProvider` here. We have made the mistake too often to limit the user.
Let's use a `SerializableSupplier` and expose that to the builder. We can use a subbuilder for basic creds.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase extends TestLogger {
Review comment:
I'm not sure if we need 2 ITCase classes for such trivial sinks. What was your reasoning?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/NetworkClientConfig.java
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class NetworkClientConfig implements Serializable {
Review comment:
Remove if we go for the Supplier thingy.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkITCase.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.state.CheckpointListener;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchSink}. */
+@Testcontainers
+class ElasticsearchSinkITCase extends TestLogger {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchSinkITCase.class);
+ private static final String ELASTICSEARCH_PASSWORD = "test-password";
+ private static final String ELASTICSEARCH_USER = "elastic";
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(
+ DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_COMMERCIAL_7))
+ .withPassword(ELASTICSEARCH_PASSWORD)
Review comment:
configure user?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
Private fields would not appear in JavaDocs, right? So I'd second Alex' comment ;)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
Review comment:
Creating none is a valid use case for dead letters.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestContext.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class TestContext {
Review comment:
What's this class supposed to do? Is it just some TestUtil? I'm confused by the `context` part.
##########
File path: flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/util/DockerImageVersions.java
##########
@@ -27,6 +27,9 @@
public static final String ELASTICSEARCH_7 =
"docker.elastic.co/elasticsearch/elasticsearch-oss:7.5.1";
+ public static final String ELASTICSEARCH_COMMERCIAL_7 =
Review comment:
Why do we need the commercial here?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestProcessor.java
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+class TestProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+
+ private final String index;
+ private final XContentBuilderProvider xContentBuilderProvider;
+ private final String dataFieldName;
+
+ public static TestProcessor jsonProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::jsonBuilder);
+ }
+
+ public static TestProcessor smileProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::smileBuilder);
+ }
+
Review comment:
Should we offer some builder on top-level? I'm a bit worried about the usability of the processor. In particular, there seems to be no relation to SerializationSchema.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
Review comment:
I'd remove that line - nothing is to be gained from this documentation.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriterITCase.class);
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_7))
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ private RestHighLevelClient client;
+ private TestContext context;
+ private MetricListener metricListener;
+
+ @BeforeEach
+ void setUp() {
+ metricListener = new MetricListener();
+ client =
+ new RestHighLevelClient(
+ RestClient.builder(HttpHost.create(ES_CONTAINER.getHttpHostAddress())));
+ context = new TestContext(client);
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+
+ @Test
+ void testWriteOnBulkFlush() throws Exception {
+ final String index = "test-bulk-flush-without-checkpoint";
+ final int flushAfterNActions = 5;
+ final BulkProcessorConfig bulkProcessorConfig =
+ new BulkProcessorConfig(flushAfterNActions, -1, -1, null, 0, 0);
+
+ try (final ElasticsearchWriter<Tuple2<Integer, String>> writer =
+ createWriter(index, false, bulkProcessorConfig)) {
+ writer.write(Tuple2.of(1, buildMessage(1)), null);
+ writer.write(Tuple2.of(2, buildMessage(2)), null);
+ writer.write(Tuple2.of(3, buildMessage(3)), null);
+ writer.write(Tuple2.of(4, buildMessage(4)), null);
+
+ // Ignore flush on checkpoint
+ writer.prepareCommit(true);
+ writer.prepareCommit(false);
Review comment:
But they should see above comment on flushing.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
```suggestion
ElasticsearchProcessor<? super T> processor) {
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* cc51de6fac70261acfaa5bb2d1c86ae3a704ae45 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530)
* ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r721951686
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchEmitter.java
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+/**
+ * Creates none or multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchEmitter implements ElasticsearchEmitter<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> document = new HashMap<>();
+ * document.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(document);
+ * }
+ *
+ * public void emit(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchEmitter}
+ */
+@PublicEvolving
+public interface ElasticsearchEmitter<T> extends Function {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void emit(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
It is the watermark `currentWatermark()` and the eventtime `timestamp()`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot commented on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* cc51de6fac70261acfaa5bb2d1c86ae3a704ae45 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716708969
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
Review comment:
convert the code line to use a `RuntimeException`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718430997
##########
File path: flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/util/DockerImageVersions.java
##########
@@ -27,6 +27,9 @@
public static final String ELASTICSEARCH_7 =
"docker.elastic.co/elasticsearch/elasticsearch-oss:7.5.1";
+ public static final String ELASTICSEARCH_COMMERCIAL_7 =
Review comment:
Only the commercial image allows using the password authentication.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718430642
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkITCase.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.state.CheckpointListener;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchSink}. */
+@Testcontainers
+class ElasticsearchSinkITCase extends TestLogger {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchSinkITCase.class);
+ private static final String ELASTICSEARCH_PASSWORD = "test-password";
+ private static final String ELASTICSEARCH_USER = "elastic";
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(
+ DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_COMMERCIAL_7))
+ .withPassword(ELASTICSEARCH_PASSWORD)
Review comment:
Do not ask me why bu the `ElasticsearchContainer` does only support setting the password and the user cannot be configured ...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* cc51de6fac70261acfaa5bb2d1c86ae3a704ae45 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 70e07383ac68b4c3235a89ddd05bd0925d317753 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718234851
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
Review comment:
AFAIK you always need to pass in some kind of json to the request. Either you do it via a map or you can implicitly use a string and specify a key. This way the request builds the json internally `{your_key: your_string}`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] alpreu commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
alpreu commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r722306566
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimal setup to create a ElasticsearchSink that submits
+ * actions on checkpoint or the default number of actions was buffered (1000).
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = 1000;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private FlushBackoffType bulkFlushBackoffType = FlushBackoffType.NONE;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchEmitter<? super IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchEmitter<? super T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
Review comment:
should be changed to "Emitter"
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542)
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] alpreu commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
alpreu commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716642866
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
Review comment:
It does not have to be multiple though, in theory it could be none, one, or multiple, right?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor has still buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * outstanding actions are flushed to and acknowledged by Elasticsearch. No actions will be
Review comment:
Could change outstanding to buffered to keep in line with the docs above
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
Review comment:
Should be FlinkRuntimeException?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor has still buffered
Review comment:
still has buffered actions
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
Review comment:
missing a
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
Review comment:
Sets the wanted {@link DeliveryGuarantee
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
missing default or is this on purpose so comments do not get stale?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriterITCase.class);
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_7))
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ private RestHighLevelClient client;
+ private TestContext context;
+ private MetricListener metricListener;
+
+ @BeforeEach
+ void setUp() {
+ metricListener = new MetricListener();
+ client =
+ new RestHighLevelClient(
+ RestClient.builder(HttpHost.create(ES_CONTAINER.getHttpHostAddress())));
+ context = new TestContext(client);
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+
+ @Test
+ void testWriteOnBulkFlush() throws Exception {
+ final String index = "test-bulk-flush-without-checkpoint";
+ final int flushAfterNActions = 5;
+ final BulkProcessorConfig bulkProcessorConfig =
+ new BulkProcessorConfig(flushAfterNActions, -1, -1, null, 0, 0);
+
+ try (final ElasticsearchWriter<Tuple2<Integer, String>> writer =
+ createWriter(index, false, bulkProcessorConfig)) {
+ writer.write(Tuple2.of(1, buildMessage(1)), null);
+ writer.write(Tuple2.of(2, buildMessage(2)), null);
+ writer.write(Tuple2.of(3, buildMessage(3)), null);
+ writer.write(Tuple2.of(4, buildMessage(4)), null);
+
+ // Ignore flush on checkpoint
+ writer.prepareCommit(true);
+ writer.prepareCommit(false);
Review comment:
Why are both called in succession here?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionsRequests}. The
Review comment:
Same as above, also typo in Action*s*requests
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* d3a18adc8f5711046c47496d25374f4be4279520 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766)
* c12f95b1907cb375af2f3da22d59cba25e7fe01c Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* cc51de6fac70261acfaa5bb2d1c86ae3a704ae45 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530)
* ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise merged pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
AHeise merged pull request #17363:
URL: https://github.com/apache/flink/pull/17363
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise merged pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
AHeise merged pull request #17363:
URL: https://github.com/apache/flink/pull/17363
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r722313770
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimal setup to create a ElasticsearchSink that submits
+ * actions on checkpoint or the default number of actions was buffered (1000).
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = 1000;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private FlushBackoffType bulkFlushBackoffType = FlushBackoffType.NONE;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchEmitter<? super IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchEmitter<? super T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
Review comment:
good catch 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 7387899a9a9db33b69a0eaa0563c5c80f6209584 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623)
* 70e07383ac68b4c3235a89ddd05bd0925d317753 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718235473
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchProcessor<IN> processor;
+ private final BulkProcessorConfig buildBulkProcessorConfig;
+ private final NetworkClientConfig networkClientConfig;
+ private final DeliveryGuarantee deliveryGuarantee;
+
+ ElasticsearchSink(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ DeliveryGuarantee deliveryGuarantee,
+ BulkProcessorConfig buildBulkProcessorConfig,
+ NetworkClientConfig networkClientConfig) {
+ this.hosts = checkNotNull(hosts);
+ checkState(!hosts.isEmpty(), "Hosts cannot be empty.");
Review comment:
I am still surprised when to use which precondition ... :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716688301
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
Add type NONE to avoid the nullable?
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
We should probably add that to the root pom.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
Well it also submits actions in between checkpoints, no?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
In a way the processor is like the `SerializationSchema`. How do they relate? Should we add some Processor builder similar to `KafkaSerializationSchema`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
This could be moved inside the enum's as a method `BackoffPolicy createBackoffPolicy(backoffDelay, maxRetryCount)`, especially if you add NONE.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
Review comment:
Internal?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
Review comment:
`getBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffEnabledButNotConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
Review comment:
`getBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
The name sounds more like an input processor where you process elements coming from ES. How about `ElasticsearchEmitter`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Is this internal?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
Review comment:
```suggestion
* Flink Sink to insert or update data in an Elasticsearch index. The sink supports the following
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
Review comment:
Why is this called json, when it's a map? Maybe, we should use an example where we just add a string?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
`Function` is already `Serializable` ;)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
I see that `RequestIndexer` is a thin wrapper around ES `BulkProcessor`. I'm wondering if we should simply expose that directly.
I think `RequestIndexer` is a misnomer and should be called `Requests` or `BatchRequest`.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchProcessor<IN> processor;
+ private final BulkProcessorConfig buildBulkProcessorConfig;
+ private final NetworkClientConfig networkClientConfig;
+ private final DeliveryGuarantee deliveryGuarantee;
+
+ ElasticsearchSink(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ DeliveryGuarantee deliveryGuarantee,
+ BulkProcessorConfig buildBulkProcessorConfig,
+ NetworkClientConfig networkClientConfig) {
+ this.hosts = checkNotNull(hosts);
+ checkState(!hosts.isEmpty(), "Hosts cannot be empty.");
Review comment:
`checkArg`
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
Review comment:
```suggestion
* <p>The following example shows the minimal setup to create a ElasticsearchSink that submits
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
Review comment:
```suggestion
* failure, it might happen that actions are lost if the bulk processor still has buffered
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
Review comment:
```suggestion
private ElasticsearchProcessor<IN> processor;
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
+
+ /**
+ * Sets the username used to authenticate the connection with the Elasticsearch cluster.
+ *
+ * @param username of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionUsername(String username) {
+ checkNotNull(username);
+ this.username = username;
+ return this;
+ }
+
+ /**
+ * Sets the password used to authenticate the conection with the Elasticsearch cluster.
+ *
+ * @param password of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPassword(String password) {
+ checkNotNull(password);
+ this.password = password;
+ return this;
+ }
+
+ /**
+ * Sets a prefix which used for every REST communication to the Elasticsearch cluster.
+ *
+ * @param prefix for the communication
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPathPrefix(String prefix) {
+ checkNotNull(prefix);
+ this.connectionPathPrefix = prefix;
+ return this;
+ }
+
+ /** @return {@link ElasticsearchSink} */
+ @SuppressWarnings("unchecked")
+ public ElasticsearchSink<IN> build() {
+ checkNotNull(hosts);
+ checkNotNull(processor);
+ return new ElasticsearchSink<IN>(
+ hosts,
+ (ElasticsearchProcessor<IN>) processor,
Review comment:
Get rid of this cast and use `<? super IN>` all the way.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
+
+ /**
+ * Sets the username used to authenticate the connection with the Elasticsearch cluster.
+ *
+ * @param username of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionUsername(String username) {
+ checkNotNull(username);
+ this.username = username;
+ return this;
+ }
+
+ /**
+ * Sets the password used to authenticate the conection with the Elasticsearch cluster.
+ *
+ * @param password of the Elasticsearch cluster user
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPassword(String password) {
+ checkNotNull(password);
+ this.password = password;
+ return this;
+ }
+
+ /**
+ * Sets a prefix which used for every REST communication to the Elasticsearch cluster.
+ *
+ * @param prefix for the communication
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setConnectionPathPrefix(String prefix) {
+ checkNotNull(prefix);
+ this.connectionPathPrefix = prefix;
+ return this;
+ }
+
+ /** @return {@link ElasticsearchSink} */
+ @SuppressWarnings("unchecked")
+ public ElasticsearchSink<IN> build() {
+ checkNotNull(hosts);
+ checkNotNull(processor);
+ return new ElasticsearchSink<IN>(
+ hosts,
+ (ElasticsearchProcessor<IN>) processor,
+ deliveryGuarantee,
+ buildBulkProcessorConfig(),
+ new NetworkClientConfig(username, password, connectionPathPrefix));
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T extends IN> ElasticsearchSinkBuilder<T> self() {
+ return (ElasticsearchSinkBuilder<T>) this;
+ }
+
+ private BulkProcessorConfig buildBulkProcessorConfig() {
+ if (bulkFlushBackoffType == null) {
+ checkState(
+ bulkFlushBackoffRetries == -1,
+ "Max number of backoff attempts cannot be used without backoff type.");
+ checkState(
+ bulkFlushBackOffDelay == -1,
+ "Delay (in milliseconds) between each backoff cannot be used "
+ + "without backoff type.");
+ return new BulkProcessorConfig(bulkFlushMaxActions, bulkFlushMaxMb, bulkFlushInterval);
Review comment:
Would be nice if we could enforce that with sub-builders. See Avro's SchemaBuilder for an example.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
Review comment:
```suggestion
* <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
* buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
* but actions might be sent to Elasticsearch multiple times when Flink restarts. These additional requests may cause inconsistent data in ElasticSearch right after the restart, but eventually everything will be consistent again.
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
Review comment:
This feels like we will add in one or another way to all the batchy sink builders :/ (so all of AsyncSink's implementations). I think this is the perfect time to extract some base builders (or maybe when adopting AsyncSink?)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
Review comment:
```suggestion
ackTime = System.currentTimeMillis();
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
Review comment:
Maybe, we should collect all issues and use `ExceptionUtils#firstOrSuppressed`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed.",
+ actionRequest),
+ failure);
+ } else {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed with status %s.",
+ actionRequest, restStatus.getStatus()),
+ failure);
+ }
+ }
+ },
+ "elasticsearchSuccessCallback");
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ throw new FlinkRuntimeException("Complete bulk has failed.", failure);
+ },
+ "elasticsearchErrorCallback");
+ }
+ }
+
+ private boolean isClosed() {
+ if (closed) {
+ LOG.warn("Writer was closed before all records were acknowledged by Elasticsearch.");
+ }
+ return closed;
+ }
+
+ private class DefaultRequestIndexer implements RequestIndexer {
+
+ @Override
+ public void add(DeleteRequest... deleteRequests) {
+ for (final DeleteRequest deleteRequest : deleteRequests) {
+ if (flushOnCheckpoint) {
Review comment:
Move out of loop.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
Review comment:
In Kafka, we use `FlinkRuntimeException`.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed.",
+ actionRequest),
+ failure);
+ } else {
+ throw new FlinkRuntimeException(
+ String.format(
+ "Single action %s of bulk request failed with status %s.",
+ actionRequest, restStatus.getStatus()),
+ failure);
+ }
+ }
+ },
Review comment:
Let's replace all non-trivial lambdas with method lambdas please.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffEnabledButNotConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {})
+ .setBulkFlushBackoffType(ElasticsearchSinkBase.FlushBackoffType.CONSTANT);
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ private static List<ElasticsearchSinkBuilder<?>> validBuilders() {
+ return Lists.newArrayList(
+ getBuilder(),
+ getBuilder().setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE),
+ getBuilder()
+ .setBulkFlushBackoffType(ElasticsearchSinkBase.FlushBackoffType.CONSTANT)
+ .setBulkFlushBackoffRetries(1)
+ .setBulkFlushBackoffDelay(1),
+ getBuilder().setConnectionUsername("username").setConnectionPassword("password"));
+ }
+
+ private static List<Consumer<ElasticsearchSinkBuilder<?>>> backoffConfigurations() {
+ return Lists.newArrayList(
+ (b) -> b.setBulkFlushBackoffDelay(1), (b) -> b.setBulkFlushBackoffRetries(1));
+ }
+
+ private static ElasticsearchSinkBuilder<?> getBuilder() {
Review comment:
`createBuilder` or `newBuilder`?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
Review comment:
`MethodSource` is the worst option for parameters. The parameters are separated and only bound with a fragile string name. I need to switch between the parameter method and the actual method to understand what's being tested.
`EnumSource` or `CsvSource` are much better imho. Maybe it would be better to use a [dynamic test](https://www.baeldung.com/junit5-dynamic-tests)? Then you would also avoid the consumer thingy which feels quaint here.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
Review comment:
I don't understand the second part of the check.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
Review comment:
Here we should also flush for `!flushOnCheckpoint && flush`. That means we always count pending elements.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
Review comment:
I think we should allow arbitrary `CredentialsProvider` here. We have made the mistake too often to limit the user.
Let's use a `SerializableSupplier` and expose that to the builder. We can use a subbuilder for basic creds.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase extends TestLogger {
Review comment:
I'm not sure if we need 2 ITCase classes for such trivial sinks. What was your reasoning?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/NetworkClientConfig.java
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class NetworkClientConfig implements Serializable {
Review comment:
Remove if we go for the Supplier thingy.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkITCase.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.state.CheckpointListener;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchSink}. */
+@Testcontainers
+class ElasticsearchSinkITCase extends TestLogger {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchSinkITCase.class);
+ private static final String ELASTICSEARCH_PASSWORD = "test-password";
+ private static final String ELASTICSEARCH_USER = "elastic";
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(
+ DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_COMMERCIAL_7))
+ .withPassword(ELASTICSEARCH_PASSWORD)
Review comment:
configure user?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
Private fields would not appear in JavaDocs, right? So I'd second Alex' comment ;)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
Review comment:
Creating none is a valid use case for dead letters.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestContext.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class TestContext {
Review comment:
What's this class supposed to do? Is it just some TestUtil? I'm confused by the `context` part.
##########
File path: flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/util/DockerImageVersions.java
##########
@@ -27,6 +27,9 @@
public static final String ELASTICSEARCH_7 =
"docker.elastic.co/elasticsearch/elasticsearch-oss:7.5.1";
+ public static final String ELASTICSEARCH_COMMERCIAL_7 =
Review comment:
Why do we need the commercial here?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestProcessor.java
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+class TestProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+
+ private final String index;
+ private final XContentBuilderProvider xContentBuilderProvider;
+ private final String dataFieldName;
+
+ public static TestProcessor jsonProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::jsonBuilder);
+ }
+
+ public static TestProcessor smileProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::smileBuilder);
+ }
+
Review comment:
Should we offer some builder on top-level? I'm a bit worried about the usability of the processor. In particular, there seems to be no relation to SerializationSchema.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
Review comment:
I'd remove that line - nothing is to be gained from this documentation.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriterITCase.class);
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_7))
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ private RestHighLevelClient client;
+ private TestContext context;
+ private MetricListener metricListener;
+
+ @BeforeEach
+ void setUp() {
+ metricListener = new MetricListener();
+ client =
+ new RestHighLevelClient(
+ RestClient.builder(HttpHost.create(ES_CONTAINER.getHttpHostAddress())));
+ context = new TestContext(client);
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+
+ @Test
+ void testWriteOnBulkFlush() throws Exception {
+ final String index = "test-bulk-flush-without-checkpoint";
+ final int flushAfterNActions = 5;
+ final BulkProcessorConfig bulkProcessorConfig =
+ new BulkProcessorConfig(flushAfterNActions, -1, -1, null, 0, 0);
+
+ try (final ElasticsearchWriter<Tuple2<Integer, String>> writer =
+ createWriter(index, false, bulkProcessorConfig)) {
+ writer.write(Tuple2.of(1, buildMessage(1)), null);
+ writer.write(Tuple2.of(2, buildMessage(2)), null);
+ writer.write(Tuple2.of(3, buildMessage(3)), null);
+ writer.write(Tuple2.of(4, buildMessage(4)), null);
+
+ // Ignore flush on checkpoint
+ writer.prepareCommit(true);
+ writer.prepareCommit(false);
Review comment:
But they should see above comment on flushing.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
```suggestion
ElasticsearchProcessor<? super T> processor) {
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718221569
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Good question. Probably not. So ignore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 70e07383ac68b4c3235a89ddd05bd0925d317753 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654)
* c80cf0c61e4587125dcf9e1bce2fff8c40928255 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r719486443
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
I could even imagine that this beyond connectors and then you are right.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r721188286
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchEmitter.java
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+/**
+ * Creates none or multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchEmitter implements ElasticsearchEmitter<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> document = new HashMap<>();
+ * document.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(document);
+ * }
+ *
+ * public void emit(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchEmitter}
+ */
+@PublicEvolving
+public interface ElasticsearchEmitter<T> extends Function {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void emit(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
The context is pretty much only for watermark, right?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestContext.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class TestContext {
Review comment:
How about `TestClient` then? ;)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
I feel like this is not completely addressed. It seems like you set actions to 1k by default, but then this comment should also reflect that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718471850
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
Review comment:
We have to find a balance here all additional UDFs are making the usage in Table API more difficult. The previous Table API connector only supported Basic auth and no one ever complained.
In general, I understand your idea but we can easily extend the authentication feature set if needed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718433443
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestContext.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class TestContext {
Review comment:
It holds the client used for test thus I named it context. To me utils are not instantiable and only provide static methods.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576)
* 6bd214da5083a1b9708f38f1138b492ea2b76bb4 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620)
* 7387899a9a9db33b69a0eaa0563c5c80f6209584 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718224708
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
Is this good? O_O I'd go with a default bulk processor that emits every 1k requests or so. I see plenty of new users running in OOM otherwise. How does that even work without checkpointing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718223674
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
I'm wondering if we can't simply return a list of requests?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718201189
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
Isn't it already part of the root pom by specifying the bom https://github.com/apache/flink/blob/4fe9f525a92319acc1e3434bebed601306f7a16f/pom.xml#L780 ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718199624
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
Good that we have done the same thing in the Kafka docs :)
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
Isn't it already part of the root pom by specifying the bom https://github.com/apache/flink/blob/4fe9f525a92319acc1e3434bebed601306f7a16f/pom.xml#L780 ?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Yes, do we need `@Internal` for package-private classes?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
What exactly do you mean here?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
In the old sink, it was called `ElasticsearchFunction` which I found even worse. We can go with emitter.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
Looking at Elasticsearch's APIs in the past I think it is a good idea to not make any ES API part of Flink's public API to easier support multiple versions.
I also feel that `Requests` or `BatchRequests` are not really correct here because it implies that you always add to a single request. The class was called `RequestIndexer` before so I have no hard feeling about finding a good replacement.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
If you do not specify anything for the bulk processor it will not emit anything except on a checkpoint.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
Review comment:
AFAIK you always need to pass in some kind of json to the request. Either you do it via a map or you can implicitly use a string and specify a key. This way the request builds the json internally `{your_key: your_string}`.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Flink Sink to produce or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchProcessor<IN> processor;
+ private final BulkProcessorConfig buildBulkProcessorConfig;
+ private final NetworkClientConfig networkClientConfig;
+ private final DeliveryGuarantee deliveryGuarantee;
+
+ ElasticsearchSink(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ DeliveryGuarantee deliveryGuarantee,
+ BulkProcessorConfig buildBulkProcessorConfig,
+ NetworkClientConfig networkClientConfig) {
+ this.hosts = checkNotNull(hosts);
+ checkState(!hosts.isEmpty(), "Hosts cannot be empty.");
Review comment:
I am still surprised when to use which precondition ... :)
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
> In a way the processor is like the `SerializationSchema`. How do they relate? Should we add some Processor builder similar to `KafkaSerializationSchema`?
You are right, I was also wondering about the relation between the usually used `SerializationSchema`s and this elasticsearch sink way. So far I do not see a comfortable way to offer a nice build.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
Review comment:
Definitely 👍
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
Review comment:
Can do but the class is already package-private, so is it necessary?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` and configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` an configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` a configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
Review comment:
Good idea 👍
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
Review comment:
Some of the tests became unnecessary and only one simple method source is still used. I would say it is not worth the extra effort to remove it.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkITCase.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.state.CheckpointListener;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchSink}. */
+@Testcontainers
+class ElasticsearchSinkITCase extends TestLogger {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchSinkITCase.class);
+ private static final String ELASTICSEARCH_PASSWORD = "test-password";
+ private static final String ELASTICSEARCH_USER = "elastic";
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(
+ DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_COMMERCIAL_7))
+ .withPassword(ELASTICSEARCH_PASSWORD)
Review comment:
Do not ask me why bu the `ElasticsearchContainer` does only support setting the password and the user cannot be configured ...
##########
File path: flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/util/DockerImageVersions.java
##########
@@ -27,6 +27,9 @@
public static final String ELASTICSEARCH_7 =
"docker.elastic.co/elasticsearch/elasticsearch-oss:7.5.1";
+ public static final String ELASTICSEARCH_COMMERCIAL_7 =
Review comment:
Only the commercial image allows using the password authentication.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestProcessor.java
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+class TestProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+
+ private final String index;
+ private final XContentBuilderProvider xContentBuilderProvider;
+ private final String dataFieldName;
+
+ public static TestProcessor jsonProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::jsonBuilder);
+ }
+
+ public static TestProcessor smileProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::smileBuilder);
+ }
+
Review comment:
Unfortunately, I do not see an easy way to provide a builder because users can produce multiple types of actions `Delete`, `Index` or `Update`, and the parameters are not compatible across elastic versions.
Any idea?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase extends TestLogger {
Review comment:
Hmm, I like that the WriterITCase covers most of the actual flush behavior which seemed hard to test when Flink is calling the flushing methods and the overall sink it cases are to see how it interacts in common scenarios.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestContext.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestHighLevelClient;
+
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class TestContext {
Review comment:
It holds the client used for test thus I named it context. To me utils are not instantiable and only provide static methods.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
Review comment:
We have to find a balance here all additional UDFs are making the usage in Table API more difficult. The previous Table API connector only supported Basic auth and no one ever complained.
In general, I understand your idea but we can easily extend the authentication feature set if needed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
}, {
"hash" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c12f95b1907cb375af2f3da22d59cba25e7fe01c Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776)
* 9b43b01e84d828b0dd6f1f121ffc736df8760743 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718238615
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
Review comment:
> In a way the processor is like the `SerializationSchema`. How do they relate? Should we add some Processor builder similar to `KafkaSerializationSchema`?
You are right, I was also wondering about the relation between the usually used `SerializationSchema`s and this elasticsearch sink way. So far I do not see a comfortable way to offer a nice build.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718429830
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilderTest.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.TestLogger;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
+
+import org.apache.http.HttpHost;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/** Tests for {@link ElasticsearchSinkBuilder}. */
+class ElasticsearchSinkBuilderTest extends TestLogger {
+
+ @ParameterizedTest
+ @MethodSource("validBuilders")
+ void testBuildElasticsearchSink(ElasticsearchSinkBuilder<?> builder) {
+ builder.build();
+ }
+
+ @Test
+ void testThrowIfExactlyOnceConfigured() {
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE));
+ }
+
+ @Test
+ void testThrowIfHostsNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setProcessor((element, indexer, context) -> {})
+ .build());
+ }
+
+ @Test
+ void testThrowIfProcessorNotSet() {
+ assertThrows(
+ NullPointerException.class,
+ () ->
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .build());
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
+ void testThrowIfBackoffNotEnabledButConfigured(
+ Consumer<ElasticsearchSinkBuilder<?>> configure) {
+ final ElasticsearchSinkBuilder<?> builder =
+ new ElasticsearchSinkBuilder<>()
+ .setHosts(new HttpHost("localhost:3000"))
+ .setProcessor((element, indexer, context) -> {});
+ configure.accept(builder);
+ assertThrows(IllegalStateException.class, builder::build);
+ }
+
+ @ParameterizedTest
+ @MethodSource("backoffConfigurations")
Review comment:
Some of the tests became unnecessary and only one simple method source is still used. I would say it is not worth the extra effort to remove it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 7387899a9a9db33b69a0eaa0563c5c80f6209584 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623)
* 70e07383ac68b4c3235a89ddd05bd0925d317753 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c12f95b1907cb375af2f3da22d59cba25e7fe01c Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c80cf0c61e4587125dcf9e1bce2fff8c40928255 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713)
* d3a18adc8f5711046c47496d25374f4be4279520 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
}, {
"hash" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"triggerType" : "PUSH"
}, {
"hash" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c12f95b1907cb375af2f3da22d59cba25e7fe01c Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776)
* 9b43b01e84d828b0dd6f1f121ffc736df8760743 UNKNOWN
* bee7c870c5607a28c2d2a652601e8efa5b92458d UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r723011641
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/TestProcessor.java
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+class TestProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+
+ private final String index;
+ private final XContentBuilderProvider xContentBuilderProvider;
+ private final String dataFieldName;
+
+ public static TestProcessor jsonProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::jsonBuilder);
+ }
+
+ public static TestProcessor smileProcessor(String index, String dataFieldName) {
+ return new TestProcessor(index, dataFieldName, XContentFactory::smileBuilder);
+ }
+
Review comment:
Not yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576)
* 6bd214da5083a1b9708f38f1138b492ea2b76bb4 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-933429258
Could you adjust the title to something for user-friendly?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c80cf0c61e4587125dcf9e1bce2fff8c40928255 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713)
* d3a18adc8f5711046c47496d25374f4be4279520 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718432796
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase extends TestLogger {
Review comment:
Hmm, I like that the WriterITCase covers most of the actual flush behavior which seemed hard to test when Flink is calling the flushing methods and the overall sink it cases are to see how it interacts in common scenarios.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r719483898
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
Review comment:
I see from IndexRequest javadoc: `Index request to index a typed JSON document into a specific index and make it searchable.` So I kinda understand the point, but imho the field should be `document` and not the technical term.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718296315
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
Review comment:
WDYT about making the `FlushBackoffType` similar to `DeliveryGuarantee` and configuration enum accessible to all connectors? I can imagine there a lot of connectors wanting to implement a similar thing.
This would mean we cannot put elastic-specific code into it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718222862
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
Agreed that this is already better, we can still think of better names. I was even thinking of ESSerializationSchema.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718220854
##########
File path: flink-connectors/flink-connector-elasticsearch7/pom.xml
##########
@@ -92,6 +92,12 @@ under the License.
<scope>test</scope>
</dependency>
+ <dependency>
Review comment:
The bom just aligns versions. I'd just make it available to all modules similar to junit.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Good question. Probably not. So ignore.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
```suggestion
private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType = NONE;
...
enum FlushBackoffType {
NONE, ...;
}
```
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
Review comment:
Agreed that this is already better, we can still think of better names. I was even thinking of ESSerializationSchema.
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchProcessor.java
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.Function;
+import org.apache.flink.api.connector.sink.SinkWriter;
+
+import org.elasticsearch.action.ActionRequest;
+
+import java.io.Serializable;
+
+/**
+ * Creates multiple {@link ActionRequest ActionRequests} from the incoming elements.
+ *
+ * <p>This is used by sinks to prepare elements for sending them to Elasticsearch.
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * private static class TestElasticsearchProcessor implements ElasticsearchProcessor<Tuple2<Integer, String>> {
+ *
+ * public IndexRequest createIndexRequest(Tuple2<Integer, String> element) {
+ * Map<String, Object> json = new HashMap<>();
+ * json.put("data", element.f1);
+ *
+ * return Requests.indexRequest()
+ * .index("my-index")
+ * .type("my-type")
+ * .id(element.f0.toString())
+ * .source(json);
+ * }
+ *
+ * public void process(Tuple2<Integer, String> element, RequestIndexer indexer) {
+ * indexer.add(createIndexRequest(element));
+ * }
+ * }
+ *
+ * }</pre>
+ *
+ * @param <T> The type of the element handled by this {@link ElasticsearchProcessor}
+ */
+@PublicEvolving
+public interface ElasticsearchProcessor<T> extends Function, Serializable {
+
+ /**
+ * Initialization method for the function. It is called once before the actual working process
+ * methods.
+ */
+ default void open() throws Exception {}
+
+ /** Tear-down method for the function. It is called when the sink closes. */
+ default void close() throws Exception {}
+
+ /**
+ * Process the incoming element to produce multiple {@link ActionRequest ActionRequests}. The
+ * produced requests should be added to the provided {@link RequestIndexer}.
+ *
+ * @param element incoming element to process
+ * @param context to access additional information about the record
+ * @param indexer request indexer that {@code ActionRequest} should be added to
+ */
+ void process(T element, SinkWriter.Context context, RequestIndexer indexer);
Review comment:
I'm wondering if we can't simply return a list of requests?
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
Is this good? O_O I'd go with a default bulk processor that emits every 1k requests or so. I see plenty of new users running in OOM otherwise. How does that even work without checkpointing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot commented on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927721069
Thanks a lot for your contribution to the Apache Flink project. I'm the @flinkbot. I help the community
to review your pull request. We will use this comment to track the progress of the review.
## Automated Checks
Last check on commit cc51de6fac70261acfaa5bb2d1c86ae3a704ae45 (Mon Sep 27 10:09:47 UTC 2021)
**Warnings:**
* **1 pom.xml files were touched**: Check for build and licensing issues.
* No documentation files were touched! Remember to keep the Flink docs up to date!
<sub>Mention the bot in a comment to re-run the automated checks.</sub>
## Review Progress
* ❓ 1. The [description] looks good.
* ❓ 2. There is [consensus] that the contribution should go into to Flink.
* ❓ 3. Needs [attention] from.
* ❓ 4. The change fits into the overall [architecture].
* ❓ 5. Overall code [quality] is good.
Please see the [Pull Request Review Guide](https://flink.apache.org/contributing/reviewing-prs.html) for a full explanation of the review process.<details>
The Bot is tracking the review progress through labels. Labels are applied according to the order of the review items. For consensus, approval by a Flink committer of PMC member is required <summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot approve description` to approve one or more aspects (aspects: `description`, `consensus`, `architecture` and `quality`)
- `@flinkbot approve all` to approve all aspects
- `@flinkbot approve-until architecture` to approve everything until `architecture`
- `@flinkbot attention @username1 [@username2 ..]` to require somebody's attention
- `@flinkbot disapprove architecture` to remove an approval you gave earlier
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718240545
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
Review comment:
Can do but the class is already package-private, so is it necessary?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716710209
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,265 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriterITCase.class);
+
+ @Container
+ private static final ElasticsearchContainer ES_CONTAINER =
+ new ElasticsearchContainer(DockerImageName.parse(DockerImageVersions.ELASTICSEARCH_7))
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ private RestHighLevelClient client;
+ private TestContext context;
+ private MetricListener metricListener;
+
+ @BeforeEach
+ void setUp() {
+ metricListener = new MetricListener();
+ client =
+ new RestHighLevelClient(
+ RestClient.builder(HttpHost.create(ES_CONTAINER.getHttpHostAddress())));
+ context = new TestContext(client);
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+
+ @Test
+ void testWriteOnBulkFlush() throws Exception {
+ final String index = "test-bulk-flush-without-checkpoint";
+ final int flushAfterNActions = 5;
+ final BulkProcessorConfig bulkProcessorConfig =
+ new BulkProcessorConfig(flushAfterNActions, -1, -1, null, 0, 0);
+
+ try (final ElasticsearchWriter<Tuple2<Integer, String>> writer =
+ createWriter(index, false, bulkProcessorConfig)) {
+ writer.write(Tuple2.of(1, buildMessage(1)), null);
+ writer.write(Tuple2.of(2, buildMessage(2)), null);
+ writer.write(Tuple2.of(3, buildMessage(3)), null);
+ writer.write(Tuple2.of(4, buildMessage(4)), null);
+
+ // Ignore flush on checkpoint
+ writer.prepareCommit(true);
+ writer.prepareCommit(false);
Review comment:
If the method is called with `true` it usually signalizes some sort of special final flushing i.e. for batch execution when the job finishes. I just wanted to show that none of the calls neither with flush nor without emit records.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718199624
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
Good that we have done the same thing in the Kafka docs :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718202041
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
Review comment:
Yes, do we need `@Internal` for package-private classes?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718239254
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
+ *
+ * @param deliveryGuarantee which describes the record emission behaviour
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
+ checkState(
+ deliveryGuarantee != DeliveryGuarantee.EXACTLY_ONCE,
+ "Elasticsearch sink does not support the EXACTLY_ONCE guarantee.");
+ this.deliveryGuarantee = checkNotNull(deliveryGuarantee);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param numMaxActions the maximum number of actions to buffer per bulk request.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxActions(int numMaxActions) {
+ checkState(
+ numMaxActions == -1 || numMaxActions > 0,
+ "Max number of buffered actions must be larger than 0.");
+ this.bulkFlushMaxActions = numMaxActions;
+ return this;
+ }
+
+ /**
+ * Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
+ * disable it.
+ *
+ * @param maxSizeMb the maximum size of buffered actions, in mb.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushMaxSizeMb(int maxSizeMb) {
+ checkState(
+ maxSizeMb == -1 || maxSizeMb > 0,
+ "Max size of buffered actions must be larger than 0.");
+ this.bulkFlushMaxMb = maxSizeMb;
+ return this;
+ }
+
+ /**
+ * Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
+ *
+ * @param intervalMillis the bulk flush interval, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushInterval(long intervalMillis) {
+ checkState(
+ intervalMillis == -1 || intervalMillis >= 0,
+ "Interval (in milliseconds) between each flush must be larger than "
+ + "or equal to 0.");
+ this.bulkFlushInterval = intervalMillis;
+ return this;
+ }
+
+ /**
+ * Sets the type of back of to use when flushing bulk requests.
+ *
+ * @param flushBackoffType the backoff type to use.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffType(
+ ElasticsearchSinkBase.FlushBackoffType flushBackoffType) {
+ this.bulkFlushBackoffType = checkNotNull(flushBackoffType);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
+ *
+ * @param maxRetries the maximum number of retries for a backoff attempt when flushing bulk
+ * requests
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffRetries(int maxRetries) {
+ checkState(maxRetries > 0, "Max number of backoff attempts must be larger than 0.");
+ this.bulkFlushBackoffRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets the amount of delay between each backoff attempt when flushing bulk requests, in
+ * milliseconds.
+ *
+ * @param delayMillis the amount of delay between each backoff attempt when flushing bulk
+ * requests, in milliseconds.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public ElasticsearchSinkBuilder<IN> setBulkFlushBackoffDelay(long delayMillis) {
+ checkState(
+ delayMillis >= 0,
+ "Delay (in milliseconds) between each backoff attempt must be larger "
+ + "than or equal to 0.");
+ this.bulkFlushBackOffDelay = delayMillis;
+ return this;
+ }
Review comment:
Definitely 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 7387899a9a9db33b69a0eaa0563c5c80f6209584 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
}, {
"hash" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24776",
"triggerID" : "c12f95b1907cb375af2f3da22d59cba25e7fe01c",
"triggerType" : "PUSH"
}, {
"hash" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "9b43b01e84d828b0dd6f1f121ffc736df8760743",
"triggerType" : "PUSH"
}, {
"hash" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24796",
"triggerID" : "bee7c870c5607a28c2d2a652601e8efa5b92458d",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 9b43b01e84d828b0dd6f1f121ffc736df8760743 UNKNOWN
* bee7c870c5607a28c2d2a652601e8efa5b92458d Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24796)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r723035131
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * Flink Sink to insert or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure, it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts. These
+ * additional requests may cause inconsistent data in ElasticSearch right after the restart,
+ * but eventually everything will be consistent again.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchEmitter<? super IN> processor;
Review comment:
I hope I caught all the processors this time ...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 70e07383ac68b4c3235a89ddd05bd0925d317753 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654)
* c80cf0c61e4587125dcf9e1bce2fff8c40928255 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* c80cf0c61e4587125dcf9e1bce2fff8c40928255 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r719487292
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/test/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriterITCase.java
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.metrics.testutils.MetricListener;
+import org.apache.flink.runtime.metrics.groups.InternalSinkWriterMetricGroup;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.util.DockerImageVersions;
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.TestLogger;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.apache.http.HttpHost;
+import org.elasticsearch.ElasticsearchStatusException;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.elasticsearch.ElasticsearchContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.apache.flink.connector.elasticsearch.sink.TestContext.buildMessage;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitUntilCondition;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Tests for {@link ElasticsearchWriter}. */
+@Testcontainers
+class ElasticsearchWriterITCase extends TestLogger {
Review comment:
Fair point. If we move flushing out in a building block, we would then take that ITCase with it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] AHeise commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
AHeise commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r723012465
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSink.java
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink.Committer;
+import org.apache.flink.api.connector.sink.GlobalCommitter;
+import org.apache.flink.api.connector.sink.Sink;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.http.HttpHost;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * Flink Sink to insert or update data in an Elasticsearch index. The sink supports the following
+ * delivery guarantees.
+ *
+ * <ul>
+ * <li>{@link DeliveryGuarantee#NONE} does not provide any guarantees: actions are flushed to
+ * Elasticsearch only depending on the configurations of the bulk processor. In case of a
+ * failure, it might happen that actions are lost if the bulk processor still has buffered
+ * actions.
+ * <li>{@link DeliveryGuarantee#AT_LEAST_ONCE} on a checkpoint the sink will wait until all
+ * buffered actions are flushed to and acknowledged by Elasticsearch. No actions will be lost
+ * but actions might be sent to Elasticsearch multiple times when Flink restarts. These
+ * additional requests may cause inconsistent data in ElasticSearch right after the restart,
+ * but eventually everything will be consistent again.
+ * </ul>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ * @see ElasticsearchSinkBuilder on how to construct a ElasticsearchSink
+ */
+@PublicEvolving
+public class ElasticsearchSink<IN> implements Sink<IN, Void, Void, Void> {
+
+ private final List<HttpHost> hosts;
+ private final ElasticsearchEmitter<? super IN> processor;
Review comment:
Here as well. Just grep processor and double-check.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on the unified sink (FLIP-143)
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24576",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
}, {
"hash" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24620",
"triggerID" : "6bd214da5083a1b9708f38f1138b492ea2b76bb4",
"triggerType" : "PUSH"
}, {
"hash" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24623",
"triggerID" : "7387899a9a9db33b69a0eaa0563c5c80f6209584",
"triggerType" : "PUSH"
}, {
"hash" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24654",
"triggerID" : "70e07383ac68b4c3235a89ddd05bd0925d317753",
"triggerType" : "PUSH"
}, {
"hash" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24713",
"triggerID" : "c80cf0c61e4587125dcf9e1bce2fff8c40928255",
"triggerType" : "PUSH"
}, {
"hash" : "d3a18adc8f5711046c47496d25374f4be4279520",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766",
"triggerID" : "d3a18adc8f5711046c47496d25374f4be4279520",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* d3a18adc8f5711046c47496d25374f4be4279520 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24766)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #17363:
URL: https://github.com/apache/flink/pull/17363#issuecomment-927758743
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24530",
"triggerID" : "cc51de6fac70261acfaa5bb2d1c86ae3a704ae45",
"triggerType" : "PUSH"
}, {
"hash" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542",
"triggerID" : "ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e",
"triggerType" : "PUSH"
}, {
"hash" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* ba7e72b52bc72ae96c5db7211d80807e0d5fcb8e Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=24542)
* 5c90ef7cfc8d835f3010fb5fcd38f7889d64ef72 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718404527
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchWriter.java
##########
@@ -0,0 +1,326 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink.SinkWriter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.action.DocWriteRequest;
+import org.elasticsearch.action.bulk.BackoffPolicy;
+import org.elasticsearch.action.bulk.BulkItemResponse;
+import org.elasticsearch.action.bulk.BulkProcessor;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestClientBuilder;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.common.unit.ByteSizeUnit;
+import org.elasticsearch.common.unit.ByteSizeValue;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.rest.RestStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+class ElasticsearchWriter<IN> implements SinkWriter<IN, Void, Void> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class);
+
+ private final ElasticsearchProcessor<IN> processor;
+ private final MailboxExecutor mailboxExecutor;
+ private final boolean flushOnCheckpoint;
+ private final BulkProcessor bulkProcessor;
+ private final RestHighLevelClient client;
+ private final RequestIndexer requestIndexer;
+ private final Counter numBytesOutCounter;
+
+ private long pendingActions = 0;
+ private boolean checkpointInProgress = false;
+ private volatile long lastSendTime = 0;
+ private volatile long receiveTime = Long.MAX_VALUE;
+ private volatile boolean closed = false;
+
+ /**
+ * Constructor creating an elasticsearch writer.
+ *
+ * <p>It will throw a {@link RuntimeException} if {@link ElasticsearchProcessor#open()} fails.
+ *
+ * @param hosts the reachable elasticsearch cluster nodes
+ * @param processor converting incoming records to elasticsearch actions
+ * @param flushOnCheckpoint if true all until now received records are flushed after every
+ * checkpoint
+ * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link
+ * BulkProcessor}
+ * @param networkClientConfig describing properties of the network connection used to connect to
+ * the elasticsearch cluster
+ * @param metricGroup for the sink writer
+ * @param mailboxExecutor Flink's mailbox executor
+ */
+ public ElasticsearchWriter(
+ List<HttpHost> hosts,
+ ElasticsearchProcessor<IN> processor,
+ boolean flushOnCheckpoint,
+ BulkProcessorConfig bulkProcessorConfig,
+ NetworkClientConfig networkClientConfig,
+ SinkWriterMetricGroup metricGroup,
+ MailboxExecutor mailboxExecutor) {
+ this.processor = checkNotNull(processor);
+ this.flushOnCheckpoint = flushOnCheckpoint;
+ this.mailboxExecutor = checkNotNull(mailboxExecutor);
+ this.client =
+ new RestHighLevelClient(
+ configureRestClientBuilder(
+ RestClient.builder(hosts.toArray(new HttpHost[0])),
+ networkClientConfig));
+ this.bulkProcessor =
+ configureBulkProcessor(
+ BulkProcessor.builder(
+ (bulkRequest, bulkResponseActionListener) ->
+ client.bulkAsync(
+ bulkRequest,
+ RequestOptions.DEFAULT,
+ bulkResponseActionListener),
+ new BulkListener()),
+ bulkProcessorConfig);
+ this.requestIndexer = new DefaultRequestIndexer();
+ checkNotNull(metricGroup);
+ metricGroup.setCurrentSendTimeGauge(() -> receiveTime - lastSendTime);
+ this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter();
+ try {
+ processor.open();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to open the ElasticsearchProcessor", e);
+ }
+ }
+
+ @Override
+ public void write(IN element, Context context) throws IOException, InterruptedException {
+ // do not allow new bulk writes until all actions are flushed
+ while (checkpointInProgress) {
+ mailboxExecutor.yield();
+ }
+ processor.process(element, context, requestIndexer);
+ }
+
+ @Override
+ public List<Void> prepareCommit(boolean flush) throws IOException, InterruptedException {
+ checkpointInProgress = true;
+ while (pendingActions != 0) {
+ bulkProcessor.flush();
+ LOG.info("Waiting for the response of {} pending actions.", pendingActions);
+ mailboxExecutor.yield();
+ }
+ checkpointInProgress = false;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public void close() throws Exception {
+ closed = true;
+ processor.close();
+ client.close();
+ }
+
+ private static RestClientBuilder configureRestClientBuilder(
+ RestClientBuilder builder, NetworkClientConfig networkClientConfig) {
+ if (networkClientConfig.getConnectionPathPrefix() != null) {
+ builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix());
+ }
+ if (networkClientConfig.getPassword() != null
+ && networkClientConfig.getUsername() != null) {
+ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(
+ networkClientConfig.getUsername(), networkClientConfig.getPassword()));
+ builder.setHttpClientConfigCallback(
+ httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
+ }
+ return builder;
+ }
+
+ private static BulkProcessor configureBulkProcessor(
+ BulkProcessor.Builder builder, BulkProcessorConfig bulkProcessorConfig) {
+ // This makes flush() blocking
+ builder.setConcurrentRequests(0);
+
+ if (bulkProcessorConfig.getBulkFlushMaxActions() != -1) {
+ builder.setBulkActions(bulkProcessorConfig.getBulkFlushMaxActions());
+ }
+
+ if (bulkProcessorConfig.getBulkFlushMaxMb() != -1) {
+ builder.setBulkSize(
+ new ByteSizeValue(bulkProcessorConfig.getBulkFlushMaxMb(), ByteSizeUnit.MB));
+ }
+
+ if (bulkProcessorConfig.getBulkFlushInterval() != -1) {
+ builder.setFlushInterval(new TimeValue(bulkProcessorConfig.getBulkFlushInterval()));
+ }
+
+ BackoffPolicy backoffPolicy;
+ if (bulkProcessorConfig.getFlushBackoffType() != null) {
+ final TimeValue backoffDelay =
+ new TimeValue(bulkProcessorConfig.getBulkFlushBackOffDelay());
+ final int maxRetryCount = bulkProcessorConfig.getBulkFlushBackoffRetries();
+ switch (bulkProcessorConfig.getFlushBackoffType()) {
+ case CONSTANT:
+ backoffPolicy = BackoffPolicy.constantBackoff(backoffDelay, maxRetryCount);
+ break;
+ case EXPONENTIAL:
+ default:
+ backoffPolicy = BackoffPolicy.exponentialBackoff(backoffDelay, maxRetryCount);
+ }
+ } else {
+ backoffPolicy = BackoffPolicy.noBackoff();
+ }
+ builder.setBackoffPolicy(backoffPolicy);
+
+ return builder.build();
+ }
+
+ private class BulkListener implements BulkProcessor.Listener {
+
+ @Override
+ public void beforeBulk(long executionId, BulkRequest request) {
+ LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions());
+ lastSendTime = System.currentTimeMillis();
+ numBytesOutCounter.inc(request.estimatedSizeInBytes());
+ }
+
+ @Override
+ public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ receiveTime = System.currentTimeMillis();
+ // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint
+ // configured or shutdown without a final
+ // checkpoint) the mailbox might already be shutdown, so we should not enqueue any
+ // actions.
+ if (isClosed()) {
+ return;
+ }
+ mailboxExecutor.execute(
+ () -> {
+ if (!response.hasFailures() && flushOnCheckpoint) {
+ pendingActions -= request.numberOfActions();
+ return;
+ }
+
+ for (int i = 0; i < response.getItems().length; i++) {
+ final BulkItemResponse itemResponse = response.getItems()[i];
+ if (!itemResponse.isFailed()) {
+ continue;
+ }
+ final Throwable failure = itemResponse.getFailure().getCause();
+ if (failure == null) {
+ continue;
+ }
+ final RestStatus restStatus = itemResponse.getFailure().getStatus();
+ final DocWriteRequest<?> actionRequest = request.requests().get(i);
+
+ if (restStatus == null) {
+ throw new FlinkRuntimeException(
Review comment:
Good idea 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718219633
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct a {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
Review comment:
If you do not specify anything for the bulk processor it will not emit anything except on a checkpoint.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r716708288
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/ElasticsearchSinkBuilder.java
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.DeliveryGuarantee;
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+import org.apache.flink.util.InstantiationUtil;
+
+import org.apache.http.HttpHost;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Builder to construct {@link ElasticsearchSink}.
+ *
+ * <p>The following example shows the minimum setup to create a ElasticsearchSink that submits
+ * actions on checkpoint.
+ *
+ * <pre>{@code
+ * Elasticsearch<String> sink = Elasticsearch
+ * .builder()
+ * .setHosts(MY_ELASTICSEARCH_HOSTS)
+ * .setProcessor(MY_ELASTICSEARCH_PROCESSOR)
+ * .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
+ * .build();
+ * }</pre>
+ *
+ * @param <IN> type of the records converted to Elasticsearch actions
+ */
+@PublicEvolving
+public class ElasticsearchSinkBuilder<IN> {
+
+ private int bulkFlushMaxActions = -1;
+ private int bulkFlushMaxMb = -1;
+ private long bulkFlushInterval = -1;
+ private ElasticsearchSinkBase.FlushBackoffType bulkFlushBackoffType;
+ private int bulkFlushBackoffRetries = -1;
+ private long bulkFlushBackOffDelay = -1;
+ private DeliveryGuarantee deliveryGuarantee = DeliveryGuarantee.NONE;
+ private List<HttpHost> hosts;
+ private ElasticsearchProcessor<? extends IN> processor;
+ private String username;
+ private String password;
+ private String connectionPathPrefix;
+
+ ElasticsearchSinkBuilder() {}
+
+ /**
+ * Sets the hosts where the Elasticsearch cluster nodes are reachable.
+ *
+ * @param hosts http addresses describing the node locations
+ */
+ public ElasticsearchSinkBuilder<IN> setHosts(HttpHost... hosts) {
+ checkNotNull(hosts);
+ checkState(hosts.length > 0, "Hosts cannot be empty.");
+ this.hosts = Arrays.asList(hosts);
+ return this;
+ }
+
+ /**
+ * Sets the processor which is invoked on every record to convert it to Elasticsearch actions.
+ *
+ * @param processor to process records into Elasticsearch actions.
+ * @return {@link ElasticsearchSinkBuilder}
+ */
+ public <T extends IN> ElasticsearchSinkBuilder<T> setProcessor(
+ ElasticsearchProcessor<? extends T> processor) {
+ checkNotNull(processor);
+ checkState(
+ InstantiationUtil.isSerializable(processor),
+ "The elasticsearch processor must be serializable.");
+ final ElasticsearchSinkBuilder<T> self = self();
+ self.processor = processor;
+ return self;
+ }
+
+ /**
+ * Sets the wanted the {@link DeliveryGuarantee}. The default delivery guarantee is {@link
+ * #deliveryGuarantee}.
Review comment:
The javadoc refers via the link to a variable named `deliveryGuarantee` holding the default value :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] fapaul commented on a change in pull request #17363: [FLINK-24324][connectors/elasticsearch] Add Elasticsearch 7 sink based on FLIP-143
Posted by GitBox <gi...@apache.org>.
fapaul commented on a change in pull request #17363:
URL: https://github.com/apache/flink/pull/17363#discussion_r718202530
##########
File path: flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/connector/elasticsearch/sink/BulkProcessorConfig.java
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.flink.connector.elasticsearch.sink;
+
+import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkBase;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+
+class BulkProcessorConfig implements Serializable {
+
+ private final int bulkFlushMaxActions;
+ private final int bulkFlushMaxMb;
+ private final long bulkFlushInterval;
+ @Nullable private final ElasticsearchSinkBase.FlushBackoffType flushBackoffType;
Review comment:
What exactly do you mean here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org