sabhyankar commented on a change in pull request #11950: URL: https://github.com/apache/beam/pull/11950#discussion_r438777187
########## File path: sdks/java/io/splunk/src/main/java/org/apache/beam/sdk/io/splunk/HttpEventPublisher.java ########## @@ -0,0 +1,346 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS 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.checkNotNull; + +import com.google.api.client.http.ByteArrayContent; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; +import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.HttpMediaType; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpRequestFactory; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.apache.v2.ApacheHttpTransport; +import com.google.api.client.util.ExponentialBackOff; +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 javax.net.ssl.HostnameVerifier; +import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting; +import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Joiner; +import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.ssl.SSLContextBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A utility class that helps write {@link SplunkEvent} records to Splunk's Http Event Collector + * (HEC) endpoint. + */ +@AutoValue +abstract class HttpEventPublisher { + + private static final Logger LOG = LoggerFactory.getLogger(HttpEventPublisher.class); + + private static final int DEFAULT_MAX_CONNECTIONS = 1; + + private static final boolean DEFAULT_DISABLE_CERTIFICATE_VALIDATION = false; + + private static final Gson GSON = + new GsonBuilder().setFieldNamingStrategy(f -> f.getName().toLowerCase()).create(); + + @VisibleForTesting static final String HEC_URL_PATH = "services/collector/event"; + + private static final HttpMediaType MEDIA_TYPE = + new HttpMediaType("application/json;profile=urn:splunk:event:1.0;charset=utf-8"); + + private static final String CONTENT_TYPE = + Joiner.on('/').join(MEDIA_TYPE.getType(), MEDIA_TYPE.getSubType()); + + private static final String AUTHORIZATION_SCHEME = "Splunk %s"; + + private static final String HTTPS_PROTOCOL_PREFIX = "https"; + + /** Provides a builder for creating a {@link HttpEventPublisher}. */ + static Builder newBuilder() { + return new AutoValue_HttpEventPublisher.Builder(); + } + + abstract ApacheHttpTransport transport(); + + abstract HttpRequestFactory requestFactory(); + + abstract GenericUrl genericUrl(); + + abstract String token(); + + @Nullable + abstract Integer maxElapsedMillis(); + + abstract Boolean disableCertificateValidation(); + + /** + * Executes a POST for the list of {@link SplunkEvent} objects into Splunk's Http Event Collector + * endpoint. + * + * @param events list of {@link SplunkEvent}s + * @return {@link HttpResponse} for the POST + */ + HttpResponse execute(List<SplunkEvent> events) throws IOException { + + HttpContent content = getContent(events); + HttpRequest request = requestFactory().buildPostRequest(genericUrl(), content); + + HttpBackOffUnsuccessfulResponseHandler responseHandler = + new HttpBackOffUnsuccessfulResponseHandler(getConfiguredBackOff()); + + responseHandler.setBackOffRequired(BackOffRequired.ON_SERVER_ERROR); + + request.setUnsuccessfulResponseHandler(responseHandler); + setHeaders(request, token()); + + return request.execute(); + } + + /** + * Same as {@link HttpEventPublisher#execute(List)} but with a single {@link SplunkEvent}. + * + * @param event {@link SplunkEvent} object + */ + HttpResponse execute(SplunkEvent event) throws IOException { + return this.execute(ImmutableList.of(event)); + } + + /** + * Returns an {@link ExponentialBackOff} with the right settings. + * + * @return {@link ExponentialBackOff} object + */ + @VisibleForTesting + ExponentialBackOff getConfiguredBackOff() { + return new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(maxElapsedMillis()).build(); + } + + /** Shutsdown connection manager and releases all resources. */ + void close() throws IOException { + if (transport() != null) { + LOG.info("Closing publisher transport."); + transport().shutdown(); + } + } + + /** + * Utility method to set Authorization and other relevant http headers into the {@link + * HttpRequest}. + * + * @param request {@link HttpRequest} object to add headers to + * @param token Splunk's HEC authorization token + */ + private void setHeaders(HttpRequest request, String token) { + request.getHeaders().setAuthorization(String.format(AUTHORIZATION_SCHEME, token)); + } + + /** + * Marshals a list of {@link SplunkEvent}s into an {@link HttpContent} object that can be used to + * create an {@link HttpRequest}. + * + * @param events list of {@link SplunkEvent}s + * @return {@link HttpContent} that can be used to create an {@link HttpRequest}. + */ + @VisibleForTesting + HttpContent getContent(List<SplunkEvent> events) { + String payload = getStringPayload(events); + LOG.debug("Payload content: {}", payload); + return ByteArrayContent.fromString(CONTENT_TYPE, payload); + } + + /** Extracts the payload string from a list of {@link SplunkEvent}s. */ + @VisibleForTesting + String getStringPayload(List<SplunkEvent> events) { + StringBuilder sb = new StringBuilder(); + events.forEach(event -> sb.append(GSON.toJson(event))); Review comment: Its not necessary to have newlines or separators as the batch protocol for Splunk's HEC is [simple event objects stacked one after the other and not necessarily in a JSON array.](https://docs.splunk.com/Documentation/Splunk/8.0.4/Data/FormateventsforHTTPEventCollector#Examples) ---------------------------------------------------------------- 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