Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,13 @@ For non-Java applications or tools like `cqlsh`, you can run the Spanner Cassand
-Dhost=127.0.0.1 \
-Dport=9042 \
-DnumGrpcChannels=4 \
-DhealthCheckPort=8080 \
-jar path/to/your/spanner-cassandra-launcher.jar
```

* Replace the value of `-DdatabaseUri` with your Spanner database URI.
* You can omit `-Dhost` to use the default `0.0.0.0`, omit `-Dport` to use the default `9042`, and omit `-DnumGrpcChannels` to use the default `4`.
* `-DhealthCheckPort` is optional. If specified, a health check endpoint will be started on same IP address as that of the client on the specified port at url `/debug/health`. The health check endpoint will return HTTP status `200: OK` if the client is up and running, and `503: Service Unavailable` otherwise. The health check endpoint is NOT enabled by default.

## View and manage client-side metrics

Expand Down
5 changes: 5 additions & 0 deletions google-cloud-spanner-cassandra/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@
<artifactId>truth</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<scope>test</scope>
Comment thread
ath-08 marked this conversation as resolved.
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
Copyright 2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.cloud.spanner.adapter;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* A simple, lightweight HTTP server for health check monitoring.
*
* <p>It listens on a configured host and port, responding to {@code GET} requests on the {@code
* /debug/health} endpoint.
*/
final class HealthCheckServer {
private static final Logger LOG = LoggerFactory.getLogger(HealthCheckServer.class);
private static final int HTTP_OK_STATUS = 200;
private static final int HTTP_UNAVAILABLE_STATUS = 503;
private static final int HTTP_METHOD_NOT_ALLOWED = 405;

private final HttpServer server;
private final AtomicBoolean isReady = new AtomicBoolean(false);

HealthCheckServer(InetAddress address, int port) throws IOException {
this.server = HttpServer.create(new InetSocketAddress(address, port), 0);
this.server.createContext("/debug/health", new HealthCheckHandler());
}

void start() {
server.start();
LOG.info("Health check server started on {}/debug/health", server.getAddress());
}

void stop() {
server.stop(0);
LOG.info("Health check server stopped.");
}

InetSocketAddress getAddress() {
return server.getAddress();
}

void setReady(boolean ready) {
isReady.set(ready);
}

/** This handler responds to health check requests. */
private class HealthCheckHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
if (!"GET".equalsIgnoreCase(exchange.getRequestMethod())) {
// Respond with 405 Method Not Allowed for non-GET requests
exchange.sendResponseHeaders(HTTP_METHOD_NOT_ALLOWED, -1);
return;
}
if (isReady.get()) {
sendResponse(exchange, HTTP_OK_STATUS, "All listeners are up and running");
} else {
sendResponse(exchange, HTTP_UNAVAILABLE_STATUS, "Service Unavailable");
}
}

private void sendResponse(HttpExchange exchange, int statusCode, String response)
throws IOException {
byte[] responseBytes = response.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.sendResponseHeaders(statusCode, responseBytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(responseBytes);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.google.cloud.spanner.adapter;

import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsProvider;
import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsRecorder;
import com.google.spanner.adapter.v1.DatabaseName;
import io.opentelemetry.api.OpenTelemetry;
import java.io.IOException;
import java.net.InetAddress;
import java.time.Duration;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -43,6 +44,8 @@
* with Spanner. Defaults to 4.
* <li>{@code maxCommitDelayMillis}: (Optional) The max commit delay to set in requests to
* optimize write throughput, in milliseconds. Defaults to none.
* <li>{@code healthCheckPort}: (Optional) The port number for the health check server. If
* unspecifed, health check server will NOT be started.
* </ul>
*
* Example usage:
Expand All @@ -53,7 +56,8 @@
* -Dport=9042 \
* -DnumGrpcChannels=4 \
* -DmaxCommitDelayMillis=5 \
* -cp path/to/your/spanner-cassandra-launcher.jar com.google.cloud.spanner.adapter.SpannerCassandraLauncher
* -DhealthCheckPort=8080 \
* -jar com.google.cloud.spanner.adapter.SpannerCassandraLauncher
* </pre>
*
* @see Adapter
Expand All @@ -72,6 +76,38 @@ public class Launcher {
private static final String DEFAULT_NUM_GRPC_CHANNELS = "4";
private static final String MAX_COMMIT_DELAY_PROP_KEY = "maxCommitDelayMillis";
private static final String ENABLE_BUILTIN_METRICS_PROP_KEY = "enableBuiltInMetrics";
private static final String HEALTH_CHECK_PORT_PROP_KEY = "healthCheckPort";

private final Adapter adapter;
private final HealthCheckServer healthCheckServer;

Launcher(Adapter adapter, @Nullable HealthCheckServer healthCheckServer) {
this.adapter = adapter;
this.healthCheckServer = healthCheckServer;
}

void launch() {
healthCheckServer.start();
adapter.start();

Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
if (healthCheckServer != null) {
healthCheckServer.stop();
}
try {
adapter.stop();
} catch (IOException e) {
LOG.warn("Error while stopping Adapter: " + e.getMessage());
}
}));

if (healthCheckServer != null) {
healthCheckServer.setReady(true);
}
}

public static void main(String[] args) throws Exception {
final String databaseUri = System.getProperty(DATABASE_URI_PROP_KEY);
Expand All @@ -83,12 +119,25 @@ public static void main(String[] args) throws Exception {
final String maxCommitDelayProperty = System.getProperty(MAX_COMMIT_DELAY_PROP_KEY);
final boolean enableBuiltInMetrics =
Boolean.parseBoolean(System.getProperty(ENABLE_BUILTIN_METRICS_PROP_KEY, "false"));
final String healthCheckPortStr = System.getProperty(HEALTH_CHECK_PORT_PROP_KEY);
HealthCheckServer healthCheckServer = null;

if (databaseUri == null) {
throw new IllegalArgumentException(
"Spanner database URI not set. Please set it using -DdatabaseUri option.");
}

if (healthCheckPortStr != null) {
final int healthCheckPort = Integer.parseInt(healthCheckPortStr);
if (healthCheckPort < 0 || healthCheckPort > 65535) {
throw new IllegalArgumentException(
"Invalid health check port '" + healthCheckPort + "'. Must be between 0 and 65535");
}
healthCheckServer = new HealthCheckServer(inetAddress, healthCheckPort);
} else {
LOG.debug("Health check server is disabled.");
}

DatabaseName databaseName = DatabaseName.parse(databaseUri);
OpenTelemetry openTelemetry =
enableBuiltInMetrics
Expand Down Expand Up @@ -122,8 +171,8 @@ public static void main(String[] args) throws Exception {
numGrpcChannels,
maxCommitDelayProperty,
enableBuiltInMetrics);

adapter.start();
Launcher launcher = new Launcher(adapter, healthCheckServer);
launcher.launch();

try {
Thread.currentThread().join();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
Copyright 2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.cloud.spanner.adapter;

import static com.google.common.truth.Truth.assertThat;

import java.io.IOException;
import java.net.InetAddress;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public final class HealthCheckServerTest {
private HealthCheckServer server;
private CloseableHttpClient client;
private String baseUri;

@Before
public void setUp() throws IOException {
// Start the server on an ephemeral port (port 0) to avoid conflicts.
server = new HealthCheckServer(InetAddress.getLoopbackAddress(), 0);
server.start();

// Get the actual port the server is listening on to build the request URI.
final int port = server.getAddress().getPort();
baseUri = "http://localhost:" + port;

// Create a default HttpClient instance.
client = HttpClients.createDefault();
}

@After
public void tearDown() throws IOException {
if (server != null) {
server.stop();
}
if (client != null) {
client.close(); // Close the client to release resources.
}
}

@Test
public void server_whenNotReady_returns503() throws IOException {
final HttpGet request = new HttpGet(baseUri + "/debug/health");

client.execute(
request,
response -> {
assertThat(response.getCode()).isEqualTo(503);
assertThat(EntityUtils.toString(response.getEntity())).isEqualTo("Service Unavailable");
return null;
});
}

@Test
public void server_whenSetToReady_returns200() throws IOException {
server.setReady(true);
final HttpGet request = new HttpGet(baseUri + "/debug/health");

client.execute(
request,
response -> {
assertThat(response.getCode()).isEqualTo(200);
assertThat(EntityUtils.toString(response.getEntity()))
.isEqualTo("All listeners are up and running");
return null;
});
}

@Test
public void server_whenToggledToNotReady_returns503() throws IOException {
server.setReady(true);
server.setReady(false);
final HttpGet request = new HttpGet(baseUri + "/debug/health");

client.execute(
request,
response -> {
assertThat(response.getCode()).isEqualTo(503);
return null;
});
}

@Test
public void server_withPostRequest_returns405() throws IOException {
final HttpPost request = new HttpPost(baseUri + "/debug/health");

client.execute(
request,
response -> {
assertThat(response.getCode()).isEqualTo(405);
return null;
});
}

@Test
public void server_withInvalidPath_returns404() throws IOException {
final HttpGet request = new HttpGet(baseUri + "/invalid/path");

client.execute(
request,
response -> {
assertThat(response.getCode()).isEqualTo(404);
return null;
});
}
}
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@
<version>1.4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner-cassandra</artifactId>
Expand Down
Loading