You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "nicusX (via GitHub)" <gi...@apache.org> on 2023/10/22 07:59:13 UTC
[PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
nicusX opened a new pull request, #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1
## Purpose of the change
DataStream API implementation
Also includes:
* AMP Request Signed implementation ([FLINK-33141](https://issues.apache.org/jira/browse/FLINK-33141))
* Sample application, running on Amazon Managed Service for Apache Flink and writing to Amazon Managed Prometheus
## Verifying this change
* Unit tests
* Run included sample application on Amazon Managed Service for Apache Flink
### Significant changes
(Please check any boxes [x] if the answer is "yes" )
* [x] Dependencies have been added or upgraded
* [x] Public API has been changed (Public API is any class annotated with @Public(Evolving))
* [x] Serializers have been changed
* [x] New feature has been introduce
* If yes, how is this documented? JavaDocs and README.md
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757529466
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/RequestHeaderTestUtil.java:
##########
@@ -0,0 +1,21 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
License headers
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489791182
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(awsRegion), "Missing or blank AMP workspace region");
+ Preconditions.checkNotNull(
+ StringUtils.isNotBlank(remoteWriteUrl),
+ "Missing or blank AMP workspace remote-write URL");
+ this.awsRegion = awsRegion;
+ try {
+ this.remoteWriteUrl = new URL(remoteWriteUrl);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException(
+ "Invalid AMP remote-write URL: " + remoteWriteUrl, e);
+ }
+ }
+
+ /**
+ * Add the additional Http request headers required by Amazon Managed Prometheus:
+ * 'x-amz-content-sha256', 'Host', 'X-Amz-Date', 'x-amz-security-token' and 'Authorization`.
+ *
+ * @param requestHeaders original Http request headers. It must be mutable. For efficiency, any
+ * new header is added to the map, instead of making a copy.
+ * @param requestBody request body, already compressed
+ */
+ @Override
+ public void addSignatureHeaders(Map<String, String> requestHeaders, byte[] requestBody) {
+ byte[] contentHash = AWS4SignerBase.hash(requestBody);
+ String contentHashString = BinaryUtils.toHex(contentHash);
+ requestHeaders.put(
+ "x-amz-content-sha256",
+ contentHashString); // this header must be included before generating the
+ // Authorization header
+
+ DefaultAWSCredentialsProviderChain credsChain = new DefaultAWSCredentialsProviderChain();
Review Comment:
Actually, I reverted the change. Just passing a credentials provider instance obviously doesn't work, not being serializable.
Making the credentials provider customisable would mean either:
1. Copying the implementation of `org.apache.flink.connector.aws.util.AWSGeneralUtil` from `flink-connector-aws-base` and using it to create the credential provider at runtime, based on configuration, or
2. Including `flink-connector-aws-base` as a dependency. But this would bring in a number of transitive dependencies that are not used. The only AWS SDK dependencies in this connector are in this signer, and only to get the credentials. Also, `flink-connector-aws-base` uses sdk2, while this signer uses sdk1. We discussed with @hlteoh37 that porting to sdk2 is nice to have but not a priority for the first release.
Considering `DefaultAWSCredentialsProviderChain` will already cover almost every possible authentication scenario when a Flink application will be writing to AMP, I would not consider configurable credentials provider a priority for the first release, and wait if any actual user will need it.
Happy to discuss.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501895815
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
+
+ private static final ContentType CONTENT_TYPE = ContentType.create("application/x-protobuf");
+
+ public static final String DEFAULT_USER_AGENT = "Flink-Prometheus";
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusRequestSigner requestSigner;
+
+ private final Map<String, String> fixedHeaders;
+
+ public PrometheusRemoteWriteHttpRequestBuilder(
+ String prometheusRemoteWriteUrl,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent) {
+ Preconditions.checkNotNull(httpUserAgent, "User-Agent not specified");
+
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ this.requestSigner = requestSigner;
+ this.fixedHeaders =
+ Map.of(
+ HttpHeaders.CONTENT_ENCODING,
+ "snappy",
+ "X-Prometheus-Remote-Write-Version",
+ "0.1.0",
+ HttpHeaders.USER_AGENT,
+ httpUserAgent);
+ }
+
+ public SimpleHttpRequest buildHttpRequest(byte[] httpRequestBody) {
+ Map<String, String> headers = new HashMap<>(fixedHeaders);
+ if (requestSigner != null) {
+ requestSigner.addSignatureHeaders(headers, httpRequestBody);
+ }
+
+ var builder =
Review Comment:
Default target java version for connectors is 8, is java 11 features 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597488570
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
+ * Protobuf-serialized representation of a {@link Types.TimeSeries TimeSeries}. In this
+ * implementation SIZEn is the size of the Protobuf serialization, in bytes, that does not match
+ * the "size" of a {@link RequestEntryWrapper}.
+ *
+ * @param bufferedRequestState The buffered request state to be serialized
+ * @return serialized buffered request state
+ * @throws IOException
+ */
+ @Override
+ public byte[] serialize(BufferedRequestState<Types.TimeSeries> bufferedRequestState)
+ throws IOException {
+ Collection<RequestEntryWrapper<Types.TimeSeries>> bufferState =
+ bufferedRequestState.getBufferedRequestEntries();
+
+ try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final DataOutputStream out = new DataOutputStream(baos)) {
+
+ out.writeLong(DATA_IDENTIFIER); // DATA_IDENTIFIER
+ out.writeInt(bufferState.size()); // NUM_OF_ELEMENTS
+
+ for (RequestEntryWrapper<Types.TimeSeries> wrapper : bufferState) {
+ // In the serialized state we write the size of the serialized representation,
+ // rather than the size
+ // held in RequestEntryWrapper, that is the output of
+ // AsyncSinkWriter.getSizeInBytes()
+ long requestEntrySize =
+ RequestEntrySizeUtils.requestSerializedSize(wrapper.getRequestEntry());
+ out.writeLong(requestEntrySize); // SIZEn
+ serializeRequestToStream(wrapper.getRequestEntry(), out); // REQUESTn
+ }
+
+ return baos.toByteArray();
+ }
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>See {@link PrometheusStateSerializer#serialize(BufferedRequestState)} for more details.
+ *
+ * @param version The version in which the data was serialized
+ * @param serialized The serialized data
+ * @return a buffered request state wrapping the deserialized time-series.
+ * @throws IOException
+ */
+ @Override
+ public BufferedRequestState<Types.TimeSeries> deserialize(int version, byte[] serialized)
+ throws IOException {
+ try (final ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
+ final DataInputStream in = new DataInputStream(bais)) {
+
+ validateIdentifier(in); // DATA_IDENTIFIER
+ int numberOfElements = in.readInt(); // NUM_OF_ELEMENTS
+
+ List<RequestEntryWrapper<Types.TimeSeries>> serializedState = new ArrayList<>();
+ for (int i = 0; i < numberOfElements; i++) {
+ // This is the size of an request-entry in the serialized state
+ long requestSerializedSize = in.readLong(); // SIZEn - the serialized size
Review Comment:
as above
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597478707
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/prometheus/Remote.java:
##########
@@ -0,0 +1,6661 @@
+/*
Review Comment:
I think we discussed this.
Generating the Java classes from proto cannot be done with a pure Java solution included in the project.
It requires ProtoBuf binaries. (e.g. see https://github.com/javiroman/jremotewrite/blob/e1b5d9865d42254b32f2da6ddfd6956569577601/pom.xml#L210)
I am adding the *.proto file for reference and a section to the README to explain
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1467925863
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37).append(name).append(value).toHashCode();
+ }
+ }
+
+ /** A single Sample. */
+ public static class Sample implements Serializable {
Review Comment:
implemented
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1487883477
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
+
+ ParameterTool applicationParameters = ParameterTool.fromArgs(args);
+
+ // Prometheus remote-write URL
+ String prometheusRemoteWriteUrl = applicationParameters.get("prometheusRemoteWriteUrl");
+ LOGGER.info("Prometheus URL:{}", prometheusRemoteWriteUrl);
+
+ // Optionally configure Amazon Managed Prometheus request signer
+ PrometheusRequestSigner requestSigner = null;
+ String ampAWSRegion = applicationParameters.get("awsRegion");
+ if (ampAWSRegion != null) {
+ requestSigner =
+ new AmazonManagedPrometheusWriteRequestSigner(
+ prometheusRemoteWriteUrl, ampAWSRegion);
+ LOGGER.info(
+ "Enable Amazon Managed Prometheus request-signer, region: {}", ampAWSRegion);
+ }
+
+ // Configure data generator
+ int generatorMinSamplesPerTimeSeries = 1;
+ int generatorMaxSamplesPerTimeSeries = 10;
+ int generatorNumberOfDummyInstances = 5;
Review Comment:
Reworked the random data generator to generate a configurable random number of metrics (`M0000`, `M00001`...) for a configurable random number of sources (`SourceID` = `S0000000000`, `S0000000001`...).
Removed confusing references to "instances", "CPU" and "Memory"
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597488524
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
+ * Protobuf-serialized representation of a {@link Types.TimeSeries TimeSeries}. In this
+ * implementation SIZEn is the size of the Protobuf serialization, in bytes, that does not match
Review Comment:
As above, it means "SIZE<n>".
Clarified the comment
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597412205
##########
pom.xml:
##########
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-parent</artifactId>
+ <version>1.0.0</version>
+ </parent>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <name>Flink Prometheus</name>
+ <modules>
+ <module>prometheus-connector</module>
+ <module>amp-request-signer</module>
+ <module>example-datastream-job</module>
+ </modules>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+ <flink.version>1.17.0</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ <aws.sdkv1.version>1.12.570</aws.sdkv1.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk-bom</artifactId>
+ <version>${aws.sdkv1.version}</version>
Review Comment:
Correction: it is still required. But I am moving any reference to AWS SDK dependency to the AMP Signer module.
This is used to sign the AMP request only. There is no working example using SDK2 in Java. We managed to make it work with SDKv1. I'd suggest to keep it as-is for the moment and consider upgrading the signer in a future version.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1466739430
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
+ }
+
+ // Never re-queue requests
+ requestResult.accept(Collections.emptyList());
+ }
+
+ @Override
+ public void failed(Exception ex) {
+ LOG.warn(
+ "Exception executing the remote-write (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount,
+ ex);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
+
+ @Override
+ public void cancelled() {
+ LOG.warn(
+ "Write request execution cancelled (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
Review Comment:
Done: always throws an exception on cancelled
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1466738855
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
Review Comment:
Modified the behaviour so that, by default, it will throw an exception and stop the job on any unrecoverable condition. Optionally, the user can decide not to block the job, but drop data and continue, selectively for three separate conditions:
1. Max retry exceeded
2. Non-retriable error reported
3. Http client I/O error
When the Http request is cancelled, an exception is always thrown (not configurable)
The default max retry is now 100, ~ 500 sec with the default backoff timing
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1466268497
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int maxInFlightRequest = 1;
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples())
+ .orElse(getMaxBatchSizeInSamples()); // By default, set max record size to
+ // max batch size (in samples)
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs);
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ /// Disable setting maxBatchSize, maxBatchSizeInBytes, and maxRecordSizeInBytes directly
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSize(int maxBatchSize) {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxBatchSizeInBytes is not supported by this sink");
Review Comment:
Added comments to all disabled parameters, explaining what to use instead
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1469810341
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
Review Comment:
Moved the callback to a separate class and created a specific test.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486605618
##########
example-datastream-job/pom.xml:
##########
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : Sample Application</name>
+ <artifactId>example-datastream-job</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.17.2</flink.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- Amazon Managed Prometheus signed (remove if not used) -->
+ <dependency>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- Apache Flink dependencies -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-streaming-java</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-clients</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j-impl</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-api</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-core</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+
+ <!-- For Flink local development -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-runtime-web</artifactId>
Review Comment:
Removed the Flink dashboard when running locally. Removed this dependency, that was used for 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501903046
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ */
+ protected static String getCanonicalRequest(
+ URL endpoint,
+ String httpMethod,
+ String queryParameters,
+ String canonicalizedHeaderNames,
+ String canonicalizedHeaders,
+ String bodyHash) {
+ String canonicalRequest =
+ httpMethod
+ + "\n"
+ + getCanonicalizedResourcePath(endpoint)
+ + "\n"
+ + queryParameters
+ + "\n"
+ + canonicalizedHeaders
+ + "\n"
+ + canonicalizedHeaderNames
+ + "\n"
+ + bodyHash;
+ return canonicalRequest;
+ }
+
+ /** Returns the canonicalized resource path for the service endpoint. */
+ protected static String getCanonicalizedResourcePath(URL endpoint) {
+ if (endpoint == null) {
+ return "/";
+ }
+ String path = endpoint.getPath();
+ if (path == null || path.isEmpty()) {
+ return "/";
+ }
+
+ String encodedPath = urlEncode(path, true);
+ if (encodedPath.startsWith("/")) {
+ return encodedPath;
+ } else {
+ return "/".concat(encodedPath);
+ }
+ }
+
+ /**
+ * Examines the specified query string parameters and returns a canonicalized form.
+ *
+ * <p>The canonicalized query string is formed by first sorting all the query string parameters,
+ * then URI encoding both the key and value and then joining them, in order, separating key
+ * value pairs with an '&'.
+ *
+ * @param parameters The query string parameters to be canonicalized.
+ * @return A canonicalized form for the specified query string parameters.
+ */
+ public static String getCanonicalizedQueryString(Map<String, String> parameters) {
+ if (parameters == null || parameters.isEmpty()) {
+ return "";
+ }
+
+ SortedMap<String, String> sorted = new TreeMap<String, String>();
+
+ Iterator<Map.Entry<String, String>> pairs = parameters.entrySet().iterator();
+ while (pairs.hasNext()) {
+ Map.Entry<String, String> pair = pairs.next();
+ String key = pair.getKey();
+ String value = pair.getValue();
+ sorted.put(urlEncode(key, false), urlEncode(value, false));
+ }
+
+ StringBuilder builder = new StringBuilder();
+ pairs = sorted.entrySet().iterator();
+ while (pairs.hasNext()) {
+ Map.Entry<String, String> pair = pairs.next();
+ builder.append(pair.getKey());
+ builder.append("=");
+ builder.append(pair.getValue());
+ if (pairs.hasNext()) {
+ builder.append("&");
+ }
+ }
+
+ return builder.toString();
+ }
+
+ protected static String getStringToSign(
+ String scheme,
+ String algorithm,
+ String dateTime,
+ String scope,
+ String canonicalRequest) {
+ String stringToSign =
+ scheme
+ + "-"
+ + algorithm
+ + "\n"
+ + dateTime
+ + "\n"
+ + scope
+ + "\n"
+ + BinaryUtils.toHex(hash(canonicalRequest));
+ return stringToSign;
+ }
+
+ /** Hashes the string contents (assumed to be UTF-8) using the SHA-256 algorithm. */
+ public static byte[] hash(String text) {
+ try {
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(text.getBytes("UTF-8"));
+ return md.digest();
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "Unable to compute hash while signing request: " + e.getMessage(), e);
Review Comment:
Can you replace this with a more specific exception? Same comment to all other `RuntimeException` usages
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501905509
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ *
+ * @return
Review Comment:
Discussed offline, my comment was about including _both_ generated version and source `*.proto` with a way to regenerate code.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501900305
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/RequestEntrySizeUtils.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.util.Collection;
+
+/** Collection of methods to calculate the sink RequestEntry "size". */
+public class RequestEntrySizeUtils {
+
+ /**
+ * Size of a request entry (a {@link Types.TimeSeries time-series}) for the purpose of batching.
+ * Count the number of {@link Types.Sample samples}
+ *
+ * @param requestEntry a time-series
+ * @return number of Samples in the TimeSeries
+ */
+ public static long requestSizeForBatching(Types.TimeSeries requestEntry) {
+ return requestEntry.getSamplesCount();
+ }
+
+ /**
+ * Serialized size of a request entry {@link Types.TimeSeries TimeSeries}: the number of bytes
+ * of the protobuf- serialized representation of the TimeSeries.
+ *
+ * @param requestEntry a time-series
+ * @return number of bytes
+ */
+ public static long requestSerializedSize(Types.TimeSeries requestEntry) {
+ return requestEntry.getSerializedSize();
+ }
+
+ /**
+ * Count the number of {@link Types.Sample samples} in a collection of {@link Types.TimeSeries
+ * time-series} (a batch).
+ *
+ * @param requestEntries collection of time-series
+ * @return number of samples
+ */
+ public static long countSamples(Collection<Types.TimeSeries> requestEntries) {
+ return requestEntries.stream()
+ .mapToLong(RequestEntrySizeUtils::requestSizeForBatching)
+ .sum();
Review Comment:
Should this be replaced with a loop?
https://flink.apache.org/how-to-contribute/code-style-and-quality-java/#java-streams
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 merged PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1600156895
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
Review Comment:
Can we move this to an integ test? Adding it as a separate module would make releases more difficult.
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
Review Comment:
nit: can we name this `flink-connector-prometheus` to follow the repo / artifact name?
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
+* [Amazon Managed Prometheus Request Signer](./amp-request-signer): Implementation of request signer for Amazon Managed Prometheus (AMP)
Review Comment:
nit: Should we name this as `request-signer-amp` - this might read a little nicer
##########
amp-request-signer/README.md:
##########
@@ -0,0 +1,31 @@
+## Request Signer for Amazon Managed Prometheus (AMP)
+
+Request signer implementation for Amazon Managed Prometheus (AMP)
+
+The signer retrieves AWS credentials using `com.amazonaws.auth.DefaultAWSCredentialsProviderChain` and automatically
+supports session credentials.
+
+The Flink application requires `RemoteWrite` permissions to the AMP workspace (e.g. `AmazonPromethusRemoteWriteAccess`
+policy).
+
+### Sample usage
+
+To enable request signing for Amazon Managed Prometheus, and instance of `AmazonManagedPrometheusWriteRequestSigner`
+must
Review Comment:
nit: why is this on its own line?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2156438875
Addressed the latest comments and ported AMP signer to AWS SDKv2 (!)
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632194645
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
+* [Amazon Managed Prometheus Request Signer](./amp-request-signer): Implementation of request signer for Amazon Managed Prometheus (AMP)
Review Comment:
It was actually requested earlier in the PR to make the module name fully qualified, prepending `flink-connector-prometheus-`.
I am renaming the module to `flink-connector-prometheus-request-signer-amp` to make it fully qualified and retaining the logical order, general to specific
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501901955
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/PrometheusAsyncHttpClientBuilder.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.config.TlsConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+/**
+ * Builder for async http client that will retry, based on the {@link RemoteWriteRetryStrategy}
+ * specified.
+ */
+public class PrometheusAsyncHttpClientBuilder implements Serializable {
+ public static final int DEFAULT_SOCKET_TIMEOUT_MS = 5000;
+
+ private final RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+
+ public PrometheusAsyncHttpClientBuilder(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ }
+
+ public PrometheusAsyncHttpClientBuilder setSocketTimeout(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public CloseableHttpAsyncClient buildAndStartClient(SinkMetrics counters) {
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(socketTimeoutMs).orElse(DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ retryConfiguration.getInitialRetryDelayMS() >= 0,
+ "Initial retry delay must be >= 0");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryDelayMS()
+ >= retryConfiguration.getInitialRetryDelayMS(),
+ "Max retry delay must be >= initial retry delay");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryCount() >= 0, "Max retry count must be >= 0");
+ Preconditions.checkArgument(actualSocketTimeoutMs >= 0, "Socket timeout must be >= 0");
+
+ final IOReactorConfig ioReactorConfig =
+ IOReactorConfig.custom()
+ .setIoThreadCount(1) // Always one thread
Review Comment:
Can you expand the comment with why a single thread is used here?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/PrometheusAsyncHttpClientBuilder.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.config.TlsConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+/**
+ * Builder for async http client that will retry, based on the {@link RemoteWriteRetryStrategy}
+ * specified.
+ */
+public class PrometheusAsyncHttpClientBuilder implements Serializable {
+ public static final int DEFAULT_SOCKET_TIMEOUT_MS = 5000;
+
+ private final RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+
+ public PrometheusAsyncHttpClientBuilder(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ }
+
+ public PrometheusAsyncHttpClientBuilder setSocketTimeout(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public CloseableHttpAsyncClient buildAndStartClient(SinkMetrics counters) {
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(socketTimeoutMs).orElse(DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ retryConfiguration.getInitialRetryDelayMS() >= 0,
+ "Initial retry delay must be >= 0");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryDelayMS()
+ >= retryConfiguration.getInitialRetryDelayMS(),
+ "Max retry delay must be >= initial retry delay");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryCount() >= 0, "Max retry count must be >= 0");
+ Preconditions.checkArgument(actualSocketTimeoutMs >= 0, "Socket timeout must be >= 0");
+
+ final IOReactorConfig ioReactorConfig =
+ IOReactorConfig.custom()
+ .setIoThreadCount(1) // Always one thread
+ .setSoTimeout(Timeout.ofMilliseconds(actualSocketTimeoutMs))
+ .build();
+
+ var client =
+ HttpAsyncClients.custom()
+ .setConnectionManager(
+ PoolingAsyncClientConnectionManagerBuilder.create()
+ .setDefaultTlsConfig(
+ TlsConfig.custom()
+ .setVersionPolicy(
+ HttpVersionPolicy.FORCE_HTTP_1)
+ .build())
+ .build())
Review Comment:
Sould this part be extracted into variable to avoid deep nesting?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597510944
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
Review Comment:
Fixed.
Now `groupId` is `org.apache.flink` and `artifactId` is `flink-connector-prometheus-amp-request-signer`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1755176342
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering ecc.
+
+For efficiency, the sink **does not do any validation or reordering** of the input. It's responsibility
+of the application ensuring that input is well-formed.
+
+Any malformed data will be rejected on write to Prometheus. Depending on
+the [error handling behaviours](#error-handling-behavior)
+configured, the sink will throw an exception stopping the job (default), or drop the entire write-request, log the fact,
+and continue.
+
+For complete details about these constraints, refer to
+the [remote-write specifications](https://prometheus.io/docs/concepts/remote_write_spec/).
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of
+5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential
+backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit, depending
+on
+the configured [error handling behaviour](#error-handling-behavior) for "Max retries exceeded", the sink will either
+throw
+an exception (`FAIL`, default behaviour), or **discard the entire write-request**, log a warning and continue. See
+[error handling behaviour](#error-handling-behavior), below, for further details.
+
+### Initializing the sink
+
+Example of sink initialisation (for documentation purposes, we are setting all parameters to their default values):
+Sink
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500) // Batch size (write-request size), in samples (default: 500)
+ .setMaxRecordSizeInSamples(500) // Max sink input record size, in samples (default: 500), must be <= maxBatchSizeInSamples
Review Comment:
Good point.
I will explain this in the actual docs, in the other PR
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501897480
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(...).
+ * In our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
Review Comment:
Should be moved to class javadoc comment
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1469811763
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilderTest.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.hc.core5.http.HttpHeaders;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
Review Comment:
Removed Mockito from all tests.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486607342
##########
example-datastream-job/README.md:
##########
@@ -0,0 +1,22 @@
+## Example job using Prometheus Sink connector with DataStream API
+
+Sample application demonstrating the usage of Prometheus Sink Connector with DataStream API.
+
+The example demonstrates how to write to a generic, unauthenticated Prometheus remote-write URL, and optionally how to use the Amazon Managed Prometheus request signer.
+
+It generates random dummy Memory and CPU metrics from a number of instances, and writes them to Prometheus.
+
+### Configuration
+
+The application expects these parameters, via command line:
+
+* `--prometheusRemoteWriteUrl <URL>`: the Prometheus remote-write URL to target
+* `--awsRegion <region>`: (optional) if specified, it configures the Amazon Managed Prometheus request signer for a workspace in this Region
+* `--webUI`: (optional, for local development only) enables Flink Web UI, with flame graphs, for local development
Review Comment:
I don't think that would be any useful.
The way you pass parameters depends on your deployment.
And if you are running locally in your IDE, it depends on your IDE.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1464895640
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
Review Comment:
The whole signer implementation is a piece of code that half a dozen OSS projects are using, practically copy&paste, because nobody published it as a library
Here is just one example: https://github.com/apache/jclouds/blob/master/apis/s3/src/main/java/org/jclouds/s3/filters/Aws4SignerBase.java
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1477031366
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.17.0</flink.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk-core</artifactId>
+ <version>1.12.570</version>
Review Comment:
Added SDKv1 BOM to the parent
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488374236
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37).append(name).append(value).toHashCode();
+ }
+ }
+
+ /** A single Sample. */
+ public static class Sample implements Serializable {
+ private final double value;
+ private final long timestamp;
+
+ public Sample(double value, long timestamp) {
+ this.value = value;
+ this.timestamp = timestamp;
+ }
+
+ public double getValue() {
+ return value;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+ }
+
+ private final Label[] labels;
+ private final Sample[] samples;
+ private final String metricName;
+
+ public PrometheusTimeSeries(String metricName, Label[] labels, Sample[] samples) {
+ this.metricName = metricName;
+ this.labels = labels;
+ this.samples = samples;
+ }
+
+ public Label[] getLabels() {
+ return labels;
+ }
+
+ public Sample[] getSamples() {
+ return samples;
+ }
+
+ public String getMetricName() {
+ return metricName;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static Builder builderFrom(PrometheusTimeSeries other) {
+ return new Builder(
+ Arrays.asList(other.labels), Arrays.asList(other.samples), other.metricName);
+ }
+
+ /** Builder for sink input pojo instance. */
+ public static final class Builder {
+ private List<Label> labels = new ArrayList<>();
+ private List<Sample> samples = new ArrayList<>();
+ private String metricName;
+
+ private Builder(List<Label> labels, List<Sample> samples, String metricName) {
+ this.labels = labels;
+ this.samples = samples;
+ this.metricName = metricName;
+ }
Review Comment:
I assume you mean testing the builder, not its constructor.
Added a test for PrometheusTimeSeries.Builder
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1755375741
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering ecc.
+
+For efficiency, the sink **does not do any validation or reordering** of the input. It's responsibility
+of the application ensuring that input is well-formed.
+
+Any malformed data will be rejected on write to Prometheus. Depending on
+the [error handling behaviours](#error-handling-behavior)
+configured, the sink will throw an exception stopping the job (default), or drop the entire write-request, log the fact,
+and continue.
+
+For complete details about these constraints, refer to
+the [remote-write specifications](https://prometheus.io/docs/concepts/remote_write_spec/).
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of
+5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential
+backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit, depending
+on
+the configured [error handling behaviour](#error-handling-behavior) for "Max retries exceeded", the sink will either
+throw
+an exception (`FAIL`, default behaviour), or **discard the entire write-request**, log a warning and continue. See
+[error handling behaviour](#error-handling-behavior), below, for further details.
+
+### Initializing the sink
+
+Example of sink initialisation (for documentation purposes, we are setting all parameters to their default values):
+Sink
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500) // Batch size (write-request size), in samples (default: 500)
+ .setMaxRecordSizeInSamples(500) // Max sink input record size, in samples (default: 500), must be <= maxBatchSizeInSamples
Review Comment:
I also modified the docs, pushing the change to the other PR #2
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757531446
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkConfiguration.java:
##########
@@ -0,0 +1,165 @@
+package org.apache.flink.connector.prometheus.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+import static org.apache.flink.connector.prometheus.sink.PrometheusSinkConfiguration.OnErrorBehavior.FAIL;
+
+/** This class contains configuration classes for different components of the Prometheus sink. */
+@PublicEvolving
+public class PrometheusSinkConfiguration {
+
+ /**
+ * Defines the behaviour when an error is encountered: discard the offending request and
+ * continue, or fail, throwing an exception.
+ */
+ public enum OnErrorBehavior {
+ DISCARD_AND_CONTINUE,
+ FAIL
+ }
+
+ /**
+ * Configure the error-handling behavior of the writer, for different types of error. Also
+ * defines default behaviors.
+ */
+ public static class SinkWriterErrorHandlingBehaviorConfiguration implements Serializable {
Review Comment:
We'll have to annotate every class in this file with `@PublicEvolving`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757528729
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerForAMPTest.java:
##########
@@ -0,0 +1,73 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
License headers
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSignerTest.java:
##########
@@ -0,0 +1,112 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
License headers
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757530475
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkConfiguration.java:
##########
@@ -0,0 +1,165 @@
+package org.apache.flink.connector.prometheus.sink;
Review Comment:
License headers.
Thanks for creating this class!
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757525987
##########
flink-connector-prometheus-request-signer-amp/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,106 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/**
+ * Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP).
+ *
+ * <p>On every request, AWS credentials are retrieved using an AwsCredentialsProvider, and used to
+ * sign the request, with AWS Signature Version 4a.
+ */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
Review Comment:
Headers + `@PublicEvolving`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-1938541478
Once all the above are fixed, it would be good if we can squash the commits!
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486041042
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/SimpleInstanceMetricsTimeSeriesGenerator.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+
+import org.apache.commons.lang3.RandomUtils;
+
+import java.io.Serializable;
+import java.util.function.BiFunction;
+import java.util.function.Supplier;
+
+/**
+ * Very simple dummy TimeSeries generator, generating random `CPU` and `Memory` samples for a given
+ * number of instances.
+ *
+ * <p>Sample timestamp is always the current system time. The value is random, between 0 and 1
+ */
+public class SimpleInstanceMetricsTimeSeriesGenerator implements Serializable {
+
+ private final int numberOfDummyInstances;
+ private final int minNrOfSamples;
+ private final int maxNrOfSamples;
+
+ public SimpleInstanceMetricsTimeSeriesGenerator(
+ int minNrOfSamples, int maxNrOfSamples, int numberOfDummyInstances) {
+ this.numberOfDummyInstances = numberOfDummyInstances;
+ this.minNrOfSamples = minNrOfSamples;
+ this.maxNrOfSamples = maxNrOfSamples;
+ }
+
+ private String dummyInstanceId(int number) {
+ return "I" + String.format("%010d", number);
Review Comment:
nit: instance ID is lower case `i`
##########
prometheus-connector/README.md:
##########
@@ -0,0 +1,189 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering) and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, the write request is rejected by Prometheus and data is discarded by the sink.
+The connector will log a warning and count rejected data in custom metrics, but the data is discarded.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series are discarded.
+The reason is Remote-Write specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels) in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels go to the same sink subtask. A `KeySelector` is provided to partition input correctly (see [Partitioning](#partitioning), below).
+
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java) POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String }
+* one or more `Samples` { value: double, timestamp: long } - must be in timestamp order
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AcccountID", accountId);
+
+for(Tuple2<Double, Long> sample : samples) {
+ tsBuilder.addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+
+**Important**: for efficiency, the builder does reorder the samples. It is responsibility of the application to **add samples in timestamp order**.
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of 5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit,
+**the entire write-request**, containing the batch of time-series, **is dropped**.
+
+Every dropped request is logged at WARN level, including the reason provided by the remote-write endpoint.
Review Comment:
We can mention the configuration here too
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/RequestEntrySizeUtils.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.util.Collection;
+
+/** Collection of methods to calculate the sink RequestEntry "size". */
+public class RequestEntrySizeUtils {
+
+ /**
+ * Size of a request entry (a {@link Types.TimeSeries time-series}) for the purpose of batching.
+ * Count the number of {@link Types.Sample samples}
+ *
+ * @param requestEntry a time-series
+ * @return number of Samples in the TimeSeries
+ */
+ public static long requestSizeForBatching(Types.TimeSeries requestEntry) {
+ return requestEntry.getSamplesCount();
+ }
+
+ /**
+ * Serialized size of a request entry {@link Types.TimeSeries TimeSeries}: the number of bytes
+ * of the protobuf- serialized representation of the TimeSeries.
+ *
+ * @param requestEntry a time-series
+ * @return number of bytes
+ */
+ public static long requestSerializedSize(Types.TimeSeries requestEntry) {
+ return requestEntry.getSerializedSize();
+ }
+
+ /**
+ * Count the number of {@link Types.Sample samples} in a collection of {@link Types.TimeSeries
+ * time-series} (a batch).
+ *
+ * @param requestEntries collection of time-series
+ * @return number of samples
+ */
+ public static long countSamples(Collection<Types.TimeSeries> requestEntries) {
+ return requestEntries.stream()
+ .mapToLong(RequestEntrySizeUtils::requestSizeForBatching)
+ .sum();
+ }
Review Comment:
Can we add unit test coverage for this?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+ private String httpUserAgent = null;
+ private SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig = null;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int maxInFlightRequest = 1;
Review Comment:
nit: this could be a static constant. (I understand this is a copy of the real value in the sink itself)
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerForAuthorizationHeader.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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import java.net.URL;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * Sample AWS4 signer demonstrating how to sign requests to Amazon S3 using an 'Authorization'
+ * header.
+ */
+public class AWS4SignerForAuthorizationHeader extends AWS4SignerBase {
Review Comment:
Can we add unit tests?
##########
prometheus-connector/README.md:
##########
@@ -0,0 +1,189 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering) and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, the write request is rejected by Prometheus and data is discarded by the sink.
Review Comment:
We can mention our sink configurations
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
+
+ ParameterTool applicationParameters = ParameterTool.fromArgs(args);
+
+ // Prometheus remote-write URL
+ String prometheusRemoteWriteUrl = applicationParameters.get("prometheusRemoteWriteUrl");
+ LOGGER.info("Prometheus URL:{}", prometheusRemoteWriteUrl);
+
+ // Optionally configure Amazon Managed Prometheus request signer
+ PrometheusRequestSigner requestSigner = null;
+ String ampAWSRegion = applicationParameters.get("awsRegion");
+ if (ampAWSRegion != null) {
+ requestSigner =
+ new AmazonManagedPrometheusWriteRequestSigner(
+ prometheusRemoteWriteUrl, ampAWSRegion);
+ LOGGER.info(
+ "Enable Amazon Managed Prometheus request-signer, region: {}", ampAWSRegion);
+ }
+
+ // Configure data generator
+ int generatorMinSamplesPerTimeSeries = 1;
+ int generatorMaxSamplesPerTimeSeries = 10;
+ int generatorNumberOfDummyInstances = 5;
+ long generatorPauseBetweenTimeSeriesMs = 100;
+ LOGGER.info(
+ "Data Generator configuration:"
+ + "\n\t\tMin samples per time series:{}\n\t\tMax samples per time series:{}\n\t\tPause between time series:{} ms"
+ + "\n\t\tNumber of dummy instances:{}",
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorPauseBetweenTimeSeriesMs,
+ generatorNumberOfDummyInstances);
+
+ Supplier<PrometheusTimeSeries> eventGenerator =
+ new SimpleInstanceMetricsTimeSeriesGenerator(
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorNumberOfDummyInstances)
+ .generator();
+
+ SourceFunction<PrometheusTimeSeries> source =
+ new FixedDelayDataGenertorSource<>(
Review Comment:
Typo - `Generator`
##########
example-datastream-job/README.md:
##########
@@ -0,0 +1,22 @@
+## Example job using Prometheus Sink connector with DataStream API
+
+Sample application demonstrating the usage of Prometheus Sink Connector with DataStream API.
+
+The example demonstrates how to write to a generic, unauthenticated Prometheus remote-write URL, and optionally how to use the Amazon Managed Prometheus request signer.
+
+It generates random dummy Memory and CPU metrics from a number of instances, and writes them to Prometheus.
+
+### Configuration
+
+The application expects these parameters, via command line:
+
+* `--prometheusRemoteWriteUrl <URL>`: the Prometheus remote-write URL to target
+* `--awsRegion <region>`: (optional) if specified, it configures the Amazon Managed Prometheus request signer for a workspace in this Region
+* `--webUI`: (optional, for local development only) enables Flink Web UI, with flame graphs, for local development
+
+### Data generation
+
+The application generates random time series, containing `CPU` and `Memory` samples from 5 dummy "instances". A new time series is generated about every 100ms. Each time series contains 1 to 10 samples.
+
+These parameters are configurable from the code
Review Comment:
```suggestion
These parameters are configurable from the code.
```
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
Review Comment:
Can we explain why this is set to 2?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/HttpResponseCallback.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/**
+ * Callback handling the outcome of the http async request.
+ *
+ * <p>This class implements the error handling behaviour, based on the configuration in {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}. Depending on the condition, the sink may throw an
+ * exception and cause the job to fail, or log the condition to WARN, increment the counters and
+ * continue with the next request.
+ *
+ * <p>In any case, every write-request either entirely succeed or fail. Partial failures are not
+ * handled.
+ *
+ * <p>In no condition a write-request is re-queued for the AsyncSink to reprocess: this would cause
+ * out of order writes that would be rejected by Prometheus.
+ *
+ * <p>Note that the http async client retries, based on the configured retry policy. The callback is
+ * called with an outcome of *completed* either when the request has succeeded or the max retry
+ * limit has been exceeded. It is responsibility of the callback distinguishing between these
+ * conditions.
+ */
+class HttpResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private static final Logger LOG = LoggerFactory.getLogger(HttpResponseCallback.class);
+
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> reQueuedResult;
+ private final SinkMetrics metrics;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public HttpResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkMetrics metrics,
Review Comment:
nit: This can be abstracted away to another `metricsCallback`
##########
example-datastream-job/README.md:
##########
@@ -0,0 +1,22 @@
+## Example job using Prometheus Sink connector with DataStream API
+
+Sample application demonstrating the usage of Prometheus Sink Connector with DataStream API.
+
+The example demonstrates how to write to a generic, unauthenticated Prometheus remote-write URL, and optionally how to use the Amazon Managed Prometheus request signer.
+
+It generates random dummy Memory and CPU metrics from a number of instances, and writes them to Prometheus.
+
+### Configuration
+
+The application expects these parameters, via command line:
+
+* `--prometheusRemoteWriteUrl <URL>`: the Prometheus remote-write URL to target
+* `--awsRegion <region>`: (optional) if specified, it configures the Amazon Managed Prometheus request signer for a workspace in this Region
+* `--webUI`: (optional, for local development only) enables Flink Web UI, with flame graphs, for local development
Review Comment:
How do we run this? Should we include an example run command?
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
+
+ ParameterTool applicationParameters = ParameterTool.fromArgs(args);
+
+ // Prometheus remote-write URL
+ String prometheusRemoteWriteUrl = applicationParameters.get("prometheusRemoteWriteUrl");
+ LOGGER.info("Prometheus URL:{}", prometheusRemoteWriteUrl);
+
+ // Optionally configure Amazon Managed Prometheus request signer
+ PrometheusRequestSigner requestSigner = null;
+ String ampAWSRegion = applicationParameters.get("awsRegion");
+ if (ampAWSRegion != null) {
+ requestSigner =
+ new AmazonManagedPrometheusWriteRequestSigner(
+ prometheusRemoteWriteUrl, ampAWSRegion);
+ LOGGER.info(
+ "Enable Amazon Managed Prometheus request-signer, region: {}", ampAWSRegion);
+ }
+
+ // Configure data generator
+ int generatorMinSamplesPerTimeSeries = 1;
+ int generatorMaxSamplesPerTimeSeries = 10;
+ int generatorNumberOfDummyInstances = 5;
Review Comment:
Hmm, this is hard to understand out of context. Can we add an overall description at the top of this class, or rename this to "NumberOfKeys/NumberOfUniqueMetrics" or something?
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
+
+ ParameterTool applicationParameters = ParameterTool.fromArgs(args);
+
+ // Prometheus remote-write URL
+ String prometheusRemoteWriteUrl = applicationParameters.get("prometheusRemoteWriteUrl");
+ LOGGER.info("Prometheus URL:{}", prometheusRemoteWriteUrl);
+
+ // Optionally configure Amazon Managed Prometheus request signer
+ PrometheusRequestSigner requestSigner = null;
+ String ampAWSRegion = applicationParameters.get("awsRegion");
+ if (ampAWSRegion != null) {
+ requestSigner =
+ new AmazonManagedPrometheusWriteRequestSigner(
+ prometheusRemoteWriteUrl, ampAWSRegion);
+ LOGGER.info(
+ "Enable Amazon Managed Prometheus request-signer, region: {}", ampAWSRegion);
+ }
+
+ // Configure data generator
+ int generatorMinSamplesPerTimeSeries = 1;
+ int generatorMaxSamplesPerTimeSeries = 10;
+ int generatorNumberOfDummyInstances = 5;
+ long generatorPauseBetweenTimeSeriesMs = 100;
+ LOGGER.info(
+ "Data Generator configuration:"
+ + "\n\t\tMin samples per time series:{}\n\t\tMax samples per time series:{}\n\t\tPause between time series:{} ms"
+ + "\n\t\tNumber of dummy instances:{}",
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorPauseBetweenTimeSeriesMs,
+ generatorNumberOfDummyInstances);
+
+ Supplier<PrometheusTimeSeries> eventGenerator =
+ new SimpleInstanceMetricsTimeSeriesGenerator(
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorNumberOfDummyInstances)
+ .generator();
+
+ SourceFunction<PrometheusTimeSeries> source =
+ new FixedDelayDataGenertorSource<>(
+ PrometheusTimeSeries.class,
+ eventGenerator,
+ generatorPauseBetweenTimeSeriesMs);
+
+ DataStream<PrometheusTimeSeries> prometheusTimeSeries = env.addSource(source);
+
+ // Build the sink showing all supported configuration parameters.
+ // It is not mandatory to specify all configurations, as they will fall back to the default
+ // value
+ AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> sink =
+ PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500)
+ .setMaxRecordSizeInSamples(500)
+ .setMaxTimeInBufferMS(5000)
+ .setRetryConfiguration(
+ RetryConfiguration.builder()
+ .setInitialRetryDelayMS(30L)
+ .setMaxRetryDelayMS(5000L)
+ .setMaxRetryCount(100)
+ .build())
+ .setSocketTimeoutMs(5000)
Review Comment:
nit: Should we leave comment after to show which are optional?
e.g.
```
.setMaxBatchSizeInSamples(500) // Optional, defaults to 500
```
##########
example-datastream-job/src/main/resources/log4j2.properties:
##########
@@ -0,0 +1,29 @@
+#
+# 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.
+#
+
+appender.console.name = ConsoleAppender
+appender.console.type = CONSOLE
+appender.console.layout.type = PatternLayout
+appender.console.layout.pattern = %d{HH:mm:ss,SSS} %-5p %-60c %x - %m%n
+
+#logger.tracing.name = org.apache.flink.connector.prometheus.sink
+#logger.tracing.level = trace
+#logger.tracing.additivity = false
+#logger.tracing.appenderRef.console.ref = ConsoleAppender
Review Comment:
Can we remove these, or explain when to uncomment for testing?
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializerTest.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class PrometheusStateSerializerTest {
+
+ private static final ElementConverter<PrometheusTimeSeries, Types.TimeSeries>
+ ELEMENT_CONVERTER = new PrometheusTimeSeriesConverter();
+
+ private static PrometheusTimeSeries getTestTimeSeries(int i) {
+ return PrometheusTimeSeries.builder()
+ .withMetricName("metric-name")
+ .addLabel("dimension-a", "value-" + i)
+ .addSample(i + 42.0, i + 1L)
+ .addSample(i + 3.14, i + 2L)
+ .build();
+ }
+
+ // This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
+ // the requestEntry "size"
+ // (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
+ // see
+ // https://github.com/apache/flink/blob/69e812688b43be9a0c4f79e6af81bc2d1d8a873e/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializer.java#L60
Review Comment:
Can we consider making this a javadoc + link to code?
For example:
```
/**
* This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
* the requestEntry "size"
* (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
* see {@link org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer#serialize(BufferedRequestState)}
*/
```
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/HttpResponseCallback.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/**
+ * Callback handling the outcome of the http async request.
+ *
+ * <p>This class implements the error handling behaviour, based on the configuration in {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}. Depending on the condition, the sink may throw an
+ * exception and cause the job to fail, or log the condition to WARN, increment the counters and
+ * continue with the next request.
+ *
+ * <p>In any case, every write-request either entirely succeed or fail. Partial failures are not
+ * handled.
+ *
+ * <p>In no condition a write-request is re-queued for the AsyncSink to reprocess: this would cause
+ * out of order writes that would be rejected by Prometheus.
+ *
+ * <p>Note that the http async client retries, based on the configured retry policy. The callback is
+ * called with an outcome of *completed* either when the request has succeeded or the max retry
+ * limit has been exceeded. It is responsibility of the callback distinguishing between these
+ * conditions.
+ */
+class HttpResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private static final Logger LOG = LoggerFactory.getLogger(HttpResponseCallback.class);
+
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> reQueuedResult;
+ private final SinkMetrics metrics;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public HttpResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkMetrics metrics,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ Consumer<List<Types.TimeSeries>> reQueuedResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.reQueuedResult = reQueuedResult;
+ this.metrics = metrics;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ }
+
+ /**
+ * The completed outcome is invoked every time the http client successfully receives a valid
+ * http response, regardless of the status code.
+ *
+ * <p>This method classifies the responses and implements the behaviour expected by the
+ * Remote-Write specifications. In case of error, the behaviour is determined by the error
+ * handling configuration.
+ */
+ @Override
+ public void completed(SimpleHttpResponse response) {
Review Comment:
Do we want to consider expanding out nested `if-else` into linear with `return` instead?
See example here: https://stackoverflow.com/questions/56356190/nested-if-conditions-vs-multiple-separated-if-conditions-with-return-statement-i
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
+ * Protobuf-serialized representation of a {@link Types.TimeSeries TimeSeries}. In this
+ * implementation SIZEn is the size of the Protobuf serialization, in bytes, that does not match
+ * the "size" of a {@link RequestEntryWrapper}.
+ *
+ * @param bufferedRequestState The buffered request state to be serialized
+ * @return serialized buffered request state
+ * @throws IOException
+ */
+ @Override
+ public byte[] serialize(BufferedRequestState<Types.TimeSeries> bufferedRequestState)
+ throws IOException {
+ Collection<RequestEntryWrapper<Types.TimeSeries>> bufferState =
+ bufferedRequestState.getBufferedRequestEntries();
+
+ try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final DataOutputStream out = new DataOutputStream(baos)) {
+
+ out.writeLong(DATA_IDENTIFIER); // DATA_IDENTIFIER
+ out.writeInt(bufferState.size()); // NUM_OF_ELEMENTS
+
+ for (RequestEntryWrapper<Types.TimeSeries> wrapper : bufferState) {
+ // In the serialized state we write the size of the serialized representation,
+ // rather than the size
+ // held in RequestEntryWrapper, that is the output of
+ // AsyncSinkWriter.getSizeInBytes()
+ long requestEntrySize =
+ RequestEntrySizeUtils.requestSerializedSize(wrapper.getRequestEntry());
+ out.writeLong(requestEntrySize); // SIZEn
+ serializeRequestToStream(wrapper.getRequestEntry(), out); // REQUESTn
Review Comment:
remove the `n`?
##########
pom.xml:
##########
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-parent</artifactId>
+ <version>1.0.0</version>
+ </parent>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <name>Flink Prometheus</name>
+ <modules>
+ <module>prometheus-connector</module>
+ <module>amp-request-signer</module>
+ <module>example-datastream-job</module>
+ </modules>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+ <flink.version>1.17.0</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ <aws.sdkv1.version>1.12.570</aws.sdkv1.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk-bom</artifactId>
+ <version>${aws.sdkv1.version}</version>
Review Comment:
Why are we using AWS SDK v1? Can we use v2?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/prometheus/Remote.java:
##########
@@ -0,0 +1,6661 @@
+/*
Review Comment:
Should we consider adding API snapshot tests for this class?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+@Public
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusAsyncHttpClientBuilder clientBuilder;
+ private final PrometheusRequestSigner requestSigner;
+ private final int maxBatchSizeInSamples;
+ private final String httpUserAgent;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ protected PrometheusSink(
Review Comment:
Can we add a configuration to specify a metrics group prefix?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRequestSigner.java:
##########
@@ -0,0 +1,43 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import java.io.Serializable;
+import java.util.Map;
+
+/**
+ * Interface for a request signer, specific of the Prometheus implementation.
+ *
+ * <p>A request signer implementation can generate additional Http request headers, based on the
+ * existing headers and the request body.
+ */
+@Public
+public interface PrometheusRequestSigner extends Serializable {
+
+ /**
+ * Add to the existing http request headers any additional header required by the specific
+ * Prometheus implementation for signing.
+ *
+ * @param requestHeaders original Http request headers. For efficiency, the implementation is
+ * expected to modify the Map in place. The Map is expected to be mutable.
+ * @param requestBody request body, already compressed.
+ */
+ void addSignatureHeaders(Map<String, String> requestHeaders, byte[] requestBody);
Review Comment:
Let's add an explanation here as to why we mutate request headers instead of creating a copy - for performance reasons
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
Review Comment:
Can we add some `null`/`empty` validations for these data classes? (+ unit tests too!)
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
Review Comment:
Can we add unit test coverage for this?
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializerTest.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class PrometheusStateSerializerTest {
+
+ private static final ElementConverter<PrometheusTimeSeries, Types.TimeSeries>
+ ELEMENT_CONVERTER = new PrometheusTimeSeriesConverter();
+
+ private static PrometheusTimeSeries getTestTimeSeries(int i) {
+ return PrometheusTimeSeries.builder()
+ .withMetricName("metric-name")
+ .addLabel("dimension-a", "value-" + i)
+ .addSample(i + 42.0, i + 1L)
+ .addSample(i + 3.14, i + 2L)
+ .build();
+ }
+
+ // This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
+ // the requestEntry "size"
+ // (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
+ // see
+ // https://github.com/apache/flink/blob/69e812688b43be9a0c4f79e6af81bc2d1d8a873e/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializer.java#L60
Review Comment:
(we can replace the qualified name with an import for the class)
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37).append(name).append(value).toHashCode();
+ }
+ }
+
+ /** A single Sample. */
+ public static class Sample implements Serializable {
+ private final double value;
+ private final long timestamp;
+
+ public Sample(double value, long timestamp) {
+ this.value = value;
+ this.timestamp = timestamp;
+ }
+
+ public double getValue() {
+ return value;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+ }
+
+ private final Label[] labels;
+ private final Sample[] samples;
+ private final String metricName;
+
+ public PrometheusTimeSeries(String metricName, Label[] labels, Sample[] samples) {
+ this.metricName = metricName;
+ this.labels = labels;
+ this.samples = samples;
+ }
+
+ public Label[] getLabels() {
+ return labels;
+ }
+
+ public Sample[] getSamples() {
+ return samples;
+ }
+
+ public String getMetricName() {
+ return metricName;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static Builder builderFrom(PrometheusTimeSeries other) {
+ return new Builder(
+ Arrays.asList(other.labels), Arrays.asList(other.samples), other.metricName);
+ }
+
+ /** Builder for sink input pojo instance. */
+ public static final class Builder {
+ private List<Label> labels = new ArrayList<>();
+ private List<Sample> samples = new ArrayList<>();
+ private String metricName;
+
+ private Builder(List<Label> labels, List<Sample> samples, String metricName) {
+ this.labels = labels;
+ this.samples = samples;
+ this.metricName = metricName;
+ }
Review Comment:
Can we add unit test coverage for this?
<img width="717" alt="image" src="https://github.com/apache/flink-connector-prometheus/assets/35062175/e03c8c41-bf9b-4339-ab0f-34ac4b62b241">
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/prometheus/Remote.java:
##########
@@ -0,0 +1,6661 @@
+/*
Review Comment:
Same for `Types.java` and `GoGoProtos.java`
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,117 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
Sorry!! I think better to use `@PublicEvolving` or `@Experimental`, either ok with me. Prefer `@Experimental` because it allows easier breaking changes on our side.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486604736
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
Review Comment:
Added a comment.
The goal is to force parallel writes and demonstrate how `PrometheusTimeSeriesLabelsAndMetricNameKeySelector` partitions data preventing out-of-order writes, that would be rejected by Prometheus
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1467886908
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
+ }
+
+ // Never re-queue requests
+ requestResult.accept(Collections.emptyList());
+ }
+
+ @Override
+ public void failed(Exception ex) {
+ LOG.warn(
+ "Exception executing the remote-write (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount,
+ ex);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
Review Comment:
Changed the general behaviour (see comment below)
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1467921494
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
Review Comment:
Added a different behaviour: no response should be unclassified. If a status code < 200 is received, something is terribly wrong, so I am now throwing an exception
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1472662095
##########
msf-amp-example/README.md:
##########
@@ -0,0 +1,68 @@
+## Sample application: Amazon Managed Service for Apache Flink and Amazon Managed Prometheus
Review Comment:
Replaced the example with a new one, using Flink 1.17.2 and with nothing MSF specific.
The new example optionally demonstrates how to configure the request signer to target AMP (the only supported request signer at the moment)
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-1918882599
@hlteoh37 please check out the changes. I should have addressed all the points
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1447607637
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+
+ <flink.version>1.16.0</flink.version>
Review Comment:
Should we consider 1.17? Since the supported version is 1.17 + 1.18 now
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+
+ <flink.version>1.16.0</flink.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <version>${project.version}</version>
+ </dependency>
Review Comment:
IIUC, this should be `<scope>provided</scope>`!
##########
pom.xml:
##########
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
Review Comment:
Should we keep the same convention as other connector repos `flink-connector-prometheus-parent`?
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sing a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(awsRegion));
Review Comment:
Should we add a message here in the event of failure?
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
Review Comment:
Is there a reason we fix this as 0 UTC? Is there a scenario we would want to have a different timezone here? If so, maybe we can make this configurable / use the timezone of the host
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
+
+ private static final ContentType CONTENT_TYPE = ContentType.create("application/x-protobuf");
+
+ private static final Map<String, String> FIXED_HEADER =
+ Map.of(
+ HttpHeaders.CONTENT_ENCODING,
+ "snappy",
+ "X-Prometheus-Remote-Write-Version",
+ "0.1.0",
+ HttpHeaders.USER_AGENT,
+ "Flink-Prometheus/0.1.0" // TODO Prometheus requires a user-agent header. What
Review Comment:
As discussed offline, maybe we can make this configurable, and default to `Flink-Prometheus`?
##########
msf-amp-example/README.md:
##########
@@ -0,0 +1,68 @@
+## Sample application: Amazon Managed Service for Apache Flink and Amazon Managed Prometheus
Review Comment:
We shouldn't be putting company specific examples here. Should we consider using a non-MSF example here instead, and move this MSF-specific one elsewhere?
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
Review Comment:
Is there a reason we use `javax.crypto.Mac` here? Do we know if this limits our java version etc?
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sing a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
Review Comment:
nit: `Sign`
We also might want to put an example usage in the docs here.
##########
prometheus-connector/pom.xml:
##########
@@ -0,0 +1,130 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus</name>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <packaging>jar</packaging>
+
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+
+ <flink.version>1.16.2</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-streaming-java</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- protobuf, snappy - for prometheus remote-write payload -->
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ <version>${protobuf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java-util</artifactId>
+ <version>${protobuf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.xerial.snappy</groupId>
+ <artifactId>snappy-java</artifactId>
+ <version>1.1.9.1</version>
+ </dependency>
+
+ <!-- http client -->
+ <dependency>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
+ <version>${apache.httpclient.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <artifactId>httpcore5</artifactId>
+ <version>${apache.httpclient.version}</version>
+ </dependency>
+
+ <!-- test -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-test-utils-junit</artifactId>
+ <version>${flink.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8</artifactId>
+ <version>2.35.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>4.5.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
+ <version>4.2.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.8.0</version>
+ <configuration>
+ <source>${target.java.version}</source>
+ <target>${target.java.version}</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
Review Comment:
this might already come from the connector parent! We should 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597412742
##########
prometheus-connector/README.md:
##########
@@ -0,0 +1,189 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering) and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, the write request is rejected by Prometheus and data is discarded by the sink.
Review Comment:
Sorry, understood the point. Adding an explanation
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597488453
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
Review Comment:
It actually means "REQUEST<n>"
Fixed the comment to make it clear
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501903046
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ */
+ protected static String getCanonicalRequest(
+ URL endpoint,
+ String httpMethod,
+ String queryParameters,
+ String canonicalizedHeaderNames,
+ String canonicalizedHeaders,
+ String bodyHash) {
+ String canonicalRequest =
+ httpMethod
+ + "\n"
+ + getCanonicalizedResourcePath(endpoint)
+ + "\n"
+ + queryParameters
+ + "\n"
+ + canonicalizedHeaders
+ + "\n"
+ + canonicalizedHeaderNames
+ + "\n"
+ + bodyHash;
+ return canonicalRequest;
+ }
+
+ /** Returns the canonicalized resource path for the service endpoint. */
+ protected static String getCanonicalizedResourcePath(URL endpoint) {
+ if (endpoint == null) {
+ return "/";
+ }
+ String path = endpoint.getPath();
+ if (path == null || path.isEmpty()) {
+ return "/";
+ }
+
+ String encodedPath = urlEncode(path, true);
+ if (encodedPath.startsWith("/")) {
+ return encodedPath;
+ } else {
+ return "/".concat(encodedPath);
+ }
+ }
+
+ /**
+ * Examines the specified query string parameters and returns a canonicalized form.
+ *
+ * <p>The canonicalized query string is formed by first sorting all the query string parameters,
+ * then URI encoding both the key and value and then joining them, in order, separating key
+ * value pairs with an '&'.
+ *
+ * @param parameters The query string parameters to be canonicalized.
+ * @return A canonicalized form for the specified query string parameters.
+ */
+ public static String getCanonicalizedQueryString(Map<String, String> parameters) {
+ if (parameters == null || parameters.isEmpty()) {
+ return "";
+ }
+
+ SortedMap<String, String> sorted = new TreeMap<String, String>();
+
+ Iterator<Map.Entry<String, String>> pairs = parameters.entrySet().iterator();
+ while (pairs.hasNext()) {
+ Map.Entry<String, String> pair = pairs.next();
+ String key = pair.getKey();
+ String value = pair.getValue();
+ sorted.put(urlEncode(key, false), urlEncode(value, false));
+ }
+
+ StringBuilder builder = new StringBuilder();
+ pairs = sorted.entrySet().iterator();
+ while (pairs.hasNext()) {
+ Map.Entry<String, String> pair = pairs.next();
+ builder.append(pair.getKey());
+ builder.append("=");
+ builder.append(pair.getValue());
+ if (pairs.hasNext()) {
+ builder.append("&");
+ }
+ }
+
+ return builder.toString();
+ }
+
+ protected static String getStringToSign(
+ String scheme,
+ String algorithm,
+ String dateTime,
+ String scope,
+ String canonicalRequest) {
+ String stringToSign =
+ scheme
+ + "-"
+ + algorithm
+ + "\n"
+ + dateTime
+ + "\n"
+ + scope
+ + "\n"
+ + BinaryUtils.toHex(hash(canonicalRequest));
+ return stringToSign;
+ }
+
+ /** Hashes the string contents (assumed to be UTF-8) using the SHA-256 algorithm. */
+ public static byte[] hash(String text) {
+ try {
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(text.getBytes("UTF-8"));
+ return md.digest();
+ } catch (Exception e) {
+ throw new RuntimeException(
+ "Unable to compute hash while signing request: " + e.getMessage(), e);
Review Comment:
Can you replace this with a more specific exception? Same comment to all other `RuntimeException` usages
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501904332
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.List;
+
+/** Retry strategy for the http client. */
+public class RemoteWriteRetryStrategy implements HttpRequestRetryStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(RemoteWriteRetryStrategy.class);
+
+ private static final List<Class<? extends IOException>> NON_RETRIABLE_EXCEPTIONS =
+ List.of(
+ InterruptedIOException.class,
+ UnknownHostException.class,
+ ConnectException.class,
+ NoRouteToHostException.class,
+ SSLException.class);
+
+ private final long initialRetryDelayMs;
+ private final long maxRetryDelayMs;
+ private final int maxRetryCount;
+
+ private final SinkMetrics counters;
+
+ public RemoteWriteRetryStrategy(RetryConfiguration retryConfiguration, SinkMetrics counters) {
+ this.initialRetryDelayMs = retryConfiguration.getInitialRetryDelayMS();
+ this.maxRetryDelayMs = retryConfiguration.getMaxRetryDelayMS();
+ this.maxRetryCount = retryConfiguration.getMaxRetryCount();
+ this.counters = counters;
+ }
+
+ @Override
+ public boolean retryRequest(
+ HttpRequest httpRequest, IOException e, int execCount, HttpContext httpContext) {
+ // Retry on any IOException except those considered non-retriable
+ var retry =
+ (execCount <= maxRetryCount) && !(NON_RETRIABLE_EXCEPTIONS.contains(e.getClass()));
+ LOG.debug(
+ "{} retry on {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ e.getClass(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public boolean retryRequest(HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ var retry =
+ (execCount <= maxRetryCount)
+ && RemoteWriteResponseClassifier.isRetriableErrorResponse(httpResponse);
+ LOG.debug(
+ "{} retry on response {} {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ httpResponse.getCode(),
+ httpResponse.getReasonPhrase(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public TimeValue getRetryInterval(
+ HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ long calculatedDelay = initialRetryDelayMs << (execCount - 1);
Review Comment:
Should multiplier be configurable instead of being set to 2?
Additionally can jitter be added here?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.List;
+
+/** Retry strategy for the http client. */
+public class RemoteWriteRetryStrategy implements HttpRequestRetryStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(RemoteWriteRetryStrategy.class);
+
+ private static final List<Class<? extends IOException>> NON_RETRIABLE_EXCEPTIONS =
+ List.of(
+ InterruptedIOException.class,
+ UnknownHostException.class,
+ ConnectException.class,
+ NoRouteToHostException.class,
+ SSLException.class);
+
+ private final long initialRetryDelayMs;
+ private final long maxRetryDelayMs;
+ private final int maxRetryCount;
+
+ private final SinkMetrics counters;
+
+ public RemoteWriteRetryStrategy(RetryConfiguration retryConfiguration, SinkMetrics counters) {
+ this.initialRetryDelayMs = retryConfiguration.getInitialRetryDelayMS();
+ this.maxRetryDelayMs = retryConfiguration.getMaxRetryDelayMS();
+ this.maxRetryCount = retryConfiguration.getMaxRetryCount();
+ this.counters = counters;
+ }
+
+ @Override
+ public boolean retryRequest(
+ HttpRequest httpRequest, IOException e, int execCount, HttpContext httpContext) {
+ // Retry on any IOException except those considered non-retriable
+ var retry =
+ (execCount <= maxRetryCount) && !(NON_RETRIABLE_EXCEPTIONS.contains(e.getClass()));
+ LOG.debug(
+ "{} retry on {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ e.getClass(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public boolean retryRequest(HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ var retry =
+ (execCount <= maxRetryCount)
+ && RemoteWriteResponseClassifier.isRetriableErrorResponse(httpResponse);
+ LOG.debug(
+ "{} retry on response {} {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ httpResponse.getCode(),
+ httpResponse.getReasonPhrase(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public TimeValue getRetryInterval(
+ HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ long calculatedDelay = initialRetryDelayMs << (execCount - 1);
Review Comment:
Should multiplier be configurable instead of being set to 2?
Additionally, can jitter be added 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489284689
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ *
+ * @return
Review Comment:
@z3d1k not sure I see the value of generating the Protobuf classes from `.proto` file instead of hardwiring the generated classes, in this context.
The remote-write protocol is much more than the payload schema.
Any Prometheus remote-write protocol change will probably require changes to the code to adjust the behavior.
Also, generating the code from `.proto` would require to do the same also with GoGoProto.
And finally, this an external dependency, not something under our control, and must be "copied&pasted" into the project source, as it's not available on Maven. There is no much difference between including the proto and including the generated code
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1754639229
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
Review Comment:
The word "guarantee" here is a little confusing. Maybe we can say something like the "Prometheus Remote-Write has strict guarantees around ordering and format. This sink requires that users ensure that input data is in order and well-formed before adding it to the sink."
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering ecc.
Review Comment:
nit: etc.
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeriesConverter.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+/**
+ * Converts the sink input {@link PrometheusTimeSeries} into the Protobuf {@link Types.TimeSeries}
+ * that are sent to Prometheus.
+ */
+public class PrometheusTimeSeriesConverter
Review Comment:
`@PublicEvolving`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ // Max batch size, in number of samples
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ // Max time a record is buffered
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ // Max nr of requestEntry that will be buffered
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS = 1000;
+ // Metric Group name added to the custom metrics
+ private static final String DEFAULT_METRIC_GROUP_NAME = "Prometheus";
+
+ // Max in-flight requests is always = 1, to retain ordering
+ private static final int MAX_IN_FLIGHT_REQUESTS = 1;
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+ private String httpUserAgent = null;
+ private SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig = null;
+ private String metricGroupName = null;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples()).orElse(getMaxBatchSizeInSamples());
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ String actualHttpUserAgent =
+ Optional.ofNullable(getHttpUserAgent())
+ .orElse(PrometheusRemoteWriteHttpRequestBuilder.DEFAULT_USER_AGENT);
+
+ SinkWriterErrorHandlingBehaviorConfiguration actualErrorHandlingBehaviorConfig =
+ Optional.ofNullable(errorHandlingBehaviorConfig)
+ .orElse(SinkWriterErrorHandlingBehaviorConfiguration.DEFAULT_BEHAVIORS);
+
+ String actualMetricGroupName =
+ Optional.ofNullable(metricGroupName).orElse(DEFAULT_METRIC_GROUP_NAME);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}\n\t\thttpUserAgent={}"
+ + "\n\t\tErrorHandlingBehaviour: onMaxRetryExceeded={}, onHttpClientIOFailure={}, onNonRetriableError={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig.getOnMaxRetryExceeded(),
+ actualErrorHandlingBehaviorConfig.getOnHttpClientIOFail(),
+ actualErrorHandlingBehaviorConfig.getOnPrometheusNonRetriableError());
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig,
+ actualMetricGroupName);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setHttpUserAgent(String httpUserAgent) {
+ this.httpUserAgent = httpUserAgent;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setErrorHandlingBehaviourConfiguration(
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig) {
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMetricGroupName(String metricGroupName) {
+ this.metricGroupName = metricGroupName;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ public String getHttpUserAgent() {
+ return httpUserAgent;
+ }
+
+ public SinkWriterErrorHandlingBehaviorConfiguration getErrorHandlingBehaviorConfig() {
+ return errorHandlingBehaviorConfig;
+ }
+
+ public String getMetricGroupName() {
+ return metricGroupName;
+ }
+
+ /// Disable accessing maxBatchSize, maxBatchSizeInBytes, and maxRecordSizeInBytes directly
+
+ /** Not supported. Use setMaxBatchSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSize(int maxBatchSize) {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ /** Not supported. Use setMaxBatchSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxBatchSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use setMaxRecordSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxRecordSizeInBytes(long maxRecordSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxBatchSizeInSamples() instead */
+ @Override
+ protected Integer getMaxBatchSize() {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxBatchSizeInSamples() instead */
+ @Override
+ protected Long getMaxBatchSizeInBytes() {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxRecordSizeInSamples() instead */
+ @Override
+ protected Long getMaxRecordSizeInBytes() {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
Review Comment:
We don't need to do this, as we don't expect this builder to be extended!
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/metrics/SinkMetrics.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.prometheus.sink.metrics;
+
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.MetricGroup;
+
+/** Wraps all metrics in a single class. */
+public class SinkMetrics {
Review Comment:
`@Internal`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+@PublicEvolving
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusAsyncHttpClientBuilder clientBuilder;
+ private final PrometheusRequestSigner requestSigner;
+ private final int maxBatchSizeInSamples;
+ private final String httpUserAgent;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+ private final String metricGroupName;
+
+ protected PrometheusSink(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ int maxRecordSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ PrometheusAsyncHttpClientBuilder clientBuilder,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ String metricGroupName) {
+ super(
+ elementConverter,
+ maxBatchSizeInSamples, // maxBatchSize,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes,
+ maxTimeInBufferMS,
+ maxRecordSizeInSamples // maxRecordSizeInBytes
+ );
+
+ Preconditions.checkArgument(maxInFlightRequests == 1, "maxInFlightRequests must be 1");
+
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ this.requestSigner = requestSigner;
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ this.clientBuilder = clientBuilder;
+ this.httpUserAgent = httpUserAgent;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ this.metricGroupName = metricGroupName;
+ }
+
+ public int getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
Review Comment:
Actually can we just delete this?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+@PublicEvolving
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusAsyncHttpClientBuilder clientBuilder;
+ private final PrometheusRequestSigner requestSigner;
+ private final int maxBatchSizeInSamples;
+ private final String httpUserAgent;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+ private final String metricGroupName;
+
+ protected PrometheusSink(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ int maxRecordSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ PrometheusAsyncHttpClientBuilder clientBuilder,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ String metricGroupName) {
+ super(
+ elementConverter,
+ maxBatchSizeInSamples, // maxBatchSize,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes,
Review Comment:
Can we add a comment to explain that we don't need to check the bytes, so we simply use sample as replacement for bytes
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering ecc.
+
+For efficiency, the sink **does not do any validation or reordering** of the input. It's responsibility
+of the application ensuring that input is well-formed.
+
+Any malformed data will be rejected on write to Prometheus. Depending on
+the [error handling behaviours](#error-handling-behavior)
+configured, the sink will throw an exception stopping the job (default), or drop the entire write-request, log the fact,
+and continue.
+
+For complete details about these constraints, refer to
+the [remote-write specifications](https://prometheus.io/docs/concepts/remote_write_spec/).
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of
+5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential
+backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit, depending
+on
+the configured [error handling behaviour](#error-handling-behavior) for "Max retries exceeded", the sink will either
+throw
+an exception (`FAIL`, default behaviour), or **discard the entire write-request**, log a warning and continue. See
+[error handling behaviour](#error-handling-behavior), below, for further details.
+
+### Initializing the sink
+
+Example of sink initialisation (for documentation purposes, we are setting all parameters to their default values):
+Sink
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500) // Batch size (write-request size), in samples (default: 500)
+ .setMaxRecordSizeInSamples(500) // Max sink input record size, in samples (default: 500), must be <= maxBatchSizeInSamples
Review Comment:
Might be good to clarify the behavior when this is exceeded. The sink will continuously restart and reject the record, to be used for data validation before sending to sink. Might be even mentioning that this is not expected in the normal use case of the sink. (As compared to maxBatchSize which can be tuned for performance reasons)
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+@PublicEvolving
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusAsyncHttpClientBuilder clientBuilder;
+ private final PrometheusRequestSigner requestSigner;
+ private final int maxBatchSizeInSamples;
+ private final String httpUserAgent;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+ private final String metricGroupName;
+
+ protected PrometheusSink(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ int maxRecordSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ PrometheusAsyncHttpClientBuilder clientBuilder,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ String metricGroupName) {
+ super(
+ elementConverter,
+ maxBatchSizeInSamples, // maxBatchSize,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes,
+ maxTimeInBufferMS,
+ maxRecordSizeInSamples // maxRecordSizeInBytes
+ );
+
+ Preconditions.checkArgument(maxInFlightRequests == 1, "maxInFlightRequests must be 1");
+
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ this.requestSigner = requestSigner;
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ this.clientBuilder = clientBuilder;
+ this.httpUserAgent = httpUserAgent;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ this.metricGroupName = metricGroupName;
+ }
+
+ public int getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
Review Comment:
can this be `private`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.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.prometheus.sink;
+
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
Review Comment:
Let's annotate this as `@Internal`
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/PrometheusSinkWriteException.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+/** Exception during writing to Prometheus Remote-Write endpoint. */
+public class PrometheusSinkWriteException extends RuntimeException {
Review Comment:
`@Internal`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/HttpResponseCallback.java:
##########
@@ -0,0 +1,188 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Callback handling the outcome of the http async request.
+ *
+ * <p>This class implements the error handling behaviour, based on the configuration in {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}. Depending on the condition, the sink may throw an
+ * exception and cause the job to fail, or log the condition to WARN, increment the counters and
+ * continue with the next request.
+ *
+ * <p>In any case, every write-request either entirely succeed or fail. Partial failures are not
+ * handled.
+ *
+ * <p>In no condition a write-request is re-queued for the AsyncSink to reprocess: this would cause
+ * out of order writes that would be rejected by Prometheus.
+ *
+ * <p>Note that the http async client retries, based on the configured retry policy. The callback is
+ * called with an outcome of *completed* either when the request has succeeded or the max retry
+ * limit has been exceeded. It is responsibility of the callback distinguishing between these
+ * conditions.
+ */
+class HttpResponseCallback implements FutureCallback<SimpleHttpResponse> {
Review Comment:
Let's annotate this as `@Internal`
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,260 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in
+order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering ecc.
+
+For efficiency, the sink **does not do any validation or reordering** of the input. It's responsibility
+of the application ensuring that input is well-formed.
+
+Any malformed data will be rejected on write to Prometheus. Depending on
+the [error handling behaviours](#error-handling-behavior)
+configured, the sink will throw an exception stopping the job (default), or drop the entire write-request, log the fact,
+and continue.
+
+For complete details about these constraints, refer to
+the [remote-write specifications](https://prometheus.io/docs/concepts/remote_write_spec/).
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of
+5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential
+backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit, depending
+on
+the configured [error handling behaviour](#error-handling-behavior) for "Max retries exceeded", the sink will either
+throw
+an exception (`FAIL`, default behaviour), or **discard the entire write-request**, log a warning and continue. See
+[error handling behaviour](#error-handling-behavior), below, for further details.
+
+### Initializing the sink
+
+Example of sink initialisation (for documentation purposes, we are setting all parameters to their default values):
+Sink
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500) // Batch size (write-request size), in samples (default: 500)
+ .setMaxRecordSizeInSamples(500) // Max sink input record size, in samples (default: 500), must be <= maxBatchSizeInSamples
+ .setMaxTimeInBufferMS(5000) // Max time a time-series is buffered for batching (default: 5000 ms)
+ .setRetryConfiguration(RetryConfiguration.builder()
+ .setInitialRetryDelayMS(30L) // Initial retry delay (default: 30 ms)
+ .setMaxRetryDelayMS(5000L) // Maximum retray delay, with exponential backoff (default: 5000 ms)
Review Comment:
nit: retry delay
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ // Max batch size, in number of samples
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ // Max time a record is buffered
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ // Max nr of requestEntry that will be buffered
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS = 1000;
+ // Metric Group name added to the custom metrics
+ private static final String DEFAULT_METRIC_GROUP_NAME = "Prometheus";
+
+ // Max in-flight requests is always = 1, to retain ordering
+ private static final int MAX_IN_FLIGHT_REQUESTS = 1;
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+ private String httpUserAgent = null;
+ private SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig = null;
+ private String metricGroupName = null;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples()).orElse(getMaxBatchSizeInSamples());
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ String actualHttpUserAgent =
+ Optional.ofNullable(getHttpUserAgent())
+ .orElse(PrometheusRemoteWriteHttpRequestBuilder.DEFAULT_USER_AGENT);
+
+ SinkWriterErrorHandlingBehaviorConfiguration actualErrorHandlingBehaviorConfig =
+ Optional.ofNullable(errorHandlingBehaviorConfig)
+ .orElse(SinkWriterErrorHandlingBehaviorConfiguration.DEFAULT_BEHAVIORS);
+
+ String actualMetricGroupName =
+ Optional.ofNullable(metricGroupName).orElse(DEFAULT_METRIC_GROUP_NAME);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}\n\t\thttpUserAgent={}"
+ + "\n\t\tErrorHandlingBehaviour: onMaxRetryExceeded={}, onHttpClientIOFailure={}, onNonRetriableError={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig.getOnMaxRetryExceeded(),
+ actualErrorHandlingBehaviorConfig.getOnHttpClientIOFail(),
+ actualErrorHandlingBehaviorConfig.getOnPrometheusNonRetriableError());
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig,
+ actualMetricGroupName);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setHttpUserAgent(String httpUserAgent) {
+ this.httpUserAgent = httpUserAgent;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setErrorHandlingBehaviourConfiguration(
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig) {
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMetricGroupName(String metricGroupName) {
+ this.metricGroupName = metricGroupName;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ public String getHttpUserAgent() {
+ return httpUserAgent;
+ }
+
+ public SinkWriterErrorHandlingBehaviorConfiguration getErrorHandlingBehaviorConfig() {
+ return errorHandlingBehaviorConfig;
+ }
+
+ public String getMetricGroupName() {
+ return metricGroupName;
+ }
Review Comment:
Can we remove the `get` methods on the builder?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/OnErrorBehavior.java:
##########
@@ -0,0 +1,27 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+/**
+ * Defines the behaviour when an error is encountered: discard the offending request and continue,
+ * or fail, throwing an exception.
+ */
+public enum OnErrorBehavior {
Review Comment:
`@PublicEvolving`. Actually let's put this under a `ConfigOption` class
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/http/PrometheusAsyncHttpClientBuilder.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.config.TlsConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+/**
+ * Builder for async http client that will retry, based on the {@link RemoteWriteRetryStrategy}
+ * specified.
+ */
+public class PrometheusAsyncHttpClientBuilder implements Serializable {
Review Comment:
`@PublicEvolving`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeriesLabelsAndMetricNameKeySelector.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.java.functions.KeySelector;
+
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+/**
+ * Implementation of KeySelector ensuring the {@link PrometheusTimeSeries} with the same set of
+ * labels end up in the same partition.
+ *
+ * <p>For using the sink with parallelism > 1, the input of the sink must be a keyedStream using
+ * this KeySelector to extract the key. This guarantees TimeSeries with the same set of labels are
+ * written to Prometheus in the same order they are sent to the sink.
+ *
+ * <p>The partition key is the hash of all labels AND the metricName. The metricName is added as
+ * additional label by the sink, before writing to Prometheus.
+ */
+public class PrometheusTimeSeriesLabelsAndMetricNameKeySelector
Review Comment:
`@PublicEvolving`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/SinkWriterErrorHandlingBehaviorConfiguration.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+import static org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior.FAIL;
+
+/**
+ * Configure the error-handling behavior of the writer, for different types of error. Also defines
+ * default behaviors.
+ */
+public class SinkWriterErrorHandlingBehaviorConfiguration implements Serializable {
Review Comment:
`@PublicEvolving`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/http/RetryConfiguration.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.prometheus.sink.http;
+
+import java.io.Serializable;
+
+/** Defines the retry strategy configuration. */
+public class RetryConfiguration implements Serializable {
Review Comment:
Can we just make this a set of `ConfigOptions`?
##########
pom.xml:
##########
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-parent</artifactId>
+ <version>1.0.0</version>
+ </parent>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <name>Flink Prometheus</name>
+ <modules>
+ <module>flink-connector-prometheus</module>
+ <module>flink-connector-prometheus-request-signer-amp</module>
+ </modules>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.18.1</flink.version>
Review Comment:
Let's make this `1.19.1`
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/PrometheusSinkWriteException.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+/** Exception during writing to Prometheus Remote-Write endpoint. */
+public class PrometheusSinkWriteException extends RuntimeException {
+
+ private final String reason;
+ private final int httpStatusCode;
+ private final String httpReasonPhrase;
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final String httpResponseBody;
+
+ public PrometheusSinkWriteException(String reason, int timeSeriesCount, long sampleCount) {
+ super("Reason: " + reason);
+ this.reason = reason;
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.httpStatusCode = -1;
+ this.httpReasonPhrase = "";
+ this.httpResponseBody = "";
+ }
+
+ public PrometheusSinkWriteException(
+ String reason, int timeSeriesCount, long sampleCount, Exception cause) {
+ super("Reason: " + reason, cause);
+ this.reason = reason;
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.httpStatusCode = -1;
+ this.httpReasonPhrase = "";
+ this.httpResponseBody = "";
+ }
+
+ public PrometheusSinkWriteException(
+ String reason,
+ int httpStatusCode,
+ String httpReasonPhrase,
+ int timeSeriesCount,
+ long sampleCount,
+ String httpResponseBody) {
+ super(
+ String.format(
+ "Reason: %s. Http response: %d,%s (%s) .The offending write-request contains %d time-series and %d samples",
+ reason,
+ httpStatusCode,
+ httpReasonPhrase,
+ httpResponseBody,
+ timeSeriesCount,
+ sampleCount));
+ this.reason = reason;
+ this.httpStatusCode = httpStatusCode;
+ this.httpReasonPhrase = httpReasonPhrase;
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.httpResponseBody = httpResponseBody;
+ }
+
+ public String getReason() {
+ return reason;
+ }
+
+ public int getHttpStatusCode() {
+ return httpStatusCode;
+ }
+
+ public String getHttpReasonPhrase() {
+ return httpReasonPhrase;
+ }
+
+ public int getTimeSeriesCount() {
+ return timeSeriesCount;
+ }
+
+ public long getSampleCount() {
+ return sampleCount;
+ }
+
+ public String getHttpResponseBody() {
+ return httpResponseBody;
+ }
Review Comment:
can we remove these?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeriesLabelsAndMetricNameKeySelector.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.java.functions.KeySelector;
+
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+/**
+ * Implementation of KeySelector ensuring the {@link PrometheusTimeSeries} with the same set of
+ * labels end up in the same partition.
+ *
+ * <p>For using the sink with parallelism > 1, the input of the sink must be a keyedStream using
+ * this KeySelector to extract the key. This guarantees TimeSeries with the same set of labels are
+ * written to Prometheus in the same order they are sent to the sink.
+ *
+ * <p>The partition key is the hash of all labels AND the metricName. The metricName is added as
+ * additional label by the sink, before writing to Prometheus.
+ */
+public class PrometheusTimeSeriesLabelsAndMetricNameKeySelector
Review Comment:
Can we also name this something smaller? Like `PrometheusKeySelector`?
##########
pom.xml:
##########
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-parent</artifactId>
+ <version>1.0.0</version>
+ </parent>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <name>Flink Prometheus</name>
+ <modules>
+ <module>flink-connector-prometheus</module>
+ <module>flink-connector-prometheus-request-signer-amp</module>
+ </modules>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.18.1</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ <aws.sdkv1.version>1.12.570</aws.sdkv1.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <build>
+ <plugins>
+ <plugin>
Review Comment:
Could we copy over the other plugins here too ?
https://github.com/apache/flink-connector-aws/blob/main/pom.xml#L421-L477
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/metrics/SinkMetricsCallback.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.prometheus.sink.metrics;
+
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.metrics.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Callback updating {@link SinkMetrics} on specific request outcomes. */
+public class SinkMetricsCallback {
Review Comment:
`@Internal`?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757532179
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
Review Comment:
`@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757525575
##########
flink-connector-prometheus-request-signer-amp/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerForAMP.java:
##########
@@ -0,0 +1,347 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
Lets ensure that the license headers are added to all 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1751692587
##########
flink-connector-prometheus-request-signer-amp/README.md:
##########
@@ -0,0 +1,30 @@
+## Request Signer for Amazon Managed Prometheus (AMP)
+
+Request signer implementation for Amazon Managed Prometheus (AMP)
+
+The signer retrieves AWS credentials using `com.amazonaws.auth.DefaultAWSCredentialsProviderChain` and automatically
+supports session credentials.
+
+The Flink application requires `RemoteWrite` permissions to the AMP workspace (e.g. `AmazonPromethusRemoteWriteAccess`
+policy).
+
+### Sample usage
+
+To enable request signing for Amazon Managed Prometheus, and instance of `AmazonManagedPrometheusWriteRequestSigner`
+must be provided when building the `PrometheusSink` instance. The only required parameters are the AWS region and the
+AMP remote-write URL.
+
+```java
+
+// AWS region of the AMP workspace
+String prometheusRegion = "us-east-1";
+
+// Remote-Write URL of the AMP workspace
+String prometheusRemoteWriteUrl = "https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-091245678-9abc-def0-1234-56789abcdef0/api/v1/remote_write";
+
+// Build the sink to AMP using the request signer
+AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> sink = PrometheusSink.builder()
+ .setPrometheusRemoteWriteUrl(prometheusRemoteWriteUrl)
+ .setRequestSigner(new AmazonManagedPrometheusWriteRequestSigner(prometheusRemoteWriteUrl, prometheusRegion))
Review Comment:
LOVE how easy this interface is! :D
##########
README.md:
##########
@@ -2,12 +2,27 @@
This repository contains the official Apache Flink Prometheus connector.
+* [More details](flink-connector-prometheus/README.md) about the connector and its usage.
+* [Example application](flink-connector-prometheus/src/test/java/org/apache/flink/connector/prometheus/sink/examples/DataStreamExample.java)
+ demonstrating the usage of the connector.
+
## Apache Flink
Apache Flink is an open source stream processing framework with powerful stream- and batch-processing capabilities.
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./flink-connector-prometheus): Flink Prometheus Connector implementation; supports optional
+ request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream
Review Comment:
This needs to change.
##########
flink-connector-prometheus-request-signer-amp/pom.xml:
##########
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : Amazon Managed Prometheus Request Signer</name>
+ <artifactId>flink-connector-prometheus-request-signer-amp</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <aws.sdkv2.version>2.25.69</aws.sdkv2.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>bom</artifactId>
+ <version>${aws.sdkv2.version}</version>
Review Comment:
nice! :D
##########
flink-connector-prometheus-request-signer-amp/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,86 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+ // Header names
+ private static final String X_AMZ_CONTENT_SHA_256 = "x-amz-content-sha256";
+ private static final String AUTHORIZATION = "Authorization";
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Creates a signer instance using DefaultAWSCredentialsProviderChain.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(awsRegion), "Missing or blank AMP workspace region");
Review Comment:
nit: we can phrase it something like `remoteWriteUrl cannot be null or empty`
##########
flink-connector-prometheus-request-signer-amp/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,86 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+ // Header names
+ private static final String X_AMZ_CONTENT_SHA_256 = "x-amz-content-sha256";
+ private static final String AUTHORIZATION = "Authorization";
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Creates a signer instance using DefaultAWSCredentialsProviderChain.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(awsRegion), "Missing or blank AMP workspace region");
+ Preconditions.checkNotNull(
Review Comment:
I think this is supposed to be `Preconditions.checkArgument(` . We should also have unit tests for this.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757532715
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/RequestEntrySizeUtils.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.util.Collection;
+
+/** Collection of methods to calculate the sink RequestEntry "size". */
+public class RequestEntrySizeUtils {
Review Comment:
`@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757533031
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteResponseClassifier.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.hc.core5.http.HttpResponse;
+
+/** Classify http responses based on the status code. */
+public class RemoteWriteResponseClassifier {
Review Comment:
`@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757527855
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/RequestHeaderTestUtil.java:
##########
@@ -0,0 +1,21 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class RequestHeaderTestUtil {
Review Comment:
License header + `@Internal`
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/RequestHeaderTestUtil.java:
##########
@@ -0,0 +1,21 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class RequestHeaderTestUtil {
Review Comment:
License header + `@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1464965767
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sing a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
Review Comment:
Added an example of usage in the signer README
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1469814589
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilderTest.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.hc.core5.http.HttpHeaders;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
Review Comment:
There is still a test with WireMock to test the http request handling stack, including the async http client behaviour on specific responses, that would have been otherwise untestable.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486713717
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(awsRegion), "Missing or blank AMP workspace region");
+ Preconditions.checkNotNull(
+ StringUtils.isNotBlank(remoteWriteUrl),
+ "Missing or blank AMP workspace remote-write URL");
+ this.awsRegion = awsRegion;
+ try {
+ this.remoteWriteUrl = new URL(remoteWriteUrl);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException(
+ "Invalid AMP remote-write URL: " + remoteWriteUrl, e);
+ }
+ }
+
+ /**
+ * Add the additional Http request headers required by Amazon Managed Prometheus:
+ * 'x-amz-content-sha256', 'Host', 'X-Amz-Date', 'x-amz-security-token' and 'Authorization`.
+ *
+ * @param requestHeaders original Http request headers. It must be mutable. For efficiency, any
+ * new header is added to the map, instead of making a copy.
+ * @param requestBody request body, already compressed
+ */
+ @Override
+ public void addSignatureHeaders(Map<String, String> requestHeaders, byte[] requestBody) {
+ byte[] contentHash = AWS4SignerBase.hash(requestBody);
+ String contentHashString = BinaryUtils.toHex(contentHash);
+ requestHeaders.put(
+ "x-amz-content-sha256",
+ contentHashString); // this header must be included before generating the
+ // Authorization header
+
+ DefaultAWSCredentialsProviderChain credsChain = new DefaultAWSCredentialsProviderChain();
Review Comment:
Should this be made configurable? Some use cases may require specific credentials provider implementation.
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ *
+ * @return
Review Comment:
Missing description of returned value?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/prometheus/Remote.java:
##########
@@ -0,0 +1,6661 @@
+/*
Review Comment:
Should original `*.proto` files also be added here? With a way to generate java files.
This way it will be clearer how to update this code if API change in the future releases.
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
Review Comment:
Is this comment required?
> JavaDocs should not state meaningless information (just to satisfy the Checkstyle checker).
https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#comments
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501903310
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(...).
+ * In our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkMetrics metrics;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkMetrics metrics,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ metrics,
+ requestSigner,
+ httpUserAgent,
+ errorHandlingBehaviorConfig,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkMetrics metrics,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner, httpUserAgent);
+ this.asyncHttpClient = asyncHttpClient;
+ this.metrics = metrics;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
Review Comment:
Can you replace this with a more specific exception? Same comment to all other `RuntimeException` usages
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501905941
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
Review Comment:
Is this the correct groupId?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501900684
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/SinkMetrics.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.MetricGroup;
+
+/** Wraps all metrics in a single class. */
+public class SinkMetrics {
+ private final Counter[] counters;
+
+ private SinkMetrics(Counter[] counters) {
+ this.counters = counters;
+ }
+
+ public void inc(SinkCounter counter, long value) {
+ counters[counter.ordinal()].inc(value);
+ }
+
+ public void inc(SinkCounter counter) {
+ counters[counter.ordinal()].inc();
+ }
+
+ /** Register all custom sink metrics and return an of this wrapper class. */
+ public static SinkMetrics registerSinkMetrics(MetricGroup metrics) {
+ // Register all counters
+ Counter[] counters = new Counter[SinkCounter.values().length];
+ for (SinkCounter metric : SinkCounter.values()) {
+ counters[metric.ordinal()] = metrics.counter(metric.getMetricName());
+ }
+ return new SinkMetrics(counters);
+ }
+
+ /** Enum defining all sink counters. */
+ public enum SinkCounter {
+ // Total number of Samples that were dropped because of not being retriable errors in
+ // Prometheus
Review Comment:
Here and below: replace comment with JavaDoc
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-1944280510
@hlteoh37 @z3d1k please have a look, I pushes the changes (in a single squashed commit).
I implemented all the requested changes except those I explicitly commented not to implement.
Happy to discuss
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632187848
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
Review Comment:
I don't think an integration test is useful for a user. And the lack of proper working examples is a common obstacle to the adoption from new to Flink.
This module is not supposed to be released in any form. Can't we just keep it as source, and possibly reference from the documentation?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632188645
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
Review Comment:
Renamed subdirectories to match artifact names
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2344434793
@hlteoh37 I addressed all remaining comments above
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1756601045
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeriesLabelsAndMetricNameKeySelector.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.java.functions.KeySelector;
+
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+/**
+ * Implementation of KeySelector ensuring the {@link PrometheusTimeSeries} with the same set of
+ * labels end up in the same partition.
+ *
+ * <p>For using the sink with parallelism > 1, the input of the sink must be a keyedStream using
+ * this KeySelector to extract the key. This guarantees TimeSeries with the same set of labels are
+ * written to Prometheus in the same order they are sent to the sink.
+ *
+ * <p>The partition key is the hash of all labels AND the metricName. The metricName is added as
+ * additional label by the sink, before writing to Prometheus.
+ */
+public class PrometheusTimeSeriesLabelsAndMetricNameKeySelector
Review Comment:
Do we pay by character in classname? ;)
This is long but it's meant to express exactly what it does: a key selector extracting a compound key with all labels and metric name from a Time Series.
A better name would be explaining why you should use it, but it's even more wordy: "key selector for sink parallelism > 1 to prevent accidental out of order writes"
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757526897
##########
flink-connector-prometheus/README.md:
##########
@@ -0,0 +1,259 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based
+on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering)
+and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements of Prometheus Remote-Write, the sink requires that users ensure that input data is in
+order and well-formed, before sending it to the sink.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, **the write request is rejected by Prometheus**.
+If the write request is rejected, depending on the configured [error handling behaviour](#error-handling-behavior) for
+"Prometheus non-retriable errors", the sink will either throw an exception (`FAIL`, default behavior) or discard the
+offending
+request and continue (`DISCARD_AND_CONTINUE`). See [error handling behaviour](#error-handling-behavior), below, for
+further details.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a
+single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series
+are discarded.
+The reason is Remote-Write
+specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of
+rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the
+offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+ samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels)
+ in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels
+ go to the same sink subtask. A `KeySelector` is provided to partition input correctly (
+ see [Partitioning](#partitioning), below).
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector
+expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java)
+POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to
+a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String } - MUST BE IN ORDER BY KEY
+* one or more `Samples` { value: double, timestamp: long } - MUST BE IN TIMESTAMP ORDER
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AccountID", accountId);
+
+for(
+Tuple2<Double, Long> sample :samples){
+ tsBuilder.
+
+addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+#### Input data validation
+
+Prometheus imposes strict constraints to the content sent to remote-write, including label format and ordering, sample
+time ordering etc.
+
+For efficiency, the sink **does not do any validation or reordering** of the input. It's responsibility
+of the application ensuring that input is well-formed.
+
+Any malformed data will be rejected on write to Prometheus. Depending on
+the [error handling behaviours](#error-handling-behavior)
+configured, the sink will throw an exception stopping the job (default), or drop the entire write-request, log the fact,
+and continue.
+
+For complete details about these constraints, refer to
+the [remote-write specifications](https://prometheus.io/docs/concepts/remote_write_spec/).
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of
+5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential
+backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit, depending
+on
+the configured [error handling behaviour](#error-handling-behavior) for "Max retries exceeded", the sink will either
+throw
+an exception (`FAIL`, default behaviour), or **discard the entire write-request**, log a warning and continue. See
+[error handling behaviour](#error-handling-behavior), below, for further details.
+
+### Initializing the sink
+
+Example of sink initialisation (for documentation purposes, we are setting all parameters to their default values):
+Sink
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setMaxBatchSizeInSamples(500) // Batch size (write-request size), in samples (default: 500)
+ .setMaxRecordSizeInSamples(500) // Max sink input record size, in samples (default: 500), must be <= maxBatchSizeInSamples - If exceeded the job will continuously fail and restart!
+ .setMaxTimeInBufferMS(5000) // Max time a time-series is buffered for batching (default: 5000 ms)
+ .setRetryConfiguration(RetryConfiguration.builder()
+ .setInitialRetryDelayMS(30L) // Initial retry delay (default: 30 ms)
+ .setMaxRetryDelayMS(5000L) // Maximum retry delay, with exponential backoff (default: 5000 ms)
+ .setMaxRetryCount(100) // Max number of retries (default: 100)
+ .build())
+ .setSocketTimeoutMs(5000) // Http client socket timeout (default: 5000 ms)
+ .setPrometheusRemoteWriteUrl(prometheusRemoteWriteUrl) // Remote-write URL
+ .setRequestSigner(new AmazonManagedPrometheusWriteRequestSigner(prometheusRemoteWriteUrl, prometheusRegion)) // Optional request signed (AMP request signer in this example)
+ .setErrorHandlingBehaviourConfiguration(SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ // Error handling behaviors. See description below, for more details. All behaviors default to FAIL
+ .onPrometheusNonRetriableError(OnErrorBehavior.FAIL)
+ .onMaxRetryExceeded(OnErrorBehavior.FAIL)
+ .onHttpClientIOFail(OnErrorBehavior.FAIL)
+ .build())
+ .setMetricGroupName("Prometheus") // Customizable metric-group suffix (default: "Prometheus")
+ .build();
+```
+
+### Partitioning
+
+When the sink has parallelism > 1, the stream must be partitioned so that all time-series with same labels go to the
+same
+sink operator sub-task. If this is not the case, samples may be written out-of-order, and be rejected by Prometheus.
+
+A `keyBy()` using the provided key selector,
+[`PrometheusTimeSeriesLabelsAndMetricNameKeySelector`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeriesLabelsAndMetricNameKeySelector.java),
+automatically partitions the time-series by labels.
+
+### Authentication and Request Signing (optional)
+
+The sink supports optional request-signing for authentication, implementing the
+[`PrometheusRequestSigner`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRequestSigner.java)
+interface.
+
+### Retriable errors
+
+The sink complies with Prometheus remote-write specs not retrying any request that return status codes `4xx`,
+except `429`,
+and retrying requests that return `5xx` or `429`, with an exponential backoff strategy.
+
+The retry strategy can be configured, as shown in the following snippet:
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ .setRetryConfiguration(RetryConfiguration.builder()
+ .setInitialRetryDelayMS(30L) // Initial retry delay (default: 30 ms)
+ .setMaxRetryDelayMS(5000L) // Maximum retray delay, with exponential backoff (default: 5000 ms)
+ .setMaxRetryCount(100) // Max number of retries (default: 100)
+ .build())
+ // ...
+ .build();
+```
+
+### Error handling behavior
+
+The behaviour of the sink, when an unrecoverable error happens while writing to Prometheus remote-write endpoint, is
+configurable.
+
+There are 3 error conditions:
+
+1. Prometheus returns a non-retriable error response (i.e. any `4xx` status code except `429`)
+2. Prometheus returns a retriable error response (i.e. `5xx` or `429`) but the max retry limit is exceeded
+3. The http client fails to complete the request, for an I/O error
+
+The default behavior of the sink, for all these three error conditions, is to `FAIL`: throw
+a `PrometheusSinkWriteException`, causing the job to fail.
+
+Optionally, for each of these error conditions independently, the sink can be configured to `DISCARD_AND_CONTINUE`: "
+log, discard the offending request and continue".
+
+The error handling behaviors can be configured when creating the instance of the sink, as shown in this snipped:
+
+```java
+PrometheusSink sink = PrometheusSink.builder()
+ // ...
+ .setErrorHandlingBehaviourConfiguration(SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onPrometheusNonRetriableError(OnErrorBehavior.DISCARD_AND_CONTINUE)
+ .onMaxRetryExceeded(OnErrorBehavior.DISCARD_AND_CONTINUE)
+ .onHttpClientIOFail(OnErrorBehavior.DISCARD_AND_CONTINUE)
+ .build())
+ .build();
+```
+
+When configured for `DISCARD_AND_CONTINUE`, the sink will do the following:
+
+1. Log a message at `WARN` level, with information about the problem and the number of time-series and samples dropped
+2. Update the counters (see below)
+3. Drop the offending write-request
+4. Continue with the next request
+
+Note that there is no partial-failure condition: the entire write-request is discarded regardless what data in the
+request are causing the problem.
+Prometheus does not return sufficient information to automatically handle partial requests.
+
+### Metrics
+
+The sink exposes custom metrics, counting the samples and write-requests (batches) successfully written or discarded.
+
+* `numSamplesOut` number of samples successfully written to Prometheus
+* `numWriteRequestsOut` number of write-requests successfully written to Prometheus
+* `numWriteRequestsRetries` number of write requests retried due to a retriable error (e.g. throttling)
+* `numSamplesDropped` number of samples dropped, for any reasons
+* `numSamplesNonRetriableDropped` (when `onPrometheusNonRetriableError` is set to `DISCARD_AND_CONTINUE`) number of
+ samples dropped due to non-retriable errors
+* `numSamplesRetryLimitDropped` (when `onMaxRetryExceeded` is set to `DISCARD_AND_CONTINUE`) number of samples dropped
+ due to reaching the max number of retries
+* `numWriteRequestsPermanentlyFailed` number of write requests permanently failed, due to any reasons (non retryable,
+ max nr of retries)
+
+**Note**: the `numByteSend` does not measure the number of bytes, due to an internal limitation of the base sink.
Review Comment:
nit `numBytesOut`?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757525231
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/DummAwsSessionCredentialProvider.java:
##########
@@ -0,0 +1,29 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+
+/** Dummy AwsCredentialsProvider returning AwsSessionCredentials. */
+public class DummAwsSessionCredentialProvider implements AwsCredentialsProvider {
Review Comment:
nit: Dummy
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597510275
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.List;
+
+/** Retry strategy for the http client. */
+public class RemoteWriteRetryStrategy implements HttpRequestRetryStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(RemoteWriteRetryStrategy.class);
+
+ private static final List<Class<? extends IOException>> NON_RETRIABLE_EXCEPTIONS =
+ List.of(
+ InterruptedIOException.class,
+ UnknownHostException.class,
+ ConnectException.class,
+ NoRouteToHostException.class,
+ SSLException.class);
+
+ private final long initialRetryDelayMs;
+ private final long maxRetryDelayMs;
+ private final int maxRetryCount;
+
+ private final SinkMetrics counters;
+
+ public RemoteWriteRetryStrategy(RetryConfiguration retryConfiguration, SinkMetrics counters) {
+ this.initialRetryDelayMs = retryConfiguration.getInitialRetryDelayMS();
+ this.maxRetryDelayMs = retryConfiguration.getMaxRetryDelayMS();
+ this.maxRetryCount = retryConfiguration.getMaxRetryCount();
+ this.counters = counters;
+ }
+
+ @Override
+ public boolean retryRequest(
+ HttpRequest httpRequest, IOException e, int execCount, HttpContext httpContext) {
+ // Retry on any IOException except those considered non-retriable
+ var retry =
+ (execCount <= maxRetryCount) && !(NON_RETRIABLE_EXCEPTIONS.contains(e.getClass()));
+ LOG.debug(
+ "{} retry on {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ e.getClass(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public boolean retryRequest(HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ var retry =
+ (execCount <= maxRetryCount)
+ && RemoteWriteResponseClassifier.isRetriableErrorResponse(httpResponse);
+ LOG.debug(
+ "{} retry on response {} {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ httpResponse.getCode(),
+ httpResponse.getReasonPhrase(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public TimeValue getRetryInterval(
+ HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ long calculatedDelay = initialRetryDelayMs << (execCount - 1);
Review Comment:
I don't see much value in making the backoff strategy more sophisticated.
Prometheus Remote-write specs just say it "MUST use a backoff algorithm to prevent overwhelming the server".
Tweaking the `initialRetryIntervalMs` and `maxRetryDelayMs` will be enough to make the strategy more or less aggressive.
Also, I don't see much value in adding a jitter. There is one writer thread per subtask, and and it's very unlikely they will be synchronized when writing to the endpoint.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597473538
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+@Public
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusAsyncHttpClientBuilder clientBuilder;
+ private final PrometheusRequestSigner requestSigner;
+ private final int maxBatchSizeInSamples;
+ private final String httpUserAgent;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ protected PrometheusSink(
Review Comment:
Added a configurable metric group that gets appended after the `Sink__Writer` of AsyncSinkBase. I can't see how I can add a prefix
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597482298
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
Review Comment:
I added further explanations in the README about the behavior and the responsibility of sending well-formed data.
In any case, with the default error-handling behavior, if the application sends malformed data, the sink throws an exception when Prometheus rejects the write.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501897234
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+ private String httpUserAgent = null;
+ private SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig = null;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int maxInFlightRequest = 1;
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples())
+ .orElse(getMaxBatchSizeInSamples()); // By default, set max record size to
+ // max batch size (in samples)
Review Comment:
The comment repeats logic described in code. Is it required?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501896202
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
Review Comment:
nit: moving comment above statement will prevent formatter from splitting the line
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501903943
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.List;
+
+/** Retry strategy for the http client. */
Review Comment:
Please add more details on the retry strategy logic 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501906772
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
Review Comment:
artifactId does not represent connection to prometheus connector
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1450463846
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
Review Comment:
We shouldn't be dropping records here on a retryable error.
IMO we should either requeue the records, or propagate up the exception to fail the job.
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int maxInFlightRequest = 1;
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples())
+ .orElse(getMaxBatchSizeInSamples()); // By default, set max record size to
+ // max batch size (in samples)
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs);
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ /// Disable setting maxBatchSize, maxBatchSizeInBytes, and maxRecordSizeInBytes directly
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSize(int maxBatchSize) {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxBatchSizeInBytes is not supported by this sink");
Review Comment:
Should we add a comment on the reason why we disable it here?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS =
+ 1000; // Max nr of requestEntry that will be buffered
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int maxInFlightRequest = 1;
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples())
+ .orElse(getMaxBatchSizeInSamples()); // By default, set max record size to
+ // max batch size (in samples)
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs);
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ maxInFlightRequest,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ /// Disable setting maxBatchSize, maxBatchSizeInBytes, and maxRecordSizeInBytes directly
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSize(int maxBatchSize) {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxBatchSizeInBytes is not supported by this sink");
Review Comment:
After offline discussion, maybe we can do something like
```
Use setMaxBatchSizeInSamples() instead
```
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilderTest.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.hc.core5.http.HttpHeaders;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
Review Comment:
We don't recommend using Mockito in Flink. Usually we prefer creating test constructs to test actual behavior,
https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#avoid-mockito---use-reusable-test-implementations
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
Review Comment:
Should we add a default log here? In the event that `RemoteWriteResponseClassifier.isRetriableErrorResponse` and `RemoteWriteResponseClassifier.isNonRetriableErrorResponse` don't cover the entire set of responses?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,117 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
Let's use Flink's `@Public` annotation here
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
Review Comment:
After offline discussion, we agreed that maybe we can set the HttpCllient to a lower maxRetryCount (by default), and then if the maxRetry is exceeded, we can throw the Exception to restart the Flink job
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
+ }
+
+ // Never re-queue requests
+ requestResult.accept(Collections.emptyList());
+ }
+
+ @Override
+ public void failed(Exception ex) {
+ LOG.warn(
+ "Exception executing the remote-write (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount,
+ ex);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
+
+ @Override
+ public void cancelled() {
+ LOG.warn(
+ "Write request execution cancelled (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
Review Comment:
I wonder if we should also propagate the exception upwards here rather than swallowing it. For example, this might be triggered on interrupt / non-graceful shutdown of the async Http client
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37).append(name).append(value).toHashCode();
+ }
+ }
+
+ /** A single Sample. */
+ public static class Sample implements Serializable {
Review Comment:
we should override equals and hashcode here too
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
+ static class ResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> requestResult;
+ private final SinkCounters counters;
+
+ public ResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkCounters counters,
+ Consumer<List<Types.TimeSeries>> requestResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.requestResult = requestResult;
+ this.counters = counters;
+ }
+
+ @Override
+ public void completed(SimpleHttpResponse response) {
+ if (RemoteWriteResponseClassifier.isSuccessResponse(response)) {
+ LOG.debug(
+ "{},{} - successfully posted {} time-series, containing {} samples",
+ response.getCode(),
+ response.getReasonPhrase(),
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_OUT, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_OUT);
+ } else {
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+
+ String responseBody = response.getBodyText();
+ if (RemoteWriteResponseClassifier.isNonRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_NON_RETRIABLE_DROPPED, sampleCount);
+ } else if (RemoteWriteResponseClassifier.isRetriableErrorResponse(response)) {
+ LOG.warn(
+ "{},{} {} (after retry limit reached, discarded {} time-series, containing {} samples)",
+ response.getCode(),
+ response.getReasonPhrase(),
+ responseBody,
+ timeSeriesCount,
+ sampleCount);
+ counters.inc(NUM_SAMPLES_RETRY_LIMIT_DROPPED, sampleCount);
+ }
+ }
+
+ // Never re-queue requests
+ requestResult.accept(Collections.emptyList());
+ }
+
+ @Override
+ public void failed(Exception ex) {
+ LOG.warn(
+ "Exception executing the remote-write (discarded {} time-series containing {} samples)",
+ timeSeriesCount,
+ sampleCount,
+ ex);
+ counters.inc(NUM_SAMPLES_DROPPED, sampleCount);
+ counters.inc(NUM_WRITE_REQUESTS_PERMANENTLY_FAILED);
+ }
Review Comment:
Should we retry these failures / Propagate the exception up to transition the job to failed?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1487904426
##########
example-datastream-job/src/main/java/org/apache/flink/connector/prometheus/examples/DataStreamJob.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.prometheus.examples;
+
+import org.apache.flink.api.java.utils.ParameterTool;
+import org.apache.flink.configuration.ConfigOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.connector.prometheus.sink.PrometheusSink;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeries;
+import org.apache.flink.connector.prometheus.sink.PrometheusTimeSeriesLabelsAndMetricNameKeySelector;
+import org.apache.flink.connector.prometheus.sink.aws.AmazonManagedPrometheusWriteRequestSigner;
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/** Test application testing the Prometheus sink connector. */
+public class DataStreamJob {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DataStreamJob.class);
+
+ public static void main(String[] args) throws Exception {
+ StreamExecutionEnvironment env;
+
+ // Conditionally return a local execution environment with
+ if (args.length > 0 && Arrays.stream(args).anyMatch("--webUI"::equalsIgnoreCase)) {
+ Configuration conf = new Configuration();
+ conf.set(
+ ConfigOptions.key("rest.flamegraph.enabled").booleanType().noDefaultValue(),
+ true);
+ env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
+ } else {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ }
+
+ env.setParallelism(2);
+
+ ParameterTool applicationParameters = ParameterTool.fromArgs(args);
+
+ // Prometheus remote-write URL
+ String prometheusRemoteWriteUrl = applicationParameters.get("prometheusRemoteWriteUrl");
+ LOGGER.info("Prometheus URL:{}", prometheusRemoteWriteUrl);
+
+ // Optionally configure Amazon Managed Prometheus request signer
+ PrometheusRequestSigner requestSigner = null;
+ String ampAWSRegion = applicationParameters.get("awsRegion");
+ if (ampAWSRegion != null) {
+ requestSigner =
+ new AmazonManagedPrometheusWriteRequestSigner(
+ prometheusRemoteWriteUrl, ampAWSRegion);
+ LOGGER.info(
+ "Enable Amazon Managed Prometheus request-signer, region: {}", ampAWSRegion);
+ }
+
+ // Configure data generator
+ int generatorMinSamplesPerTimeSeries = 1;
+ int generatorMaxSamplesPerTimeSeries = 10;
+ int generatorNumberOfDummyInstances = 5;
+ long generatorPauseBetweenTimeSeriesMs = 100;
+ LOGGER.info(
+ "Data Generator configuration:"
+ + "\n\t\tMin samples per time series:{}\n\t\tMax samples per time series:{}\n\t\tPause between time series:{} ms"
+ + "\n\t\tNumber of dummy instances:{}",
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorPauseBetweenTimeSeriesMs,
+ generatorNumberOfDummyInstances);
+
+ Supplier<PrometheusTimeSeries> eventGenerator =
+ new SimpleInstanceMetricsTimeSeriesGenerator(
+ generatorMinSamplesPerTimeSeries,
+ generatorMaxSamplesPerTimeSeries,
+ generatorNumberOfDummyInstances)
+ .generator();
+
+ SourceFunction<PrometheusTimeSeries> source =
+ new FixedDelayDataGenertorSource<>(
Review Comment:
Fixed
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488419176
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializerTest.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class PrometheusStateSerializerTest {
+
+ private static final ElementConverter<PrometheusTimeSeries, Types.TimeSeries>
+ ELEMENT_CONVERTER = new PrometheusTimeSeriesConverter();
+
+ private static PrometheusTimeSeries getTestTimeSeries(int i) {
+ return PrometheusTimeSeries.builder()
+ .withMetricName("metric-name")
+ .addLabel("dimension-a", "value-" + i)
+ .addSample(i + 42.0, i + 1L)
+ .addSample(i + 3.14, i + 2L)
+ .build();
+ }
+
+ // This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
+ // the requestEntry "size"
+ // (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
+ // see
+ // https://github.com/apache/flink/blob/69e812688b43be9a0c4f79e6af81bc2d1d8a873e/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializer.java#L60
Review Comment:
Replaced with @link to the method.
This way we lose the pointer to the specific line, but okay
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488432583
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
Review Comment:
There other other validations that are more critical, like Labels must be in order by name and samples in order by timestamp, or Prometheus will reject them.
We kept these validations out of the implementation on purpose, because this object will be called a gazillion times, and this may impact performance.
In the docs, we explicitly say this is a responsibility of the application, like sending the time series in time order.
Either we decide to add validation to this class, paying the performance fee, or we leave this class unvalidated
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489284689
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ *
+ * @return
Review Comment:
@z3d1k not sure I see the value of generating the Protobuf classes from `.proto` file instead of hardwiring the generated classes, in this context.
The remote-write protocol is much more than the payload schema.
Any Prometheus remote-write protocol change will probably require changes to the code to adjust the behavior.
Also, generating the code from `.proto` would require to do the same also with GoGoProto.
This is the reason all Java Prometheus remote-write clients I found embed the generated classes in the code. e.g. https://github.com/m3dbx/prometheus_remote_client_java but you can find others
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1464922614
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
Review Comment:
This formatter is used to build the `x-amz-date` request header that must be in UTC, as documented here https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-elements.html#date
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757533937
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusSinkConfiguration;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Retry strategy for the http client.
+ *
+ * <p>Based on the http status code returned or the exception thrown, this strategy either retries
+ * with an exponential backoff strategy or immediately fail.
+ *
+ * <p>Response status codes are classified as retriable or non-retriable using {@link
+ * RemoteWriteResponseClassifier}.
+ *
+ * <p>All {@link IOException} are considered retriable, except for {@link InterruptedIOException},
+ * {@link UnknownHostException}, {@link ConnectException}, {@link NoRouteToHostException}, and
+ * {@link SSLException}.
+ */
+public class RemoteWriteRetryStrategy implements HttpRequestRetryStrategy {
Review Comment:
`@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501897657
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
+ * Protobuf-serialized representation of a {@link Types.TimeSeries TimeSeries}. In this
+ * implementation SIZEn is the size of the Protobuf serialization, in bytes, that does not match
Review Comment:
Typo: `SIZEn`, should be `SIZE`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597412465
##########
prometheus-connector/README.md:
##########
@@ -0,0 +1,189 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering) and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, the write request is rejected by Prometheus and data is discarded by the sink.
Review Comment:
Configuration is extensively documented below, in the README
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597414330
##########
prometheus-connector/README.md:
##########
@@ -0,0 +1,189 @@
+## Flink Prometheus connector (sink)
+
+Implementation of the Prometheus sink connector for DataStream API.
+
+The sink writes to Prometheus using the Remote-Write interface, based on [Remote-Write specifications version 1.0](https://prometheus.io/docs/concepts/remote_write_spec/)
+
+### Guarantees and input restrictions
+
+Due to the strict [ordering](https://prometheus.io/docs/concepts/remote_write_spec/#ordering) and [format](https://prometheus.io/docs/concepts/remote_write_spec/#labels) requirements
+of Prometheus Remote-Write, the sink guarantees that input data are written to Prometheus only if input data are in order and well-formed.
+
+For efficiency, the connector does not do any validation.
+If input is out of order or malformed, the write request is rejected by Prometheus and data is discarded by the sink.
+The connector will log a warning and count rejected data in custom metrics, but the data is discarded.
+
+The sink receives as input time-series, each containing one or more samples.
+To optimise the write throughput, input time-series are batched, in the order they are received, and written with a single write-request.
+
+If a write-request contains any out-of-order or malformed data, **the entire request is rejected** and all time series are discarded.
+The reason is Remote-Write specifications [explicitly forbids retrying](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff) of rejected write requests (4xx responses).
+and the Prometheus response does not contain enough information to efficiently partially retry the write, discarding the offending data.
+
+### Responsibilities of the application
+
+It is responsibility of the application sending the data to the sink in the correct order and format.
+
+1. Input time-series must be well-formed, e.g. only valid and non-duplicated labels,
+samples in timestamp order (see [Labels and Ordering](https://prometheus.io/docs/concepts/remote_write_spec/#labels) in Prometheus Remote-Write specs).
+2. Input time-series with identical labels are sent to the sink in timestamp order.
+3. If sink parallelism > 1 is used, the input stream must be partitioned so that all time-series with identical labels go to the same sink subtask. A `KeySelector` is provided to partition input correctly (see [Partitioning](#partitioning), below).
+
+
+#### Sink input objects
+
+To help sending well-formed data to the sink, the connector expect [`PrometheusTimeSeries`](./src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java) POJOs as input.
+
+Each `PrometheusTimeSeries` instance maps 1-to-1 to a [remote-write `TimeSeries`](https://prometheus.io/docs/concepts/remote_write_spec/#protocol). Each object contains:
+* exactly one `metericName`, mapped to the special `__name__` label
+* optionally, any number of additional labels { k: String, v:String }
+* one or more `Samples` { value: double, timestamp: long } - must be in timestamp order
+
+`PrometheusTimeSeries` provides a builder interface.
+
+```java
+
+// List<Tuple2<Double, Long>> samples = ...
+
+PrometheusTimeSeries.Builder tsBuilder = PrometheusTimeSeries.builder()
+ .withMetricName("CPU") // mapped to `__name__` label
+ .addLabel("InstanceID", instanceId)
+ .addLabel("AcccountID", accountId);
+
+for(Tuple2<Double, Long> sample : samples) {
+ tsBuilder.addSample(sample.f0, sample.f1);
+}
+
+PrometheusTimeSeries ts = tsBuilder.build();
+```
+
+
+**Important**: for efficiency, the builder does reorder the samples. It is responsibility of the application to **add samples in timestamp order**.
+
+### Batching, blocking writes and retry
+
+The sink batches multiple time-series into a single write-request, retaining the order..
+
+Batching is based on the number of samples. Each write-request contains up to 500 samples, with a max buffering time of 5 seconds
+(both configurable). The number of time-series doesn't matter.
+
+As by [Prometheus Remote-Write specifications](https://prometheus.io/docs/concepts/remote_write_spec/#retries-backoff),
+the sink retries 5xx and 429 responses. Retrying is blocking, to retain sample ordering, and uses and exponential backoff.
+
+The exponential backoff starts with an initial delay (default 30 ms) and increases it exponentially up to a max retry
+delay (default 5 sec). It continues retrying until the max number of retries is reached (default reties forever).
+
+On non-retriable error response (4xx, except 429, non retryable exceptions), or on reaching the retry limit,
+**the entire write-request**, containing the batch of time-series, **is dropped**.
+
+Every dropped request is logged at WARN level, including the reason provided by the remote-write endpoint.
Review Comment:
Added explanation
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597456357
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/HttpResponseCallback.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/**
+ * Callback handling the outcome of the http async request.
+ *
+ * <p>This class implements the error handling behaviour, based on the configuration in {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}. Depending on the condition, the sink may throw an
+ * exception and cause the job to fail, or log the condition to WARN, increment the counters and
+ * continue with the next request.
+ *
+ * <p>In any case, every write-request either entirely succeed or fail. Partial failures are not
+ * handled.
+ *
+ * <p>In no condition a write-request is re-queued for the AsyncSink to reprocess: this would cause
+ * out of order writes that would be rejected by Prometheus.
+ *
+ * <p>Note that the http async client retries, based on the configured retry policy. The callback is
+ * called with an outcome of *completed* either when the request has succeeded or the max retry
+ * limit has been exceeded. It is responsibility of the callback distinguishing between these
+ * conditions.
+ */
+class HttpResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private static final Logger LOG = LoggerFactory.getLogger(HttpResponseCallback.class);
+
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> reQueuedResult;
+ private final SinkMetrics metrics;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public HttpResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkMetrics metrics,
Review Comment:
Not exactly a minor change, because it has impact in many places. But definitely a good idea.
Implemented.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597479531
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializerTest.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class PrometheusStateSerializerTest {
+
+ private static final ElementConverter<PrometheusTimeSeries, Types.TimeSeries>
+ ELEMENT_CONVERTER = new PrometheusTimeSeriesConverter();
+
+ private static PrometheusTimeSeries getTestTimeSeries(int i) {
+ return PrometheusTimeSeries.builder()
+ .withMetricName("metric-name")
+ .addLabel("dimension-a", "value-" + i)
+ .addSample(i + 42.0, i + 1L)
+ .addSample(i + 3.14, i + 2L)
+ .build();
+ }
+
+ // This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
+ // the requestEntry "size"
+ // (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
+ // see
+ // https://github.com/apache/flink/blob/69e812688b43be9a0c4f79e6af81bc2d1d8a873e/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializer.java#L60
Review Comment:
Reviewing this, I put back the link to the implementation in GitHub.
What we want to show is the implementation, not the javadoc.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597508286
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(...).
+ * In our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkMetrics metrics;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkMetrics metrics,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ metrics,
+ requestSigner,
+ httpUserAgent,
+ errorHandlingBehaviorConfig,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkMetrics metrics,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner, httpUserAgent);
+ this.asyncHttpClient = asyncHttpClient;
+ this.metrics = metrics;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
Review Comment:
Replaced with a specific exception. It was actually the only generic `RuntimeException` thrown
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1467930051
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSink.java:
##########
@@ -0,0 +1,117 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+
+import java.util.Collection;
+
+/** Sink implementation accepting {@link PrometheusTimeSeries} as inputs. */
+public class PrometheusSink extends AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
Marked as @Public all the classes representing the public interface of the connector: `PrometheusSink`, `PrometheusTimeSeries`, and `PrometheusRequestSigner`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1464892473
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
Review Comment:
javax.crypto.Mac was introduced in Java 1.4 and is still included in Java 18. I don't think we are limiting any versions.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488409080
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/RequestEntrySizeUtils.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.util.Collection;
+
+/** Collection of methods to calculate the sink RequestEntry "size". */
+public class RequestEntrySizeUtils {
+
+ /**
+ * Size of a request entry (a {@link Types.TimeSeries time-series}) for the purpose of batching.
+ * Count the number of {@link Types.Sample samples}
+ *
+ * @param requestEntry a time-series
+ * @return number of Samples in the TimeSeries
+ */
+ public static long requestSizeForBatching(Types.TimeSeries requestEntry) {
+ return requestEntry.getSamplesCount();
+ }
+
+ /**
+ * Serialized size of a request entry {@link Types.TimeSeries TimeSeries}: the number of bytes
+ * of the protobuf- serialized representation of the TimeSeries.
+ *
+ * @param requestEntry a time-series
+ * @return number of bytes
+ */
+ public static long requestSerializedSize(Types.TimeSeries requestEntry) {
+ return requestEntry.getSerializedSize();
+ }
+
+ /**
+ * Count the number of {@link Types.Sample samples} in a collection of {@link Types.TimeSeries
+ * time-series} (a batch).
+ *
+ * @param requestEntries collection of time-series
+ * @return number of samples
+ */
+ public static long countSamples(Collection<Types.TimeSeries> requestEntries) {
+ return requestEntries.stream()
+ .mapToLong(RequestEntrySizeUtils::requestSizeForBatching)
+ .sum();
+ }
Review Comment:
Added tests for RequestEntrySizeUtilsTest 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488419176
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializerTest.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class PrometheusStateSerializerTest {
+
+ private static final ElementConverter<PrometheusTimeSeries, Types.TimeSeries>
+ ELEMENT_CONVERTER = new PrometheusTimeSeriesConverter();
+
+ private static PrometheusTimeSeries getTestTimeSeries(int i) {
+ return PrometheusTimeSeries.builder()
+ .withMetricName("metric-name")
+ .addLabel("dimension-a", "value-" + i)
+ .addSample(i + 42.0, i + 1L)
+ .addSample(i + 3.14, i + 2L)
+ .build();
+ }
+
+ // This method uses the same implementation as PrometheusSinkWriter.getSizeInBytes() to extract
+ // the requestEntry "size"
+ // (i.e. the number of Samples). This is the "size" used in RequestEntryWrapper
+ // see
+ // https://github.com/apache/flink/blob/69e812688b43be9a0c4f79e6af81bc2d1d8a873e/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/AsyncSinkWriterStateSerializer.java#L60
Review Comment:
Replaced with @link to the method.
But I am not convinced it makes sense: the link was to a specific source code to show how the size is used in the implementation of a method, not to the JavaDoc of that method
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489092917
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerBase.java:
##########
@@ -0,0 +1,290 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/** Common methods and properties for all AWS4 signer variants. */
+public abstract class AWS4SignerBase {
+
+ /** SHA256 hash of an empty request body. */
+ public static final String EMPTY_BODY_SHA256 =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
+
+ public static final String SCHEME = "AWS4";
+ public static final String ALGORITHM = "HMAC-SHA256";
+ public static final String TERMINATOR = "aws4_request";
+
+ /** format strings for the date/time and date stamps required during signing. */
+ public static final String ISO_8601_BASIC_FORMAT = "yyyyMMdd'T'HHmmss'Z'";
+
+ public static final String DATE_STRING_FORMAT = "yyyyMMdd";
+
+ protected URL endpointUrl;
+ protected String httpMethod;
+ protected String serviceName;
+ protected String regionName;
+
+ protected final SimpleDateFormat dateTimeFormat;
+ protected final SimpleDateFormat dateStampFormat;
+
+ /**
+ * Create a new AWS V4 signer.
+ *
+ * @param endpointUrl The service endpoint, including the path to any resource.
+ * @param httpMethod The HTTP verb for the request, e.g. GET.
+ * @param serviceName The signing name of the service, e.g. 's3'.
+ * @param regionName The system name of the AWS region associated with the endpoint, e.g.
+ * us-east-1.
+ */
+ public AWS4SignerBase(
+ URL endpointUrl, String httpMethod, String serviceName, String regionName) {
+ this.endpointUrl = endpointUrl;
+ this.httpMethod = httpMethod;
+ this.serviceName = serviceName;
+ this.regionName = regionName;
+
+ dateTimeFormat = new SimpleDateFormat(ISO_8601_BASIC_FORMAT);
+ dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ dateStampFormat = new SimpleDateFormat(DATE_STRING_FORMAT);
+ dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));
+ }
+
+ /**
+ * Returns the canonical collection of header names that will be included in the signature. For
+ * AWS4, all header names must be included in the process in sorted canonicalized order.
+ */
+ protected static String getCanonicalizeHeaderNames(Map<String, String> headers) {
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ StringBuilder buffer = new StringBuilder();
+ for (String header : sortedHeaders) {
+ if (buffer.length() > 0) {
+ buffer.append(";");
+ }
+ buffer.append(header.toLowerCase());
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Computes the canonical headers with values for the request. For AWS4, all headers must be
+ * included in the signing process.
+ */
+ protected static String getCanonicalizedHeaderString(Map<String, String> headers) {
+ if (headers == null || headers.isEmpty()) {
+ return "";
+ }
+
+ // step1: sort the headers by case-insensitive order
+ List<String> sortedHeaders = new ArrayList<String>();
+ sortedHeaders.addAll(headers.keySet());
+ Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER);
+
+ // step2: form the canonical header:value entries in sorted order.
+ // Multiple white spaces in the values should be compressed to a single
+ // space.
+ StringBuilder buffer = new StringBuilder();
+ for (String key : sortedHeaders) {
+ buffer.append(
+ key.toLowerCase().replaceAll("\\s+", " ")
+ + ":"
+ + headers.get(key).replaceAll("\\s+", " "));
+ buffer.append("\n");
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the canonical request string to go into the signer process; this consists of several
+ * canonical sub-parts.
+ *
+ * @return
Review Comment:
Removed `@return`, that was actually redundant with the description above
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1486091676
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/InspectableMetricGroupAssertions.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.prometheus.sink;
+
+import org.junit.jupiter.api.Assertions;
+
+/** Assertions to verify whether metrics of a {@link InspectableMetricGroup} has been modified. */
+public class InspectableMetricGroupAssertions {
+ public static void assertCounterWasIncremented(
+ InspectableMetricGroup metricGroup, SinkMetrics.SinkCounter sinkCounter) {
+ String counterName = sinkCounter.getMetricName();
+ Assertions.assertTrue(
+ metricGroup.getCounterCount(counterName) > 0,
+ "The counter " + counterName + " has not been incremented");
+ }
+
+ public static void assertCounterCount(
+ long expectedCounterCount,
+ InspectableMetricGroup metricGroup,
+ SinkMetrics.SinkCounter sinkCounter) {
+ String counterName = sinkCounter.getMetricName();
+ long actualCounterCount = metricGroup.getCounterCount(counterName);
+ Assertions.assertEquals(
+ expectedCounterCount,
+ actualCounterCount,
+ "The counter "
+ + counterName
+ + " was expected tp be "
Review Comment:
```suggestion
+ " was expected to be "
```
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632777604
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
Review Comment:
We have done it in tests previously to mitigate the "clutter" problem, and difficulty when creating the connector distribution jars.
https://github.com/apache/flink-connector-aws/tree/main/flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/sink/examples
We could do something similar and point to them via README, OR we could add a maven profile that only adds the examples module for PR / nightlies
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1756591395
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.http.RetryConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
+ extends AsyncSinkBaseBuilder<
+ PrometheusTimeSeries, Types.TimeSeries, PrometheusSinkBuilder> {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkBuilder.class);
+
+ // Max batch size, in number of samples
+ private static final int DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES = 500;
+ // Max time a record is buffered
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ // Max nr of requestEntry that will be buffered
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS = 1000;
+ // Metric Group name added to the custom metrics
+ private static final String DEFAULT_METRIC_GROUP_NAME = "Prometheus";
+
+ // Max in-flight requests is always = 1, to retain ordering
+ private static final int MAX_IN_FLIGHT_REQUESTS = 1;
+
+ private String prometheusRemoteWriteUrl;
+ private RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+ private PrometheusRequestSigner requestSigner = null;
+ private Integer maxBatchSizeInSamples;
+ private Integer maxRecordSizeInSamples;
+ private String httpUserAgent = null;
+ private SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig = null;
+ private String metricGroupName = null;
+
+ @Override
+ public AsyncSinkBase<PrometheusTimeSeries, Types.TimeSeries> build() {
+
+ int actualMaxBatchSizeInSamples =
+ Optional.ofNullable(getMaxBatchSizeInSamples())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_SAMPLES);
+ int actualMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS);
+ long actualMaxTimeInBufferMS =
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS);
+
+ int actualMaxRecordSizeInSamples =
+ Optional.ofNullable(getMaxRecordSizeInSamples()).orElse(getMaxBatchSizeInSamples());
+
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(getSocketTimeoutMs())
+ .orElse(PrometheusAsyncHttpClientBuilder.DEFAULT_SOCKET_TIMEOUT_MS);
+
+ String actualHttpUserAgent =
+ Optional.ofNullable(getHttpUserAgent())
+ .orElse(PrometheusRemoteWriteHttpRequestBuilder.DEFAULT_USER_AGENT);
+
+ SinkWriterErrorHandlingBehaviorConfiguration actualErrorHandlingBehaviorConfig =
+ Optional.ofNullable(errorHandlingBehaviorConfig)
+ .orElse(SinkWriterErrorHandlingBehaviorConfiguration.DEFAULT_BEHAVIORS);
+
+ String actualMetricGroupName =
+ Optional.ofNullable(metricGroupName).orElse(DEFAULT_METRIC_GROUP_NAME);
+
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(prometheusRemoteWriteUrl),
+ "Missing or blank Prometheus Remote-Write URL");
+ checkValidRemoteWriteUrl(prometheusRemoteWriteUrl);
+ Preconditions.checkNotNull(retryConfiguration, "Missing retry configuration");
+ Preconditions.checkArgument(
+ actualMaxBatchSizeInSamples > 0, "Max batch size (in samples) must be positive");
+ Preconditions.checkArgument(
+ actualMaxRecordSizeInSamples <= actualMaxBatchSizeInSamples,
+ "Max record size (in samples) must be <= Max batch size");
+
+ LOG.info(
+ "Prometheus sink configuration:"
+ + "\n\t\tmaxBatchSizeInSamples={}\n\t\tmaxRecordSizeInSamples={}"
+ + "\n\t\tmaxTimeInBufferMs={}\n\t\tmaxInFlightRequests={}\n\t\tmaxBufferedRequests={}"
+ + "\n\t\tinitialRetryDelayMs={}\n\t\tmaxRetryDelayMs={}\n\t\tmaxRetryCount={}"
+ + "\n\t\tsocketTimeoutMs={}\n\t\thttpUserAgent={}"
+ + "\n\t\tErrorHandlingBehaviour: onMaxRetryExceeded={}, onHttpClientIOFailure={}, onNonRetriableError={}",
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ retryConfiguration.getInitialRetryDelayMS(),
+ retryConfiguration.getMaxRetryDelayMS(),
+ retryConfiguration.getMaxRetryCount(),
+ socketTimeoutMs,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig.getOnMaxRetryExceeded(),
+ actualErrorHandlingBehaviorConfig.getOnHttpClientIOFail(),
+ actualErrorHandlingBehaviorConfig.getOnPrometheusNonRetriableError());
+
+ return new PrometheusSink(
+ new PrometheusTimeSeriesConverter(),
+ MAX_IN_FLIGHT_REQUESTS,
+ actualMaxBufferedRequests,
+ actualMaxBatchSizeInSamples,
+ actualMaxRecordSizeInSamples,
+ actualMaxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ new PrometheusAsyncHttpClientBuilder(retryConfiguration)
+ .setSocketTimeout(actualSocketTimeoutMs),
+ requestSigner,
+ actualHttpUserAgent,
+ actualErrorHandlingBehaviorConfig,
+ actualMetricGroupName);
+ }
+
+ private static void checkValidRemoteWriteUrl(String url) {
+ try {
+ new URL(url);
+ } catch (MalformedURLException mue) {
+ throw new IllegalArgumentException("Invalid Remote-Write URL: " + url, mue);
+ }
+ }
+
+ public PrometheusSinkBuilder setPrometheusRemoteWriteUrl(String prometheusRemoteWriteUrl) {
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRequestSigner(PrometheusRequestSigner requestSigner) {
+ this.requestSigner = requestSigner;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxBatchSizeInSamples(int maxBatchSizeInSamples) {
+ this.maxBatchSizeInSamples = maxBatchSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMaxRecordSizeInSamples(int maxRecordSizeInSamples) {
+ this.maxRecordSizeInSamples = maxRecordSizeInSamples;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setRetryConfiguration(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setSocketTimeoutMs(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setHttpUserAgent(String httpUserAgent) {
+ this.httpUserAgent = httpUserAgent;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setErrorHandlingBehaviourConfiguration(
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig) {
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ return this;
+ }
+
+ public PrometheusSinkBuilder setMetricGroupName(String metricGroupName) {
+ this.metricGroupName = metricGroupName;
+ return this;
+ }
+
+ private Integer getMaxBatchSizeInSamples() {
+ return maxBatchSizeInSamples;
+ }
+
+ private Integer getMaxRecordSizeInSamples() {
+ return maxRecordSizeInSamples;
+ }
+
+ public RetryConfiguration getRetryConfiguration() {
+ return retryConfiguration;
+ }
+
+ public Integer getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ public String getHttpUserAgent() {
+ return httpUserAgent;
+ }
+
+ public SinkWriterErrorHandlingBehaviorConfiguration getErrorHandlingBehaviorConfig() {
+ return errorHandlingBehaviorConfig;
+ }
+
+ public String getMetricGroupName() {
+ return metricGroupName;
+ }
+
+ /// Disable accessing maxBatchSize, maxBatchSizeInBytes, and maxRecordSizeInBytes directly
+
+ /** Not supported. Use setMaxBatchSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSize(int maxBatchSize) {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ /** Not supported. Use setMaxBatchSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxBatchSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use setMaxRecordSizeInSamples(int) instead */
+ @Override
+ public PrometheusSinkBuilder setMaxRecordSizeInBytes(long maxRecordSizeInBytes) {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxBatchSizeInSamples() instead */
+ @Override
+ protected Integer getMaxBatchSize() {
+ throw new UnsupportedOperationException("maxBatchSize is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxBatchSizeInSamples() instead */
+ @Override
+ protected Long getMaxBatchSizeInBytes() {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
+
+ /** Not supported. Use getMaxRecordSizeInSamples() instead */
+ @Override
+ protected Long getMaxRecordSizeInBytes() {
+ throw new UnsupportedOperationException(
+ "maxRecordSizeInBytes is not supported by this sink");
+ }
Review Comment:
But if someone does, because they are creating their custom extended sink and they think to reuse this, they will get to the methods exposed by `AsyncSinkBaseBuilder`, potentially causing a mess.
I think shadowing those methods is safer and harmless.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757525787
##########
flink-connector-prometheus-request-signer-amp/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerForAMP.java:
##########
@@ -0,0 +1,347 @@
+package org.apache.flink.connector.prometheus.sink.aws;
+
+import org.apache.flink.util.StringUtils;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SimpleTimeZone;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/**
+ * Implements Http/1.1 AWS Signature Version 4a request signing for POST requests to the Amazon
+ * Managed Prometheus service (`aps`).
+ */
+public class AWS4SignerForAMP {
Review Comment:
Also let's make this `@PublicEvolving`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757529253
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/DummAwsSessionCredentialProvider.java:
##########
@@ -0,0 +1,29 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
License headers
##########
flink-connector-prometheus-request-signer-amp/src/test/java/org/apache/flink/connector/prometheus/sink/aws/DummyAwsBasicCredentialsProvider.java:
##########
@@ -0,0 +1,25 @@
+package org.apache.flink.connector.prometheus.sink.aws;
Review Comment:
License headers
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757530223
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkBuilder.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+
+/** Builder for Sink implementation. */
+public class PrometheusSinkBuilder
Review Comment:
`@PublicEvolving`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632187848
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
Review Comment:
I don't think an integration test is useful for a user. And the lack of proper working examples is a common obstacle to the adoption for users new to Flink.
This module is not supposed to be released in any form. Can't we just keep it as source, and possibly reference from the documentation?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597410882
##########
pom.xml:
##########
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-parent</artifactId>
+ <version>1.0.0</version>
+ </parent>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+
+ <name>Flink Prometheus</name>
+ <modules>
+ <module>prometheus-connector</module>
+ <module>amp-request-signer</module>
+ <module>example-datastream-job</module>
+ </modules>
+
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+ <flink.version>1.17.0</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ <aws.sdkv1.version>1.12.570</aws.sdkv1.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk-bom</artifactId>
+ <version>${aws.sdkv1.version}</version>
Review Comment:
This is actually no longer needed. The AMP request signer no longer uses any SDK
I am removing 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597475338
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AWS4SignerForAuthorizationHeader.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.prometheus.sink.aws;
+
+import com.amazonaws.util.BinaryUtils;
+
+import java.net.URL;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * Sample AWS4 signer demonstrating how to sign requests to Amazon S3 using an 'Authorization'
+ * header.
+ */
+public class AWS4SignerForAuthorizationHeader extends AWS4SignerBase {
Review Comment:
It's silly, but this "just works". There is no specs .
This is a class copied&pasted in a gazillion of OSS projects, including big ones.
(try searching "Sample AWS4 signer demonstrating how to sign requests to Amazon S3" in GitHub)
Any unit test would be written reverse-engineering the implementation, so useless.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2106039721
I addressed all comments, except those I explained why I didn't.
Also, now upgraded to Flink 1.18 and newer AsyncSinkBase API.
I cannot split AMP signer and connector in separate PRs at this point, because of the interdependency with the sample application.
Also, I strongly recommend to keep the sample application in the repository, because it serves both as documentation for the user and a way to test the connector (and optionally the signer) in an actual environment. The sample application is not supposed to be released as artifact, but just to stay in the repo as source.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597479280
##########
msf-amp-example/README.md:
##########
@@ -0,0 +1,68 @@
+## Sample application: Amazon Managed Service for Apache Flink and Amazon Managed Prometheus
Review Comment:
Updated to 1.18.1
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-1877219219
@hlteoh37 @dannycranmer please review this PR when you have the chance, so we can proceed with the other related tasks
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1466256133
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
+
+ private static final ContentType CONTENT_TYPE = ContentType.create("application/x-protobuf");
+
+ private static final Map<String, String> FIXED_HEADER =
+ Map.of(
+ HttpHeaders.CONTENT_ENCODING,
+ "snappy",
+ "X-Prometheus-Remote-Write-Version",
+ "0.1.0",
+ HttpHeaders.USER_AGENT,
+ "Flink-Prometheus/0.1.0" // TODO Prometheus requires a user-agent header. What
Review Comment:
Made user-agent configurable with fallback default
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1465060158
##########
pom.xml:
##########
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
Review Comment:
Updated
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1477028925
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/SinkWriterErrorHandlingBehaviorConfiguration.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+import static org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior.FAIL;
+
+/**
+ * Configure the error-handling behavior of the writer, for different types of error. Also defines
+ * default behaviors.
+ */
+public class SinkWriterErrorHandlingBehaviorConfiguration implements Serializable {
+
+ public static final OnErrorBehavior ON_MAX_RETRY_EXCEEDED_DEFAULT_BEHAVIOR = FAIL;
+ public static final OnErrorBehavior ON_HTTP_CLIENT_IO_FAIL_DEFAULT_BEHAVIOR = FAIL;
+ public static final OnErrorBehavior ON_PROMETHEUS_NON_RETRIABLE_ERROR_DEFAULT_BEHAVIOR = FAIL;
+
+ /** Behaviour when the max retries is exceeded on Prometheus retriable errors. */
+ private final OnErrorBehavior onMaxRetryExceeded;
+
+ /** Behaviour when the HTTP client fails, for an I/O problem. */
+ private final OnErrorBehavior onHttpClientIOFail;
+
+ /** Behaviour when Prometheus Remote-Write respond with a non-retriable error. */
+ private final OnErrorBehavior onPrometheusNonRetriableError;
+
+ public SinkWriterErrorHandlingBehaviorConfiguration(
+ OnErrorBehavior onMaxRetryExceeded,
+ OnErrorBehavior onHttpClientIOFail,
+ OnErrorBehavior onPrometheusNonRetriableError) {
+ this.onMaxRetryExceeded = onMaxRetryExceeded;
+ this.onHttpClientIOFail = onHttpClientIOFail;
+ this.onPrometheusNonRetriableError = onPrometheusNonRetriableError;
+ }
+
+ public OnErrorBehavior getOnMaxRetryExceeded() {
+ return onMaxRetryExceeded;
+ }
+
+ public OnErrorBehavior getOnHttpClientIOFail() {
+ return onHttpClientIOFail;
+ }
+
+ public OnErrorBehavior getOnPrometheusNonRetriableError() {
+ return onPrometheusNonRetriableError;
+ }
+
+ /** Builder for PrometheusSinkWriterErrorHandlingConfiguration. */
+ public static class Builder {
+ private OnErrorBehavior onMaxRetryExceeded = null;
+ private OnErrorBehavior onHttpClientIOFail = null;
+ private OnErrorBehavior onPrometheusNonRetriableError = null;
+
+ public Builder() {}
+
+ public Builder onMaxRetryExceeded(OnErrorBehavior onErrorBehavior) {
+ this.onMaxRetryExceeded = onErrorBehavior;
+ return this;
+ }
+
+ public Builder onHttpClientIOFail(OnErrorBehavior onErrorBehavior) {
+ this.onHttpClientIOFail = onErrorBehavior;
+ return this;
+ }
+
+ public Builder onPrometheusNonRetriableError(OnErrorBehavior onErrorBehavior) {
+ this.onPrometheusNonRetriableError = onErrorBehavior;
+ return this;
Review Comment:
Absolutely not. For Prometheus, non-retriable errors are malformed or out-of-order writes. This may happen because of input data, and the writer may want to just log, drop, and continue. This is actually the default behaviour of most of tools writing to Prometheus.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1476176456
##########
example-datastream-job/pom.xml:
##########
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : Sample Application</name>
+ <artifactId>example-datastream-job</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.17.2</flink.version>
+ <log4j.version>2.17.1</log4j.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- Amazon Managed Prometheus signed (remove if not used) -->
+ <dependency>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- Apache Flink dependencies -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-streaming-java</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-clients</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j-impl</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-api</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-core</artifactId>
+ <version>${log4j.version}</version>
+ <scope>runtime</scope>
+ </dependency>
+
+ <!-- For Flink local development -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-runtime-web</artifactId>
Review Comment:
why do we need flink-runtime-web?
##########
amp-request-signer/pom.xml:
##########
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus-parent</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus : AMP request signer</name>
+ <groupId>org.apache.flink.connector.prometheus</groupId>
+ <artifactId>amp-request-signer</artifactId>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <flink.version>1.17.0</flink.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk-core</artifactId>
+ <version>1.12.570</version>
Review Comment:
can we delegate this to a bom in parent?
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/errorhandling/SinkWriterErrorHandlingBehaviorConfiguration.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.prometheus.sink.errorhandling;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+import static org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior.FAIL;
+
+/**
+ * Configure the error-handling behavior of the writer, for different types of error. Also defines
+ * default behaviors.
+ */
+public class SinkWriterErrorHandlingBehaviorConfiguration implements Serializable {
+
+ public static final OnErrorBehavior ON_MAX_RETRY_EXCEEDED_DEFAULT_BEHAVIOR = FAIL;
+ public static final OnErrorBehavior ON_HTTP_CLIENT_IO_FAIL_DEFAULT_BEHAVIOR = FAIL;
+ public static final OnErrorBehavior ON_PROMETHEUS_NON_RETRIABLE_ERROR_DEFAULT_BEHAVIOR = FAIL;
+
+ /** Behaviour when the max retries is exceeded on Prometheus retriable errors. */
+ private final OnErrorBehavior onMaxRetryExceeded;
+
+ /** Behaviour when the HTTP client fails, for an I/O problem. */
+ private final OnErrorBehavior onHttpClientIOFail;
+
+ /** Behaviour when Prometheus Remote-Write respond with a non-retriable error. */
+ private final OnErrorBehavior onPrometheusNonRetriableError;
+
+ public SinkWriterErrorHandlingBehaviorConfiguration(
+ OnErrorBehavior onMaxRetryExceeded,
+ OnErrorBehavior onHttpClientIOFail,
+ OnErrorBehavior onPrometheusNonRetriableError) {
+ this.onMaxRetryExceeded = onMaxRetryExceeded;
+ this.onHttpClientIOFail = onHttpClientIOFail;
+ this.onPrometheusNonRetriableError = onPrometheusNonRetriableError;
+ }
+
+ public OnErrorBehavior getOnMaxRetryExceeded() {
+ return onMaxRetryExceeded;
+ }
+
+ public OnErrorBehavior getOnHttpClientIOFail() {
+ return onHttpClientIOFail;
+ }
+
+ public OnErrorBehavior getOnPrometheusNonRetriableError() {
+ return onPrometheusNonRetriableError;
+ }
+
+ /** Builder for PrometheusSinkWriterErrorHandlingConfiguration. */
+ public static class Builder {
+ private OnErrorBehavior onMaxRetryExceeded = null;
+ private OnErrorBehavior onHttpClientIOFail = null;
+ private OnErrorBehavior onPrometheusNonRetriableError = null;
+
+ public Builder() {}
+
+ public Builder onMaxRetryExceeded(OnErrorBehavior onErrorBehavior) {
+ this.onMaxRetryExceeded = onErrorBehavior;
+ return this;
+ }
+
+ public Builder onHttpClientIOFail(OnErrorBehavior onErrorBehavior) {
+ this.onHttpClientIOFail = onErrorBehavior;
+ return this;
+ }
+
+ public Builder onPrometheusNonRetriableError(OnErrorBehavior onErrorBehavior) {
+ this.onPrometheusNonRetriableError = onErrorBehavior;
+ return this;
Review Comment:
we should consider making this non-configurable
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1488349352
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusTimeSeries.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.Public;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Pojo used as sink input, containing a single TimeSeries: a list of Labels and a list of Samples.
+ *
+ * <p>metricName is mapped in Prometheus to the value of the mandatory label named '__name__'
+ * labels. The other labels, as key/value, are appended after the '__name__' label.
+ */
+@Public
+public class PrometheusTimeSeries implements Serializable {
+ /** A single Label. */
+ public static class Label implements Serializable {
+ private final String name;
+ private final String value;
+
+ public Label(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Label label = (Label) o;
+ return new EqualsBuilder()
+ .append(name, label.name)
+ .append(value, label.value)
+ .isEquals();
+ }
Review Comment:
Added unit tests on equals and hashCode semantics, and also fixed a bug: missing equals() in one of the inner 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501896859
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
+
+ private static final ContentType CONTENT_TYPE = ContentType.create("application/x-protobuf");
+
+ public static final String DEFAULT_USER_AGENT = "Flink-Prometheus";
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusRequestSigner requestSigner;
+
+ private final Map<String, String> fixedHeaders;
+
+ public PrometheusRemoteWriteHttpRequestBuilder(
+ String prometheusRemoteWriteUrl,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent) {
+ Preconditions.checkNotNull(httpUserAgent, "User-Agent not specified");
+
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ this.requestSigner = requestSigner;
+ this.fixedHeaders =
+ Map.of(
+ HttpHeaders.CONTENT_ENCODING,
+ "snappy",
+ "X-Prometheus-Remote-Write-Version",
+ "0.1.0",
Review Comment:
Can these values be moved to constant?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501898533
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
Please add tests for this class, currently not covered
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501902624
##########
prometheus-connector/src/test/java/org/apache/flink/connector/prometheus/sink/HttpResponseHandlingBehaviourIT.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.PrometheusAsyncHttpClientBuilder;
+import org.apache.flink.metrics.groups.UnregisteredMetricsGroup;
+
+import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
+import com.github.tomakehurst.wiremock.junit5.WireMockTest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.exactly;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.status;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static org.apache.flink.connector.prometheus.sink.HttpResponseCallbackTestUtils.assertCallbackCompletedOnceWithException;
+import static org.apache.flink.connector.prometheus.sink.HttpResponseCallbackTestUtils.assertCallbackCompletedOnceWithNoException;
+import static org.apache.flink.connector.prometheus.sink.HttpResponseCallbackTestUtils.getRequestResult;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * Test the http response handling behaviour with the full stack handling http client, retries and
+ * error handling.
+ *
+ * <p>The full behaviour is determined by the combination of {@link HttpResponseCallback}, {@link
+ * org.apache.flink.connector.prometheus.sink.http.RemoteWriteRetryStrategy}, {@link
+ * org.apache.flink.connector.prometheus.sink.http.RetryConfiguration}, {@link
+ * org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier}, and {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}.
+ *
+ * <p>The behaviour of the stack is tested sending a request through the http client and simulating
+ * the response from Prometheus using a WireMock stub.
+ */
+@WireMockTest
+public class HttpResponseHandlingBehaviourIT {
+
+ private static final int TIME_SERIES_COUNT = 13;
+ private static final long SAMPLE_COUNT = 42;
+
+ private SinkMetrics metrics;
+
+ @BeforeEach
+ void setUp() {
+ metrics = SinkMetrics.registerSinkMetrics(new UnregisteredMetricsGroup());
+ }
+
+ private SimpleHttpRequest buildRequest(WireMockRuntimeInfo wmRuntimeInfo)
+ throws URISyntaxException {
+ return HttpTestUtils.buildPostRequest(HttpTestUtils.buildRequestUrl(wmRuntimeInfo));
+ }
+
+ private void serverWillRespond(ResponseDefinitionBuilder responseDefinition) {
+ WireMock.stubFor(post("/remote_write").willReturn(responseDefinition));
+ }
+
+ private PrometheusAsyncHttpClientBuilder getHttpClientBuilder(int maxRetryCount) {
+ return new PrometheusAsyncHttpClientBuilder(
+ HttpTestUtils.fastRetryConfiguration(maxRetryCount));
+ }
+
+ private VerifyableResponseCallback getResponseCallback(
+ SinkMetrics metrics,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior) {
+ return new VerifyableResponseCallback(
+ new HttpResponseCallback(
+ TIME_SERIES_COUNT,
+ SAMPLE_COUNT,
+ metrics,
+ errorHandlingBehavior,
+ getRequestResult(new ArrayList<>())));
+ }
+
+ @Test
+ void shouldCompleteOn200Ok(WireMockRuntimeInfo wmRuntimeInfo)
+ throws URISyntaxException, IOException {
+ int statusCode = 200;
+ serverWillRespond(status(statusCode));
+
+ PrometheusAsyncHttpClientBuilder clientBuilder = getHttpClientBuilder(1);
+
+ // Fail on any error
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior =
+ SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onMaxRetryExceeded(OnErrorBehavior.FAIL)
+ .onHttpClientIOFail(OnErrorBehavior.FAIL)
+ .onPrometheusNonRetriableError(OnErrorBehavior.FAIL)
+ .build();
+
+ VerifyableResponseCallback callback = getResponseCallback(metrics, errorHandlingBehavior);
+
+ SimpleHttpRequest request = buildRequest(wmRuntimeInfo);
+
+ try (CloseableHttpAsyncClient client = clientBuilder.buildAndStartClient(metrics)) {
+ client.execute(request, callback);
+
+ await().untilAsserted(
+ () -> {
+ // Check the client execute only one request
+ verify(exactly(1), postRequestedFor(urlEqualTo("/remote_write")));
+
+ // Verify the callback is completed
+ assertCallbackCompletedOnceWithNoException(callback);
+ });
+ }
+ }
+
+ @Test
+ void shouldCompleteAfterRetryingOn500WhenDiscardAndContinueOnMaxRetryExceededIsSelected(
+ WireMockRuntimeInfo wmRuntimeInfo) throws URISyntaxException, IOException {
+ int statusCode = 500; // 500,Server error is retriable for Prometheus remote-write
+ serverWillRespond(status(statusCode));
+
+ int maxRetryCount = 2;
+ PrometheusAsyncHttpClientBuilder clientBuilder = getHttpClientBuilder(maxRetryCount);
+
+ // Discard and continue on max retry exceeded
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior =
+ SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onMaxRetryExceeded(OnErrorBehavior.DISCARD_AND_CONTINUE)
+ .build();
+
+ VerifyableResponseCallback callback = getResponseCallback(metrics, errorHandlingBehavior);
+
+ SimpleHttpRequest request = buildRequest(wmRuntimeInfo);
+
+ try (CloseableHttpAsyncClient client = clientBuilder.buildAndStartClient(metrics)) {
+ client.execute(request, callback);
+
+ await().untilAsserted(
+ () -> {
+ // Check the http client retries for max retries + one initial
+ // attempt
+ verify(
+ exactly(maxRetryCount + 1),
+ postRequestedFor(urlEqualTo("/remote_write")));
+
+ // Verify the callback is completed
+ assertCallbackCompletedOnceWithNoException(callback);
+ });
+ }
+ }
+
+ @Test
+ void shouldRetryCompleteAndThrowExceptionOn500WhenFailOnMaxRetryExceededIsSelected(
+ WireMockRuntimeInfo wmRuntimeInfo) throws URISyntaxException, IOException {
+ int statusCode = 500; // 500,Server error is retriable for Prometheus remote-write
+ serverWillRespond(status(statusCode));
+
+ int maxRetryCount = 2;
+ PrometheusAsyncHttpClientBuilder clientBuilder = getHttpClientBuilder(maxRetryCount);
+
+ // Fail on max retry exceeded
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior =
+ SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onMaxRetryExceeded(OnErrorBehavior.FAIL)
+ .build();
+
+ VerifyableResponseCallback callback = getResponseCallback(metrics, errorHandlingBehavior);
+
+ SimpleHttpRequest request = buildRequest(wmRuntimeInfo);
+
+ try (CloseableHttpAsyncClient client = clientBuilder.buildAndStartClient(metrics)) {
+ client.execute(request, callback);
+
+ await().untilAsserted(
+ () -> {
+ // Check the http client retries for max retries + one initial
+ // attempt
+ verify(
+ exactly(maxRetryCount + 1),
+ postRequestedFor(urlEqualTo("/remote_write")));
+
+ // Verify the callback was completed once with an exception
+ assertCallbackCompletedOnceWithException(
+ PrometheusSinkWriteException.class, callback);
+ });
+ }
+ }
+
+ @Test
+ void shouldNotRetryAndCompleteOn404WhenDiscardAndContinueOnNonRetriableIsSelected(
+ WireMockRuntimeInfo wmRuntimeInfo) throws URISyntaxException, IOException {
+ PrometheusAsyncHttpClientBuilder clientBuilder = getHttpClientBuilder(1);
+ int statusCode = 404; // 404,Not found is non-retriable for Prometheus remote-write
+ serverWillRespond(status(statusCode));
+
+ // Discard and continue on non-retriable
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior =
+ SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onPrometheusNonRetriableError(OnErrorBehavior.DISCARD_AND_CONTINUE)
+ .build();
+
+ VerifyableResponseCallback callback = getResponseCallback(metrics, errorHandlingBehavior);
+
+ SimpleHttpRequest request = buildRequest(wmRuntimeInfo);
+
+ try (CloseableHttpAsyncClient client = clientBuilder.buildAndStartClient(metrics)) {
+ client.execute(request, callback);
+
+ await().untilAsserted(
+ () -> {
+ // Check the client execute only one request
+ verify(exactly(1), postRequestedFor(urlEqualTo("/remote_write")));
+
+ // Verify the callback is completed
+ assertCallbackCompletedOnceWithNoException(callback);
+ });
+ }
+ }
+
+ @Test
+ void shouldNotRetryAndCompleteAndThrowExceptionOn404WhenFailOnNonRetriableIsSelected(
+ WireMockRuntimeInfo wmRuntimeInfo) throws URISyntaxException, IOException {
+ PrometheusAsyncHttpClientBuilder clientBuilder = getHttpClientBuilder(1);
+ int statusCode = 404; // 404,Not found is non-retriable for Prometheus remote-write
+ serverWillRespond(status(statusCode));
+
+ // Fail on non-retriable
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehavior =
+ SinkWriterErrorHandlingBehaviorConfiguration.builder()
+ .onPrometheusNonRetriableError(OnErrorBehavior.FAIL)
+ .build();
+
+ VerifyableResponseCallback callback = getResponseCallback(metrics, errorHandlingBehavior);
+
+ SimpleHttpRequest request = buildRequest(wmRuntimeInfo);
+
+ try (CloseableHttpAsyncClient client = clientBuilder.buildAndStartClient(metrics)) {
+ client.execute(request, callback);
+
+ await().untilAsserted(
+ () -> {
+ // Check the client execute only one request
+ verify(exactly(1), postRequestedFor(urlEqualTo("/remote_write")));
+
+ // Verify the callback was completed once with an exception
+ assertCallbackCompletedOnceWithException(
+ PrometheusSinkWriteException.class, callback);
+ });
+ }
+ }
+
+ @Test
+ void shouldNotRetryCompleteAndThrowExceptionOn304(WireMockRuntimeInfo wmRuntimeInfo)
+ throws URISyntaxException, IOException {
+ int statusCode =
+ 304; // 304, Not modified is just status code for which the behaviour is not
+ // specified by Prometheus remote-write specs, and makes the http client
+ // terminate successfully
Review Comment:
Move this long comment above the expression
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501901973
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/PrometheusAsyncHttpClientBuilder.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.config.TlsConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.util.Timeout;
+
+import java.io.Serializable;
+import java.util.Optional;
+
+/**
+ * Builder for async http client that will retry, based on the {@link RemoteWriteRetryStrategy}
+ * specified.
+ */
+public class PrometheusAsyncHttpClientBuilder implements Serializable {
+ public static final int DEFAULT_SOCKET_TIMEOUT_MS = 5000;
+
+ private final RetryConfiguration retryConfiguration;
+ private Integer socketTimeoutMs;
+
+ public PrometheusAsyncHttpClientBuilder(RetryConfiguration retryConfiguration) {
+ this.retryConfiguration = retryConfiguration;
+ }
+
+ public PrometheusAsyncHttpClientBuilder setSocketTimeout(int socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ return this;
+ }
+
+ public CloseableHttpAsyncClient buildAndStartClient(SinkMetrics counters) {
+ int actualSocketTimeoutMs =
+ Optional.ofNullable(socketTimeoutMs).orElse(DEFAULT_SOCKET_TIMEOUT_MS);
+
+ Preconditions.checkArgument(
+ retryConfiguration.getInitialRetryDelayMS() >= 0,
+ "Initial retry delay must be >= 0");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryDelayMS()
+ >= retryConfiguration.getInitialRetryDelayMS(),
+ "Max retry delay must be >= initial retry delay");
+ Preconditions.checkArgument(
+ retryConfiguration.getMaxRetryCount() >= 0, "Max retry count must be >= 0");
+ Preconditions.checkArgument(actualSocketTimeoutMs >= 0, "Socket timeout must be >= 0");
+
+ final IOReactorConfig ioReactorConfig =
+ IOReactorConfig.custom()
+ .setIoThreadCount(1) // Always one thread
+ .setSoTimeout(Timeout.ofMilliseconds(actualSocketTimeoutMs))
+ .build();
+
+ var client =
+ HttpAsyncClients.custom()
+ .setConnectionManager(
+ PoolingAsyncClientConnectionManagerBuilder.create()
+ .setDefaultTlsConfig(
+ TlsConfig.custom()
+ .setVersionPolicy(
+ HttpVersionPolicy.FORCE_HTTP_1)
+ .build())
+ .build())
Review Comment:
Should this part be extracted into variable to avoid deep nesting?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501897750
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
+ * Protobuf-serialized representation of a {@link Types.TimeSeries TimeSeries}. In this
+ * implementation SIZEn is the size of the Protobuf serialization, in bytes, that does not match
+ * the "size" of a {@link RequestEntryWrapper}.
+ *
+ * @param bufferedRequestState The buffered request state to be serialized
+ * @return serialized buffered request state
+ * @throws IOException
+ */
+ @Override
+ public byte[] serialize(BufferedRequestState<Types.TimeSeries> bufferedRequestState)
+ throws IOException {
+ Collection<RequestEntryWrapper<Types.TimeSeries>> bufferState =
+ bufferedRequestState.getBufferedRequestEntries();
+
+ try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final DataOutputStream out = new DataOutputStream(baos)) {
+
+ out.writeLong(DATA_IDENTIFIER); // DATA_IDENTIFIER
+ out.writeInt(bufferState.size()); // NUM_OF_ELEMENTS
+
+ for (RequestEntryWrapper<Types.TimeSeries> wrapper : bufferState) {
+ // In the serialized state we write the size of the serialized representation,
+ // rather than the size
+ // held in RequestEntryWrapper, that is the output of
+ // AsyncSinkWriter.getSizeInBytes()
+ long requestEntrySize =
+ RequestEntrySizeUtils.requestSerializedSize(wrapper.getRequestEntry());
+ out.writeLong(requestEntrySize); // SIZEn
+ serializeRequestToStream(wrapper.getRequestEntry(), out); // REQUESTn
+ }
+
+ return baos.toByteArray();
+ }
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>See {@link PrometheusStateSerializer#serialize(BufferedRequestState)} for more details.
+ *
+ * @param version The version in which the data was serialized
+ * @param serialized The serialized data
+ * @return a buffered request state wrapping the deserialized time-series.
+ * @throws IOException
+ */
+ @Override
+ public BufferedRequestState<Types.TimeSeries> deserialize(int version, byte[] serialized)
+ throws IOException {
+ try (final ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
+ final DataInputStream in = new DataInputStream(bais)) {
+
+ validateIdentifier(in); // DATA_IDENTIFIER
+ int numberOfElements = in.readInt(); // NUM_OF_ELEMENTS
+
+ List<RequestEntryWrapper<Types.TimeSeries>> serializedState = new ArrayList<>();
+ for (int i = 0; i < numberOfElements; i++) {
+ // This is the size of an request-entry in the serialized state
+ long requestSerializedSize = in.readLong(); // SIZEn - the serialized size
Review Comment:
Typo: `SIZEn`, should be `SIZE`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501897616
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusStateSerializer.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.RequestEntryWrapper;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Serializes/deserializes the sink request-entry, the protobuf-generated {@link Types.TimeSeries},
+ * using protobuf.
+ */
+public class PrometheusStateSerializer extends AsyncSinkWriterStateSerializer<Types.TimeSeries> {
+ private static final int VERSION = 1;
+
+ // Copied from AsyncSinkWriterStateSerializer.DATA_IDENTIFIER
+ private static final long DATA_IDENTIFIER = -1;
+
+ @Override
+ protected void serializeRequestToStream(Types.TimeSeries request, DataOutputStream out)
+ throws IOException {
+ byte[] serializedRequest = request.toByteArray();
+ out.write(serializedRequest);
+ }
+
+ @Override
+ protected Types.TimeSeries deserializeRequestFromStream(long requestSize, DataInputStream in)
+ throws IOException {
+ // The size written into the serialized stat is the size of the protobuf-serialized
+ // time-series
+ byte[] requestData = new byte[(int) requestSize];
+ in.read(requestData);
+ return Types.TimeSeries.parseFrom(requestData);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Overrides the original implementation that assumes the serialized size is the value returned
+ * by {@link PrometheusSinkWriter#getSizeInBytes(Types.TimeSeries)}
+ *
+ * <p>Most of the code is copied from the original implementation of
+ * AsyncSinkWriterStateSerializer.serialize().
+ *
+ * <p>The state is serialized in form of
+ * [DATA_IDENTIFIER,NUM_OF_ELEMENTS,SIZE1,REQUEST1,SIZE2,REQUEST2....], where REQUESTn is the
Review Comment:
Typo: `REQUESTn`, should be `REQUEST`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "z3d1k (via GitHub)" <gi...@apache.org>.
z3d1k commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1501904332
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/http/RemoteWriteRetryStrategy.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.prometheus.sink.http;
+
+import org.apache.flink.connector.prometheus.sink.SinkMetrics;
+
+import org.apache.hc.client5.http.HttpRequestRetryStrategy;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.TimeValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.NoRouteToHostException;
+import java.net.UnknownHostException;
+import java.util.List;
+
+/** Retry strategy for the http client. */
+public class RemoteWriteRetryStrategy implements HttpRequestRetryStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(RemoteWriteRetryStrategy.class);
+
+ private static final List<Class<? extends IOException>> NON_RETRIABLE_EXCEPTIONS =
+ List.of(
+ InterruptedIOException.class,
+ UnknownHostException.class,
+ ConnectException.class,
+ NoRouteToHostException.class,
+ SSLException.class);
+
+ private final long initialRetryDelayMs;
+ private final long maxRetryDelayMs;
+ private final int maxRetryCount;
+
+ private final SinkMetrics counters;
+
+ public RemoteWriteRetryStrategy(RetryConfiguration retryConfiguration, SinkMetrics counters) {
+ this.initialRetryDelayMs = retryConfiguration.getInitialRetryDelayMS();
+ this.maxRetryDelayMs = retryConfiguration.getMaxRetryDelayMS();
+ this.maxRetryCount = retryConfiguration.getMaxRetryCount();
+ this.counters = counters;
+ }
+
+ @Override
+ public boolean retryRequest(
+ HttpRequest httpRequest, IOException e, int execCount, HttpContext httpContext) {
+ // Retry on any IOException except those considered non-retriable
+ var retry =
+ (execCount <= maxRetryCount) && !(NON_RETRIABLE_EXCEPTIONS.contains(e.getClass()));
+ LOG.debug(
+ "{} retry on {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ e.getClass(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public boolean retryRequest(HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ var retry =
+ (execCount <= maxRetryCount)
+ && RemoteWriteResponseClassifier.isRetriableErrorResponse(httpResponse);
+ LOG.debug(
+ "{} retry on response {} {}, at execution {}",
+ (retry) ? "DO" : "DO NOT",
+ httpResponse.getCode(),
+ httpResponse.getReasonPhrase(),
+ execCount);
+ countRetry(retry);
+ return retry;
+ }
+
+ @Override
+ public TimeValue getRetryInterval(
+ HttpResponse httpResponse, int execCount, HttpContext httpContext) {
+ long calculatedDelay = initialRetryDelayMs << (execCount - 1);
Review Comment:
Should multiplier be configurable instead of being set to 2?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1447650514
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkCounters.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
+
+ /**
+ * * Batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable
+ * number. This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and
+ * maxBatchSizeInBytes is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because
+ * each TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(..). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are
+ * limiting the number of Samples in each TimeSeries to the max batch size, setting
+ * maxRecordSizeInBytes = maxBatchSizeInBytes.
+ */
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusSinkWriter.class);
+
+ private final SinkCounters counters;
+ private final CloseableHttpAsyncClient asyncHttpClient;
+ private final PrometheusRemoteWriteHttpRequestBuilder requestBuilder;
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner) {
+ this(
+ elementConverter,
+ context,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples,
+ maxTimeInBufferMS,
+ prometheusRemoteWriteUrl,
+ asyncHttpClient,
+ counters,
+ requestSigner,
+ Collections.emptyList());
+ }
+
+ public PrometheusSinkWriter(
+ ElementConverter<PrometheusTimeSeries, Types.TimeSeries> elementConverter,
+ Sink.InitContext context,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ int maxBatchSizeInSamples,
+ long maxTimeInBufferMS,
+ String prometheusRemoteWriteUrl,
+ CloseableHttpAsyncClient asyncHttpClient,
+ SinkCounters counters,
+ PrometheusRequestSigner requestSigner,
+ Collection<BufferedRequestState<Types.TimeSeries>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSizeInSamples, // maxBatchSize
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInSamples, // maxBatchSizeInBytes
+ maxTimeInBufferMS,
+ maxBatchSizeInSamples, // maxRecordSizeInBytes
+ states);
+ this.requestBuilder =
+ new PrometheusRemoteWriteHttpRequestBuilder(
+ prometheusRemoteWriteUrl, requestSigner);
+ this.asyncHttpClient = asyncHttpClient;
+ this.counters = counters;
+ }
+
+ /**
+ * This is the "size" of the request entry (a {@link Types.TimeSeries time-series}) used for
+ * batching. Regardless the name of the method, it returns the number of {@link Types.Sample
+ * samples} in the time-series (not bytes), to support batching in terms of samples.
+ *
+ * @param timeSeries the request entry for which we want to know the size
+ * @return number of samples in the time-series
+ */
+ @Override
+ protected long getSizeInBytes(Types.TimeSeries timeSeries) {
+ return RequestEntrySizeUtils.requestSizeForBatching(timeSeries);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<Types.TimeSeries> requestEntries, Consumer<List<Types.TimeSeries>> requestResult) {
+ int timeSeriesCount = requestEntries.size();
+ long sampleCount = RequestEntrySizeUtils.countSamples(requestEntries);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(
+ "Writing {} time-series containing {} samples ", timeSeriesCount, sampleCount);
+ }
+
+ Remote.WriteRequest writeRequest = buildWriteRequest(requestEntries);
+ byte[] requestBody;
+ try {
+ requestBody = compressWriteRequest(writeRequest);
+ } catch (IOException e) {
+ throw new RuntimeException("Exception compressing the request body", e);
+ }
+
+ SimpleHttpRequest postRequest = requestBuilder.buildHttpRequest(requestBody);
+ asyncHttpClient.execute(
+ postRequest,
+ new ResponseCallback(timeSeriesCount, sampleCount, counters, requestResult));
+ }
+
+ @VisibleForTesting
Review Comment:
Not a fan of this `@VisibleForTesting` - can we instead write a test `asyncHttpClient` that tests each scenario?
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489187810
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
Review Comment:
Modified the comment only retaining the `@param` 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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1489268899
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sign a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(awsRegion), "Missing or blank AMP workspace region");
+ Preconditions.checkNotNull(
+ StringUtils.isNotBlank(remoteWriteUrl),
+ "Missing or blank AMP workspace remote-write URL");
+ this.awsRegion = awsRegion;
+ try {
+ this.remoteWriteUrl = new URL(remoteWriteUrl);
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException(
+ "Invalid AMP remote-write URL: " + remoteWriteUrl, e);
+ }
+ }
+
+ /**
+ * Add the additional Http request headers required by Amazon Managed Prometheus:
+ * 'x-amz-content-sha256', 'Host', 'X-Amz-Date', 'x-amz-security-token' and 'Authorization`.
+ *
+ * @param requestHeaders original Http request headers. It must be mutable. For efficiency, any
+ * new header is added to the map, instead of making a copy.
+ * @param requestBody request body, already compressed
+ */
+ @Override
+ public void addSignatureHeaders(Map<String, String> requestHeaders, byte[] requestBody) {
+ byte[] contentHash = AWS4SignerBase.hash(requestBody);
+ String contentHashString = BinaryUtils.toHex(contentHash);
+ requestHeaders.put(
+ "x-amz-content-sha256",
+ contentHashString); // this header must be included before generating the
+ // Authorization header
+
+ DefaultAWSCredentialsProviderChain credsChain = new DefaultAWSCredentialsProviderChain();
Review Comment:
Added the possibility to instantiate a signer with a different credentials provider.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597505926
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/** Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries. */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
Not much to test here, except the initialization that is coupled with the PrometheusSink initialization.
I created a test similar to what is done in the Kinesis Sink.
https://github.com/apache/flink-connector-aws/blob/main/flink-connector-aws/flink-connector-aws-kinesis-streams/src/test/java/org/apache/flink/connector/kinesis/sink/KinesisStreamsSinkWriterTest.java
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597486440
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusRemoteWriteHttpRequestBuilder.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.util.Preconditions;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Builds the POST request to the Remote-Write endpoint for a given binary payload. */
+public class PrometheusRemoteWriteHttpRequestBuilder {
+
+ private static final ContentType CONTENT_TYPE = ContentType.create("application/x-protobuf");
+
+ public static final String DEFAULT_USER_AGENT = "Flink-Prometheus";
+ private final String prometheusRemoteWriteUrl;
+ private final PrometheusRequestSigner requestSigner;
+
+ private final Map<String, String> fixedHeaders;
+
+ public PrometheusRemoteWriteHttpRequestBuilder(
+ String prometheusRemoteWriteUrl,
+ PrometheusRequestSigner requestSigner,
+ String httpUserAgent) {
+ Preconditions.checkNotNull(httpUserAgent, "User-Agent not specified");
+
+ this.prometheusRemoteWriteUrl = prometheusRemoteWriteUrl;
+ this.requestSigner = requestSigner;
+ this.fixedHeaders =
+ Map.of(
+ HttpHeaders.CONTENT_ENCODING,
+ "snappy",
+ "X-Prometheus-Remote-Write-Version",
+ "0.1.0",
+ HttpHeaders.USER_AGENT,
+ httpUserAgent);
+ }
+
+ public SimpleHttpRequest buildHttpRequest(byte[] httpRequestBody) {
+ Map<String, String> headers = new HashMap<>(fixedHeaders);
+ if (requestSigner != null) {
+ requestSigner.addSignatureHeaders(headers, httpRequestBody);
+ }
+
+ var builder =
Review Comment:
Is it still the case for 1.18?
Anyhow, I removed java 11 features
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1632194796
##########
amp-request-signer/README.md:
##########
@@ -0,0 +1,31 @@
+## Request Signer for Amazon Managed Prometheus (AMP)
+
+Request signer implementation for Amazon Managed Prometheus (AMP)
+
+The signer retrieves AWS credentials using `com.amazonaws.auth.DefaultAWSCredentialsProviderChain` and automatically
+supports session credentials.
+
+The Flink application requires `RemoteWrite` permissions to the AMP workspace (e.g. `AmazonPromethusRemoteWriteAccess`
+policy).
+
+### Sample usage
+
+To enable request signing for Amazon Managed Prometheus, and instance of `AmazonManagedPrometheusWriteRequestSigner`
+must
Review Comment:
Fixed
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1633781977
##########
README.md:
##########
@@ -8,6 +8,14 @@ Apache Flink is an open source stream processing framework with powerful stream-
Learn more about Flink at [https://flink.apache.org/](https://flink.apache.org/)
+## Modules
+
+This repository contains the following modules
+
+* [Prometheus Connector](./prometheus-connector): Flink Prometheus Connector implementation; supports optional request signer
+* [Sample application](./example-datastream-job): Sample application showing the usage of the connector with DataStream API. It also demonstrates how to configure the request signer.
Review Comment:
I moved the example application under tests, as suggested, merging everything in a single class.
The usage of the AMP connector is commented out, being a separate dependency, but still present to show the usage, in case someone wants to use it.
https://github.com/apache/flink-connector-prometheus/blob/5afb890aa8fe860ce25bcf89f7cdee93a6d2c4be/flink-connector-prometheus/src/test/java/org/apache/flink/connector/prometheus/sink/examples/DataStreamExample.java
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2159216321
I moved the example application under tests and removed the separate module completely.
I added links to the example application in the README.
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1597458387
##########
prometheus-connector/src/main/java/org/apache/flink/connector/prometheus/sink/HttpResponseCallback.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.connector.prometheus.sink.errorhandling.OnErrorBehavior;
+import org.apache.flink.connector.prometheus.sink.errorhandling.PrometheusSinkWriteException;
+import org.apache.flink.connector.prometheus.sink.errorhandling.SinkWriterErrorHandlingBehaviorConfiguration;
+import org.apache.flink.connector.prometheus.sink.http.RemoteWriteResponseClassifier;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_NON_RETRIABLE_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_SAMPLES_RETRY_LIMIT_DROPPED;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_OUT;
+import static org.apache.flink.connector.prometheus.sink.SinkMetrics.SinkCounter.NUM_WRITE_REQUESTS_PERMANENTLY_FAILED;
+
+/**
+ * Callback handling the outcome of the http async request.
+ *
+ * <p>This class implements the error handling behaviour, based on the configuration in {@link
+ * SinkWriterErrorHandlingBehaviorConfiguration}. Depending on the condition, the sink may throw an
+ * exception and cause the job to fail, or log the condition to WARN, increment the counters and
+ * continue with the next request.
+ *
+ * <p>In any case, every write-request either entirely succeed or fail. Partial failures are not
+ * handled.
+ *
+ * <p>In no condition a write-request is re-queued for the AsyncSink to reprocess: this would cause
+ * out of order writes that would be rejected by Prometheus.
+ *
+ * <p>Note that the http async client retries, based on the configured retry policy. The callback is
+ * called with an outcome of *completed* either when the request has succeeded or the max retry
+ * limit has been exceeded. It is responsibility of the callback distinguishing between these
+ * conditions.
+ */
+class HttpResponseCallback implements FutureCallback<SimpleHttpResponse> {
+ private static final Logger LOG = LoggerFactory.getLogger(HttpResponseCallback.class);
+
+ private final int timeSeriesCount;
+ private final long sampleCount;
+ private final Consumer<List<Types.TimeSeries>> reQueuedResult;
+ private final SinkMetrics metrics;
+ private final SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig;
+
+ public HttpResponseCallback(
+ int timeSeriesCount,
+ long sampleCount,
+ SinkMetrics metrics,
+ SinkWriterErrorHandlingBehaviorConfiguration errorHandlingBehaviorConfig,
+ Consumer<List<Types.TimeSeries>> reQueuedResult) {
+ this.timeSeriesCount = timeSeriesCount;
+ this.sampleCount = sampleCount;
+ this.reQueuedResult = reQueuedResult;
+ this.metrics = metrics;
+ this.errorHandlingBehaviorConfig = errorHandlingBehaviorConfig;
+ }
+
+ /**
+ * The completed outcome is invoked every time the http client successfully receives a valid
+ * http response, regardless of the status code.
+ *
+ * <p>This method classifies the responses and implements the behaviour expected by the
+ * Remote-Write specifications. In case of error, the behaviour is determined by the error
+ * handling configuration.
+ */
+ @Override
+ public void completed(SimpleHttpResponse response) {
Review Comment:
Done.
One nested if (no else) is still required to throw exception when the error behaviour is FAIL, avoiding too many `if (A && X1)... if (A && X2)...`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1464974937
##########
amp-request-signer/src/main/java/org/apache/flink/connector/prometheus/sink/aws/AmazonManagedPrometheusWriteRequestSigner.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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.prometheus.sink.aws;
+
+import org.apache.flink.connector.prometheus.sink.PrometheusRequestSigner;
+import org.apache.flink.util.Preconditions;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSSessionCredentials;
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.util.BinaryUtils;
+import org.apache.commons.lang3.StringUtils;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+
+/** Sing a Remote-Write request to Amazon Managed Service for Prometheus (AMP). */
+public class AmazonManagedPrometheusWriteRequestSigner implements PrometheusRequestSigner {
+
+ private final URL remoteWriteUrl;
+ private final String awsRegion;
+
+ /**
+ * Constructor.
+ *
+ * @param remoteWriteUrl URL of the remote-write endpoint
+ * @param awsRegion Region of the AMP workspace
+ */
+ public AmazonManagedPrometheusWriteRequestSigner(String remoteWriteUrl, String awsRegion) {
+ Preconditions.checkArgument(StringUtils.isNotBlank(awsRegion));
Review Comment:
Added message for both parameters.
Also using `isNotBlank()` with both, for consistency
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1465061400
##########
prometheus-connector/pom.xml:
##########
@@ -0,0 +1,130 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-prometheus</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <name>Flink : Connectors : Prometheus</name>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-prometheus</artifactId>
+ <packaging>jar</packaging>
+
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <target.java.version>11</target.java.version>
+ <maven.compiler.source>${target.java.version}</maven.compiler.source>
+ <maven.compiler.target>${target.java.version}</maven.compiler.target>
+
+ <flink.version>1.16.2</flink.version>
+ <protobuf.version>3.22.2</protobuf.version>
+ <apache.httpclient.version>5.2.1</apache.httpclient.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-streaming-java</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- protobuf, snappy - for prometheus remote-write payload -->
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
+ <version>${protobuf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java-util</artifactId>
+ <version>${protobuf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.xerial.snappy</groupId>
+ <artifactId>snappy-java</artifactId>
+ <version>1.1.9.1</version>
+ </dependency>
+
+ <!-- http client -->
+ <dependency>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
+ <version>${apache.httpclient.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents.core5</groupId>
+ <artifactId>httpcore5</artifactId>
+ <version>${apache.httpclient.version}</version>
+ </dependency>
+
+ <!-- test -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-test-utils-junit</artifactId>
+ <version>${flink.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8</artifactId>
+ <version>2.35.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>4.5.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
+ <version>4.2.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.8.0</version>
+ <configuration>
+ <source>${target.java.version}</source>
+ <target>${target.java.version}</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
Review Comment:
Moved to parent only
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#discussion_r1757531627
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkException.java:
##########
@@ -0,0 +1,33 @@
+/*
+ * 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.prometheus.sink;
+
+/**
+ * A {@link RuntimeException} wrapper indicating a generic unhandled exception was thrown by the
+ * Prometheus sink.
+ */
+public class PrometheusSinkException extends RuntimeException {
Review Comment:
`@Internal`?
##########
flink-connector-prometheus/src/main/java/org/apache/flink/connector/prometheus/sink/PrometheusSinkWriter.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.prometheus.sink;
+
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.config.AsyncSinkWriterConfiguration;
+import org.apache.flink.connector.prometheus.sink.metrics.SinkMetricsCallback;
+import org.apache.flink.connector.prometheus.sink.prometheus.Remote;
+import org.apache.flink.connector.prometheus.sink.prometheus.Types;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.core5.io.CloseMode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xerial.snappy.Snappy;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Writer, taking care of batching the {@link PrometheusTimeSeries} and handling retries.
+ *
+ * <p>The batching of this sink is in terms of Samples, not bytes. The goal is adaptively increase
+ * the number of Samples in each batch, a WriteRequest sent to Prometheus, to a configurable number.
+ * This is the parameter maxBatchSizeInBytes.
+ *
+ * <p>getSizeInBytes(requestEntry) returns the number of Samples (not bytes) and maxBatchSizeInBytes
+ * is actually in terms of Samples (not bytes).
+ *
+ * <p>In AsyncSinkWriter, maxBatchSize is in terms of requestEntries (TimeSeries). But because each
+ * TimeSeries contains 1+ Samples, we set maxBatchSize = maxBatchSizeInBytes.
+ *
+ * <p>maxRecordSizeInBytes is also calculated in the same unit assumed by getSizeInBytes(...). In
+ * our case is the max number of Samples in a single TimeSeries sent to the Sink. We are limiting
+ * the number of Samples in each TimeSeries to the max batch size, setting maxRecordSizeInBytes =
+ * maxBatchSizeInBytes.
+ */
+public class PrometheusSinkWriter extends AsyncSinkWriter<PrometheusTimeSeries, Types.TimeSeries> {
Review Comment:
`@Internal`
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2346741773
@hlteoh37 I should have addressed all comments.
The configuration classes have been moved into a top-level `PrometheusSinkConfiguration` class
--
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
Re: [PR] [FLINK-33138] DataStream API implementation [flink-connector-prometheus]
Posted by "nicusX (via GitHub)" <gi...@apache.org>.
nicusX commented on PR #1:
URL: https://github.com/apache/flink-connector-prometheus/pull/1#issuecomment-2348323175
@hlteoh37 all non-test classes are now annotated with either `@PublicEvolving` or `@Internal`.
All .java, .xml, and .properties file have the Apache 2.0 license header.
Note that the .proto files, that have been copied into the project just for reference, have their own license header
--
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