sabhyankar commented on a change in pull request #11950:
URL: https://github.com/apache/beam/pull/11950#discussion_r438829308



##########
File path: 
sdks/java/io/splunk/src/main/java/org/apache/beam/sdk/io/splunk/SplunkEventWriter.java
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.sdk.io.splunk;
+
+import static 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
+import static 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.api.client.http.HttpResponse;
+import com.google.api.client.http.HttpResponseException;
+import com.google.auto.value.AutoValue;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Metrics;
+import org.apache.beam.sdk.options.ValueProvider;
+import org.apache.beam.sdk.state.BagState;
+import org.apache.beam.sdk.state.StateSpec;
+import org.apache.beam.sdk.state.StateSpecs;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.state.Timer;
+import org.apache.beam.sdk.state.TimerSpec;
+import org.apache.beam.sdk.state.TimerSpecs;
+import org.apache.beam.sdk.state.ValueState;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.values.KV;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.MoreObjects;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** A {@link DoFn} to write {@link SplunkEvent}s to Splunk's HEC endpoint. */
+@AutoValue
+abstract class SplunkEventWriter extends DoFn<KV<Integer, SplunkEvent>, 
SplunkWriteError> {
+
+  private static final Integer DEFAULT_BATCH_COUNT = 1;
+  private static final Boolean DEFAULT_DISABLE_CERTIFICATE_VALIDATION = false;
+  private static final Logger LOG = 
LoggerFactory.getLogger(SplunkEventWriter.class);
+  private static final long DEFAULT_FLUSH_DELAY = 2;
+  private static final Counter INPUT_COUNTER =
+      Metrics.counter(SplunkEventWriter.class, "inbound-events");
+  private static final Counter SUCCESS_WRITES =
+      Metrics.counter(SplunkEventWriter.class, "outbound-successful-events");
+  private static final Counter FAILED_WRITES =
+      Metrics.counter(SplunkEventWriter.class, "outbound-failed-events");
+  private static final String BUFFER_STATE_NAME = "buffer";
+  private static final String COUNT_STATE_NAME = "count";
+  private static final String TIME_ID_NAME = "expiry";
+
+  @StateId(BUFFER_STATE_NAME)
+  private final StateSpec<BagState<SplunkEvent>> buffer = StateSpecs.bag();
+
+  @StateId(COUNT_STATE_NAME)
+  private final StateSpec<ValueState<Long>> count = StateSpecs.value();
+
+  @TimerId(TIME_ID_NAME)
+  private final TimerSpec expirySpec = TimerSpecs.timer(TimeDomain.EVENT_TIME);
+
+  private Integer batchCount;
+  private Boolean disableValidation;
+  private HttpEventPublisher publisher;
+
+  private static final Gson GSON =
+      new GsonBuilder().setFieldNamingStrategy(f -> 
f.getName().toLowerCase()).create();
+
+  /** A builder class for creating a {@link SplunkEventWriter}. */
+  static Builder newBuilder() {
+    return new AutoValue_SplunkEventWriter.Builder();
+  }
+
+  @Nullable
+  abstract ValueProvider<String> url();
+
+  @Nullable
+  abstract ValueProvider<String> token();
+
+  @Nullable
+  abstract ValueProvider<Boolean> disableCertificateValidation();
+
+  @Nullable
+  abstract ValueProvider<Integer> inputBatchCount();
+
+  @Setup
+  public void setup() {
+
+    checkArgument(url().isAccessible(), "url is required for writing events.");
+    checkArgument(token().isAccessible(), "Access token is required for 
writing events.");
+
+    // Either user supplied or default batchCount.
+    if (batchCount == null) {
+
+      if (inputBatchCount() != null) {
+        batchCount = inputBatchCount().get();
+      }
+
+      batchCount = MoreObjects.firstNonNull(batchCount, DEFAULT_BATCH_COUNT);
+      LOG.info("Batch count set to: {}", batchCount);
+    }
+
+    // Either user supplied or default disableValidation.
+    if (disableValidation == null) {
+
+      if (disableCertificateValidation() != null) {
+        disableValidation = disableCertificateValidation().get();
+      }
+
+      disableValidation =
+          MoreObjects.firstNonNull(disableValidation, 
DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
+      LOG.info("Disable certificate validation set to: {}", disableValidation);
+    }
+
+    try {
+      HttpEventPublisher.Builder builder =
+          HttpEventPublisher.newBuilder()
+              .withUrl(url().get())
+              .withToken(token().get())
+              .withDisableCertificateValidation(disableValidation);
+
+      publisher = builder.build();
+      LOG.info("Successfully created HttpEventPublisher");
+
+    } catch (NoSuchAlgorithmException
+        | KeyStoreException
+        | KeyManagementException
+        | UnsupportedEncodingException e) {
+      LOG.error("Error creating HttpEventPublisher: {}", e.getMessage());
+      throw new RuntimeException(e);
+    }
+  }
+
+  @ProcessElement
+  public void processElement(
+      @Element KV<Integer, SplunkEvent> input,
+      OutputReceiver<SplunkWriteError> receiver,
+      BoundedWindow window,
+      @StateId(BUFFER_STATE_NAME) BagState<SplunkEvent> bufferState,
+      @StateId(COUNT_STATE_NAME) ValueState<Long> countState,
+      @TimerId(TIME_ID_NAME) Timer timer)
+      throws IOException {
+
+    Long count = MoreObjects.<Long>firstNonNull(countState.read(), 0L);
+    SplunkEvent event = input.getValue();
+    INPUT_COUNTER.inc();
+    bufferState.add(event);
+    count += 1;
+    countState.write(count);
+    timer.offset(Duration.standardSeconds(DEFAULT_FLUSH_DELAY)).setRelative();
+
+    if (count >= batchCount) {
+
+      LOG.info("Flushing batch of {} events", count);
+      flush(receiver, bufferState, countState);
+    }
+  }
+
+  @OnTimer(TIME_ID_NAME)
+  public void onExpiry(
+      OutputReceiver<SplunkWriteError> receiver,
+      @StateId(BUFFER_STATE_NAME) BagState<SplunkEvent> bufferState,
+      @StateId(COUNT_STATE_NAME) ValueState<Long> countState)
+      throws IOException {
+
+    if (MoreObjects.<Long>firstNonNull(countState.read(), 0L) > 0) {
+      LOG.info("Flushing window with {} events", countState.read());
+      flush(receiver, bufferState, countState);
+    }
+  }
+
+  @Teardown
+  public void tearDown() {
+    if (this.publisher != null) {
+      try {
+        this.publisher.close();
+        LOG.info("Successfully closed HttpEventPublisher");
+
+      } catch (IOException e) {
+        LOG.warn("Received exception while closing HttpEventPublisher: {}", 
e.getMessage());
+      }
+    }
+  }
+
+  /**
+   * Flushes a batch of requests via {@link HttpEventPublisher}.
+   *
+   * @param receiver Receiver to write {@link SplunkWriteError}s to
+   */
+  private void flush(
+      OutputReceiver<SplunkWriteError> receiver,
+      @StateId(BUFFER_STATE_NAME) BagState<SplunkEvent> bufferState,
+      @StateId(COUNT_STATE_NAME) ValueState<Long> countState)

Review comment:
       Done




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to