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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ For non-Java applications or tools like `cqlsh`, you can run the Spanner Cassand
**Configuration Notes:**

* **Database URI**: You must specify the Spanner database URI. This is done via the `databaseUri` property in YAML or the `-DdatabaseUri` system property.
* **Host**: The default host is `0.0.0.0`. This can be overridden with the `host` property in YAML or `-Dhost`.
* **Host**: The default host is `127.0.0.1`. This can be overridden with the `host` property in YAML or `-Dhost`.
* **Port**: The default port is `9042`. This can be overridden with the `port` property in YAML or `-Dport`.
* **gRPC Channels**: The default number of gRPC channels is `4`. This can be overridden with `numGrpcChannels` in YAML or `-DnumGrpcChannels`.
* **Health Check**: You can optionally enable a health check endpoint.
Expand Down
2 changes: 1 addition & 1 deletion docs/config-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ globalClientConfigs:
listeners:
# The name of the listener. It is recommended to use a meaningful name, such as the cluster name.
- name: "listener_1"
# [Optional] The host to bind the listener to. Defaults to "0.0.0.0".
# [Optional] The host to bind the listener to. Defaults to "127.0.0.1".
host: "127.0.0.1"
# [Optional] The port to bind the listener to. Defaults to 9042.
port: 9042
Expand Down
2 changes: 2 additions & 0 deletions docs/cqlsh.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ Replace `<java_client_hostname>` and `<java_client_port>` with the appropriate v

### Option 2: Use Dockerized cqlsh

> **Note:** By default, the standalone Spanner Cassandra Launcher binds to `127.0.0.1`. To connect from inside a Docker container, either run the container with host networking (`docker run --network host -it nuvo/docker-cqlsh cqlsh 127.0.0.1 9042 --protocol-version 4`) or start the launcher with `-Dhost=0.0.0.0` (or `host: "0.0.0.0"` in `config.yaml`) behind appropriate firewall controls.

#### Step 1: Install Docker

Ensure Docker is installed on your machine. Follow the instructions on the [Docker website](https://docs.docker.com/get-docker/) to install Docker for your operating system.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.google.cloud.NoCredentials;
import com.google.cloud.spanner.adapter.SpannerCqlSessionBuilder.InstanceType;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.spanner.adapter.v1.AdapterClient;
import com.google.spanner.adapter.v1.AdapterSettings;
Expand Down Expand Up @@ -178,7 +179,10 @@ void start() {
serverSocket =
new ServerSocket(
options.getTcpPort(), DEFAULT_CONNECTION_BACKLOG, options.getInetAddress());
LOG.info("Local TCP server started on {}:{}", options.getInetAddress(), options.getTcpPort());
LOG.info(
"Local TCP server started on {}:{}",
options.getInetAddress(),
serverSocket.getLocalPort());

if (executor == null) {
executor = Executors.newCachedThreadPool();
Expand Down Expand Up @@ -211,6 +215,17 @@ void stop() throws IOException {
LOG.info("Adapter stopped.");
}

/**
* Returns the local port the server socket is bound to (the OS-assigned port when {@code tcpPort}
* is {@code 0}).
*
* @throws IllegalStateException if the adapter has not been started.
*/
int getBoundPort() {
Preconditions.checkState(started && serverSocket != null, "Adapter was never started!");
return serverSocket.getLocalPort();
}

private void acceptClientConnections() {
try {
while (!Thread.currentThread().isInterrupted()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.google.common.base.Strings;
import java.net.InetAddress;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;

/** Options for creating the {@link Adapter}. */
Expand All @@ -33,7 +34,7 @@ class AdapterOptions {
static class Builder {
String spannerEndpoint = DEFAULT_SPANNER_ENDPOINT;
int tcpPort;
InetAddress inetAddress;
InetAddress inetAddress = InetAddress.getLoopbackAddress();
String databaseUri;
int numGrpcChannels = DEFAULT_NUM_GRPC_CHANNELS;
Optional<Duration> maxCommitDelay = Optional.empty();
Expand All @@ -60,7 +61,7 @@ Builder tcpPort(int tcpPort) {

/** The specific local {@link InetAddress} for the server socket to bind to. */
Builder inetAddress(InetAddress inetAddress) {
this.inetAddress = inetAddress;
this.inetAddress = Objects.requireNonNull(inetAddress, "inetAddress cannot be null");
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
* <ul>
* <li>{@code databaseUri}: (Required) The URI of the target Spanner database.
* <li>{@code host}: (Optional) The hostname or IP address to bind the service to. Defaults to
* "0.0.0.0".
* "127.0.0.1".
* <li>{@code port}: (Optional) The port number to bind the service to. Defaults to 9042.
* <li>{@code numGrpcChannels}: (Optional) The number of gRPC channels to use for communication
* with Spanner. Defaults to 4.
Expand Down Expand Up @@ -212,6 +212,7 @@ public void shutdown() {
}

private void startHealthCheckServer(HealthCheckConfig config) throws IOException {
warnIfNonLoopback(config.getHostAddress(), "health check server");
healthCheckServer =
adapterFactory.createHealthCheckServer(config.getHostAddress(), config.getPort());
healthCheckServer.start();
Expand Down Expand Up @@ -264,6 +265,7 @@ private DatabaseName resolveDatabaseName(ListenerConfig config) {
}

private void startAdapter(ListenerConfig config) throws IOException {
warnIfNonLoopback(config.getHostAddress(), "listener");
LOG.info(
"Starting Adapter for Spanner database {} on {}:{} with {} gRPC channels, max commit"
+ " delay of {} and built-in metrics enabled: {}",
Expand All @@ -283,4 +285,22 @@ private void startAdapter(ListenerConfig config) throws IOException {
adapters.add(adapter);
adapter.start();
}

/**
* Logs a WARN when {@code address} is {@code null} (wildcard) or non-loopback.
*
* @return {@code true} if a warning was logged.
*/
static boolean warnIfNonLoopback(InetAddress address, String component) {
if (address == null || !address.isLoopbackAddress()) {
LOG.warn(
"Binding {} to non-loopback address {} exposes the unauthenticated adapter over the"
+ " network. Prefer 127.0.0.1 or ::1 unless remote access is secured by network"
+ " controls.",
component,
address);
return true;
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.google.cloud.spanner.adapter.configs.ListenerConfigs;
import com.google.cloud.spanner.adapter.configs.UserConfigs;
import com.google.common.base.Strings;
import com.google.common.net.HostAndPort;
import com.google.spanner.adapter.v1.DatabaseName;
import java.net.InetAddress;
import java.net.UnknownHostException;
Expand Down Expand Up @@ -398,14 +399,21 @@ public int getPort() {
}

static HealthCheckConfig fromEndpointString(String endpoint) throws UnknownHostException {
String[] parts = endpoint.split(":");
if (parts.length != 2) {
final HostAndPort hostAndPort;
try {
hostAndPort = HostAndPort.fromString(endpoint);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid health check endpoint format '" + endpoint + "'. Expected 'host:port'.", e);
}
if (!hostAndPort.hasPort() || Strings.isNullOrEmpty(hostAndPort.getHost())) {
throw new IllegalArgumentException(
"Invalid health check endpoint format '" + endpoint + "'. Expected 'host:port'.");
}
String host = parts[0];
int port = parsePort(parts[1]);
return newBuilder().hostAddress(InetAddress.getByName(host)).port(port).build();
return newBuilder()
.hostAddress(InetAddress.getByName(hostAndPort.getHost()))
.port(hostAndPort.getPort())
.build();
}

@Nullable
Expand Down
Loading
Loading