Compare commits

..

1 Commits

Author SHA1 Message Date
Jon Chambers
44e11fc773 Add an action for testing on new pull requests.
Some checks failed
Service CI / build (push) Has been cancelled
2020-07-02 18:13:04 -04:00
34 changed files with 159 additions and 632 deletions

View File

@ -4,20 +4,13 @@ on: [push, pull_request]
jobs:
build:
strategy:
matrix:
os:
- ubuntu-latest
- macos-latest
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@v1
with:
java-version: 11
distribution: 'temurin'
cache: 'maven'
- name: Build with Maven
run: mvn -e -B test

View File

@ -5,7 +5,7 @@ Redis embedded server for Java integration testing
Fork Notes
==============
This repository is a fork of https://github.com/ozimov/embedded-redis, which is in turn a fork of https://github.com/kstyrc/embedded-redis. We've updated the embedded Redis binaries to version 7.0.15 so we can write tests that use recent Redis features without imposing dependencies that are not well-encapsulated by a single Maven/Gradle build.
This repository is a fork of https://github.com/ozimov/embedded-redis, which is in turn a fork of https://github.com/kstyrc/embedded-redis. We've updated the embedded Redis binaries to version 6.0.5 so we can write tests that use recent Redis features without imposing dependencies that are not well-encapsulated by a single Maven/Gradle build.
Maven dependency
==============
@ -15,7 +15,7 @@ Maven Central:
<dependency>
<groupId>org.signal</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.9.0</version>
<version>0.8.0</version>
</dependency>
```
@ -38,11 +38,10 @@ RedisServer redisServer = new RedisServer("/path/to/your/redis", 6379);
// 2) given os-independent matrix
RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
.override(OS.UNIX, "/path/to/unix/redis")
.override(OS.UNIX, Architecture.x86_64, "/path/to/unix/redis.x86_64")
.override(OS.UNIX, Architecture.arm64, "/path/to/unix/redis.arm64")
.override(OS.UNIX, Architecture.x86, "/path/to/unix/redis.i386")
.override(OS.MAC_OS_X, Architecture.x86_64, "/path/to/macosx/redis-x86_64")
.override(OS.MAC_OS_X, Architecture.arm64, "/path/to/macosx/redis.arm64")
.override(OS.WINDOWS, Architecture.x86, "/path/to/windows/redis")
.override(OS.Windows, Architecture.x86_64, "/path/to/windows/redis")
.override(OS.MAC_OS_X, Architecture.x86, "/path/to/macosx/redis")
.override(OS.MAC_OS_X, Architecture.x86_64, "/path/to/macosx/redis")
RedisServer redisServer = new RedisServer(customProvider, 6379);
```
@ -142,12 +141,10 @@ Redis version
By default, RedisServer runs an OS-specific executable enclosed in in the `embedded-redis` jar. The jar includes:
- Redis 7.0.15 for Linux/Unix (i386, x86_64 and arm64)
- Redis 7.0.15 for macOS (x86_64 and arm64e AKA Apple Silicon)
- Redis 6.0.5 for Linux/Unix (amd64 and x86)
- Redis 6.0.5 for macOS (amd64)
The enclosed binaries are built from source from the [`7.0.15` tag](https://github.com/redis/redis/releases/tag/7.0.15) in the official Redis repository. The Linux and Darwin/macOS binaries are statically-linked amd64 and x86 executables built using the [build-server-binaries.sh](src/main/docker/build-server-binaries.sh) script included in this repository at `/src/main/docker`. Windows binaries are not included because Windows is not officially supported by Redis.
Note: the `build-server-binaries.sh` script attempts to build all of the above noted OS and architectures, which means that it expects the local Docker daemon to support all of them. Docker Desktop on macOS and Windows supports multi-arch builds out of the box; Docker on Linux may require [additional configuration](https://docs.docker.com/buildx/working-with-buildx/).
The enclosed binaries are built from source from the [`6.0.5` tag](https://github.com/antirez/redis/releases/tag/6.0.5) in the official Redis repository. The Linux binaries are statically-linked amd64 and x86 executables built using the `build-server-binaries.sh` script included in this repository at `/src/main/docker`. The macOS binaries are built according to the [instructions in the README](https://github.com/antirez/redis/blob/51efb7fe25753867d39aa88a521f7c275fd8cddb/README.md#building-redis). Windows binaries are not included because Windows is not officially supported by Redis.
Callers may provide a path to a specific `redis-server` executable if needed.
@ -156,19 +153,6 @@ License
==============
Licensed under the Apache License, Version 2.0
The included Redis binaries are covered by [Rediss license](https://github.com/redis/redis/blob/4930d19e70c391750479951022e207e19111eb55/COPYING):
> Copyright (c) 2006-2020, Salvatore Sanfilippo
> All rights reserved.
>
> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
>
> * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
> * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
> * Neither the name of Redis nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
>
> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Contributors
==============
@ -179,29 +163,10 @@ Contributors
* Sean Simonsen ([@SeanSimonsen](https://github.com/SeanSimonsen))
* Rob Winch ([@rwinch](https://github.com/rwinch))
* Jon Chambers ([@jchambers](https://github.com/jchambers))
* Chris Eager ([@eager](https://github.com/eager))
Changelog
==============
### 0.9.0
* Updated to Redis 7.0.15
* Updated Guava to 33
* Updated JUnit to 4.13.2
### 0.8.3
* Updated to Redis 6.2.7
* Statically link Linux binaries with OpenSSL instead of LibreSSL to avoid `openssl.cnf` incompatibilities
### 0.8.2
* Updated to Redis 6.2.6
* Added native support for Apple Silicon (darwin/arm64) and Linux aarch64
* Compiled Redis servers with TLS support
### 0.8.1
* Include statically-linked Redis binaries
* Update still more dependencies
### 0.8
* Updated to Redis 6.0.5
* Dropped support for Windows

77
pom.xml
View File

@ -4,7 +4,7 @@
<groupId>org.signal</groupId>
<artifactId>embedded-redis</artifactId>
<packaging>jar</packaging>
<version>0.9.2-SNAPSHOT</version>
<version>0.8.1-SNAPSHOT</version>
<name>embedded-redis</name>
<description>Redis embedded server for Java integration testing.</description>
<url>https://github.com/signalapp/embedded-redis</url>
@ -21,7 +21,7 @@
<url>https://github.com/signalapp/embedded-redis</url>
<connection>scm:git:https://github.com/signalapp/embedded-redis.git</connection>
<developerConnection>scm:git:git@github.com:signalapp/embedded-redis.git</developerConnection>
<tag>0.9.1</tag>
<tag>HEAD</tag>
</scm>
<developers>
@ -39,20 +39,21 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.0.0-jre</version>
<version>29.0-jre</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.17.0</version>
<version>2.7</version>
</dependency>
<!-- TEST DEPENDENCIES -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.10.2</version>
<version>2.8.2</version>
<!-- incompatible with 2.9.0 and up: https://github.com/ozimov/embedded-redis/pull/4 -->
<scope>test</scope>
</dependency>
<dependency>
@ -65,7 +66,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -89,13 +90,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>8</source>
<target>8</target>
@ -105,7 +105,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.3.0</version>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
@ -118,7 +118,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.6.3</version>
<version>3.2.0</version>
<configuration>
<source>8</source>
</configuration>
@ -134,7 +134,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.2.2</version>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
@ -148,7 +148,7 @@
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
@ -156,59 +156,6 @@
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
<executions>
<execution>
<id>copy-test-certs</id>
<phase>process-test-resources</phase>
<goals>
<goal>testResources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>${project.basedir}/src/test/bash/tests/tls</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>generate-test-certificates</id>
<phase>generate-test-resources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>./gen-test-certs-if-needed.sh</executable>
<workingDirectory>${project.basedir}/src/test/bash</workingDirectory>
<arguments>
<argument>${project.build.testOutputDirectory}</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>cleanup-test-certificates</id>
<phase>process-test-resources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>./cleanup-test-certs.sh</executable>
<workingDirectory>${project.basedir}/src/test/bash</workingDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,2 +0,0 @@
redis-server-*
redis-*

View File

@ -1,18 +0,0 @@
ARG ALPINE_VERSION=3.19.1
FROM alpine:${ALPINE_VERSION}
RUN apk add --no-cache gcc musl-dev openssl-dev openssl-libs-static make pkgconfig linux-headers
WORKDIR /build
ARG REDIS_VERSION
ENV REDIS_VERSION=${REDIS_VERSION}
COPY redis-${REDIS_VERSION}.tar.gz /redis-${REDIS_VERSION}.tar.gz
RUN ls -l /
ARG ARCH
RUN tar zxf /redis-${REDIS_VERSION}.tar.gz && \
cd redis-${REDIS_VERSION} && \
make BUILD_TLS='yes' CC='gcc -static' LDFLAGS='-s' MALLOC='libc' && \
mv src/redis-server /build/redis-server-${REDIS_VERSION}-linux-${ARCH}
CMD [ "/bin/sh" ]

View File

@ -0,0 +1,10 @@
FROM alpine:3.12
ARG REDIS_VERSION
RUN apk add --no-cache gcc musl-dev wget make pkgconfig linux-headers; \
mkdir /redis-server-binaries; \
wget https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz; \
tar xfz redis-${REDIS_VERSION}.tar.gz;
CMD [ "/bin/sh" ]

View File

@ -1,139 +1,16 @@
#!/bin/bash
set -e
REDIS_VERSION=6.0.5
REDIS_VERSION=7.0.15
REDIS_TARBALL="redis-${REDIS_VERSION}.tar.gz"
REDIS_URL="https://download.redis.io/releases/${REDIS_TARBALL}"
docker build --build-arg REDIS_VERSION=${REDIS_VERSION} -t redis-server-builder-amd64 -f ./build-server-amd64.docker .
docker build --build-arg REDIS_VERSION=${REDIS_VERSION} -t redis-server-builder-x86 -f ./build-server-x86.docker .
echo $ARCH
docker run -it --rm \
-v "$(pwd)/":/redis-server-binaries \
redis-server-builder-amd64 \
sh -c "cd redis-${REDIS_VERSION}; make CC='gcc -static' LDFLAGS='-s' MALLOC='libc'; cp src/redis-server /redis-server-binaries/redis-server-${REDIS_VERSION}"
function copy_openssl_and_remove_dylibs() {
# To make macOS builds more portable, we want to statically link OpenSSL,
# which is not straightforward. To force static compilation, we copy
# the openssl libraries and remove dylibs, forcing static linking
OPENSSL_HOME="${1}"
ARCH=$2
OPENSSL_HOME_COPY="${3}/${ARCH}"
echo "*** Copying openssl libraries for static linking"
cp -RL "${OPENSSL_HOME}" "${OPENSSL_HOME_COPY}"
rm -f "${OPENSSL_HOME_COPY}"/lib/*.dylib
}
if [ "$(dirname ${0})" != "." ]; then
echo "This script must be run from $(dirname ${0}). \`cd\` there and run again"
exit 1
fi
if ! [ -f "${REDIS_TARBALL}" ]; then
curl -o "${REDIS_TARBALL}" "${REDIS_URL}"
fi
all_linux=0
if command -pv docker buildx 2>/dev/null; then
for arch in amd64 arm64 386; do
builder_name="embedded-redis-builder-$RANDOM"
docker buildx create \
--name "$builder_name" \
--platform linux/amd64,linux/arm64,linux/386
docker buildx use "$builder_name"
echo "*** Building redis version ${REDIS_VERSION} for linux-${arch}"
set +e
docker buildx build \
"--platform=linux/${arch}" \
--build-arg "REDIS_VERSION=${REDIS_VERSION}" \
--build-arg "ARCH=${arch}" \
-t "redis-server-builder-${arch}" \
--load \
.
if [[ $? -ne 0 ]]; then
echo "*** ERROR: could not build for linux-${arch}"
continue
fi
set -e
docker buildx rm "$builder_name"
docker run -it --rm \
"--platform=linux/${arch}" \
-v "$(pwd)/":/mnt \
--user "$(id -u):$(id -g)" \
"redis-server-builder-${arch}" \
sh -c "cp /build/redis-server-${REDIS_VERSION}-linux-${arch} /mnt"
((all_linux+=1))
done
else
echo "*** WARNING: No docker command found or docker does not support buildx. Cannot build for linux."
fi
if [[ "${all_linux}" -lt 3 ]]; then
echo "*** WARNING: was not able to build for all linux arches; see above for errors"
fi
# To build for macOS, you must be running this script from a Mac. The script requires that openssl@1.1
# be installed via Homebrew.
#
# To build Redis binaries for both arm64e and x86_64, you'll need to run this script from an arm64e
# Mac with _two_ parallel installations of Homebrew (see
# https://stackoverflow.com/questions/64951024/how-can-i-run-two-isolated-installations-of-homebrew),
# and install openssl@1.1 with each.
if [[ "$(uname -s)" == "Darwin" ]]; then
tar zxf "${REDIS_TARBALL}"
cd "redis-${REDIS_VERSION}"
# temporary directory for openssl libraries for static linking.
# assumes standard Homebrew openssl install:
# - arm64e at /opt/homebrew/opt/openssl@1.1
# - x86_64 at /usr/local/opt/openssl@1.1
OPENSSL_TEMP=$(mktemp -d /tmp/embedded-redis-darwin-openssl.XXXXX)
# build for arm64 on apple silicon
if arch -arm64e true 2>/dev/null; then
if [ -d /opt/homebrew/opt/openssl@1.1 ]; then
copy_openssl_and_remove_dylibs /opt/homebrew/opt/openssl@1.1 arm64e "${OPENSSL_TEMP}"
echo "*** Building redis version ${REDIS_VERSION} for darwin-arm64e (apple silicon)"
make distclean
arch -arm64e make -j3 BUILD_TLS=yes OPENSSL_PREFIX="$OPENSSL_TEMP/arm64e"
mv src/redis-server "../redis-server-${REDIS_VERSION}-darwin-arm64"
else
echo "*** WARNING: openssl@1.1 not found for darwin-arm64e; skipping build"
fi
else
echo "*** WARNING: could not build for darwin-arm64e; you probably want to do this on an apple silicon device"
fi
# build for x86_64 if we're on apple silicon or a recent macos on x86_64
if arch -x86_64 true 2>/dev/null; then
if [ -d /usr/local/opt/openssl@1.1 ]; then
copy_openssl_and_remove_dylibs /usr/local/opt/openssl@1.1 x86_64 "${OPENSSL_TEMP}"
echo "*** Building redis version ${REDIS_VERSION} for darwin-x86_64"
make distclean
arch -x86_64 make -j3 BUILD_TLS=yes OPENSSL_PREFIX="$OPENSSL_TEMP/x86_64"
# x86_64 and amd64 are effectively synonymous; we use amd64 here to match the naming scheme used by Docker builds
mv src/redis-server "../redis-server-${REDIS_VERSION}-darwin-amd64"
else
echo "*** WARNING: openssl@1.1 not found for darwin-x86_64; skipping build"
fi
else
echo "*** WARNING: you are on a version of macos that lacks /usr/bin/arch, you probably do not want this"
exit 1
fi
cd ..
else
echo "*** WARNING: Cannot build for macos/darwin on a $(uname -s) host"
fi
ls -l redis-server-*
echo "*** Moving built binaries to ../resources; you need to handle the rest yourself"
mv redis-server-* ../resources/
docker run -it --rm \
-v "$(pwd)/":/redis-server-binaries \
redis-server-builder-x86 \
sh -c "cd redis-${REDIS_VERSION}; make CC='gcc -static' CFLAGS='-m32' LDFLAGS='-m32 -s' MALLOC='libc'; cp src/redis-server /redis-server-binaries/redis-server-${REDIS_VERSION}-32"

View File

@ -0,0 +1,10 @@
FROM i386/alpine:3.12
ARG REDIS_VERSION
RUN apk add --no-cache gcc musl-dev wget make pkgconfig linux-headers; \
mkdir /redis-server-binaries; \
wget https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz; \
tar xfz redis-${REDIS_VERSION}.tar.gz;
CMD [ "/bin/sh" ]

View File

@ -16,17 +16,11 @@ abstract class AbstractRedisInstance implements Redis {
private volatile boolean active = false;
private Process redisProcess;
private final int port;
private final int tlsPort;
private ExecutorService executor;
protected AbstractRedisInstance(int port, int tlsPort) {
this.port = port;
this.tlsPort = tlsPort;
}
protected AbstractRedisInstance(int port) {
this(port, 0);
this.port = port;
}
public boolean isActive() {
@ -63,20 +57,20 @@ abstract class AbstractRedisInstance implements Redis {
private void awaitRedisServerReady() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(redisProcess.getInputStream()));
try {
StringBuilder outputStringBuilder = new StringBuilder();
StringBuffer outputStringBuffer = new StringBuffer();
String outputLine;
do {
outputLine = reader.readLine();
if (outputLine == null) {
// Something is wrong. Stream ended before server was activated.
throw new EmbeddedRedisException("Redis server failed to become ready. Check logs for details. Redis process log: " + outputStringBuilder.toString());
//Something goes wrong. Stream is ended before server was activated.
throw new RuntimeException("Can't start redis server. Check logs for details. Redis process log: " + outputStringBuffer.toString());
} else {
outputStringBuilder.append("\n");
outputStringBuilder.append(outputLine);
outputStringBuffer.append("\n");
outputStringBuffer.append(outputLine);
}
} while (!outputLine.matches(redisReadyPattern()));
} finally {
IOUtils.closeQuietly(reader, null);
IOUtils.closeQuietly(reader);
}
}
@ -109,11 +103,7 @@ abstract class AbstractRedisInstance implements Redis {
}
public List<Integer> ports() {
return port > 0 ? Collections.singletonList(port) : Collections.emptyList();
}
public List<Integer> tlsPorts() {
return tlsPort > 0 ? Collections.singletonList(tlsPort) : Collections.emptyList();
return Arrays.asList(port);
}
private static class PrintReaderRunnable implements Runnable {
@ -127,7 +117,7 @@ abstract class AbstractRedisInstance implements Redis {
try {
readLines();
} finally {
IOUtils.closeQuietly(reader, null);
IOUtils.closeQuietly(reader);
}
}

View File

@ -12,6 +12,4 @@ public interface Redis {
void stop() throws EmbeddedRedisException;
List<Integer> ports();
List<Integer> tlsPorts();
}

View File

@ -59,14 +59,6 @@ public class RedisCluster implements Redis {
return ports;
}
@Override
public List<Integer> tlsPorts() {
List<Integer> ports = new ArrayList<Integer>();
ports.addAll(sentinelTlsPorts());
ports.addAll(serverTlsPorts());
return ports;
}
public List<Redis> sentinels() {
return Lists.newLinkedList(sentinels);
}
@ -79,14 +71,6 @@ public class RedisCluster implements Redis {
return ports;
}
public List<Integer> sentinelTlsPorts() {
List<Integer> ports = new ArrayList<Integer>();
for(Redis redis : sentinels) {
ports.addAll(redis.tlsPorts());
}
return ports;
}
public List<Redis> servers() {
return Lists.newLinkedList(servers);
}
@ -99,14 +83,6 @@ public class RedisCluster implements Redis {
return ports;
}
public List<Integer> serverTlsPorts() {
List<Integer> ports = new ArrayList<Integer>();
for(Redis redis : servers) {
ports.addAll(redis.tlsPorts());
}
return ports;
}
public static RedisClusterBuilder builder() {
return new RedisClusterBuilder();
}

View File

@ -12,26 +12,23 @@ import java.io.IOException;
import java.util.Map;
public class RedisExecProvider {
private final Map<OsArchitecture, String> executables = Maps.newHashMap();
public static final String redisVersion = "7.0.15";
public static RedisExecProvider defaultProvider() {
return new RedisExecProvider();
}
private RedisExecProvider() {
initExecutables();
}
private void initExecutables() {
executables.put(OsArchitecture.UNIX_x86, "redis-server-" + redisVersion + "-linux-386");
executables.put(OsArchitecture.UNIX_x86_64, "redis-server-" + redisVersion + "-linux-amd64");
executables.put(OsArchitecture.UNIX_arm64, "redis-server-" + redisVersion + "-linux-arm64");
executables.put(OsArchitecture.UNIX_x86, "redis-server-6.0.5-32");
executables.put(OsArchitecture.UNIX_x86_64, "redis-server-6.0.5");
executables.put(OsArchitecture.MAC_OS_X_x86_64, "redis-server-" + redisVersion + "-darwin-amd64");
executables.put(OsArchitecture.MAC_OS_X_arm64, "redis-server-" + redisVersion + "-darwin-arm64");
executables.put(OsArchitecture.MAC_OS_X_x86, "redis-server-6.0.5.app");
executables.put(OsArchitecture.MAC_OS_X_x86_64, "redis-server-6.0.5.app");
}
public RedisExecProvider override(OS os, String executable) {
@ -47,7 +44,7 @@ public class RedisExecProvider {
executables.put(new OsArchitecture(os, arch), executable);
return this;
}
public File get() throws IOException {
OsArchitecture osArch = OsArchitecture.detect();

View File

@ -7,7 +7,6 @@ import redis.embedded.exceptions.RedisBuildingException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@ -140,7 +139,7 @@ public class RedisSentinelBuilder {
File redisConfigFile = File.createTempFile(resolveConfigName(), ".conf");
redisConfigFile.deleteOnExit();
Files.asCharSink(redisConfigFile, StandardCharsets.UTF_8).write(configString);
Files.write(configString, redisConfigFile, Charset.forName("UTF-8"));
sentinelConf = redisConfigFile.getAbsolutePath();
}

View File

@ -19,11 +19,6 @@ public class RedisServer extends AbstractRedisInstance {
this.args = builder().port(port).build().args;
}
public RedisServer(int port, int tlsPort) {
super(port, tlsPort);
this.args = builder().port(port).tlsPort(tlsPort).build().args;
}
public RedisServer(File executable, int port) {
super(port);
this.args = Arrays.asList(
@ -40,9 +35,9 @@ public class RedisServer extends AbstractRedisInstance {
);
}
RedisServer(List<String> args, int port, int tlsPort) {
super(port, tlsPort);
this.args = new ArrayList<>(args);
RedisServer(List<String> args, int port) {
super(port);
this.args = new ArrayList<String>(args);
}
public static RedisServerBuilder builder() {

View File

@ -8,7 +8,6 @@ import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@ -20,7 +19,6 @@ public class RedisServerBuilder {
private RedisExecProvider redisExecProvider = RedisExecProvider.defaultProvider();
private String bind="127.0.0.1";
private int port = 6379;
private int tlsPort = 0;
private InetSocketAddress slaveOf;
private String redisConf;
@ -41,11 +39,6 @@ public class RedisServerBuilder {
return this;
}
public RedisServerBuilder tlsPort(int tlsPort) {
this.tlsPort = tlsPort;
return this;
}
public RedisServerBuilder slaveOf(String hostname, int port) {
this.slaveOf = new InetSocketAddress(hostname, port);
return this;
@ -82,7 +75,7 @@ public class RedisServerBuilder {
setting("bind "+bind);
tryResolveConfAndExec();
List<String> args = buildCommandArgs();
return new RedisServer(args, port, tlsPort);
return new RedisServer(args, port);
}
public void reset() {
@ -104,7 +97,7 @@ public class RedisServerBuilder {
if (redisConf == null && redisConfigBuilder != null) {
File redisConfigFile = File.createTempFile(resolveConfigName(), ".conf");
redisConfigFile.deleteOnExit();
Files.asCharSink(redisConfigFile, StandardCharsets.UTF_8).write(redisConfigBuilder.toString());
Files.write(redisConfigBuilder.toString(), redisConfigFile, Charset.forName("UTF-8"));
redisConf = redisConfigFile.getAbsolutePath();
}
@ -130,11 +123,6 @@ public class RedisServerBuilder {
args.add("--port");
args.add(Integer.toString(port));
if (tlsPort > 0) {
args.add("--tls-port");
args.add(Integer.toString(tlsPort));
}
if (slaveOf != null) {
args.add("--slaveof");
args.add(slaveOf.getHostName());

View File

@ -2,6 +2,5 @@ package redis.embedded.util;
public enum Architecture {
x86,
x86_64,
arm64
x86_64
}

View File

@ -10,20 +10,14 @@ import java.io.IOException;
public class JarUtil {
public static File extractExecutableFromJar(String executable) throws IOException {
File command = extractFileFromJar(executable);
File tmpDir = Files.createTempDir();
tmpDir.deleteOnExit();
File command = new File(tmpDir, executable);
FileUtils.copyURLToFile(Resources.getResource(executable), command);
command.deleteOnExit();
command.setExecutable(true);
return command;
}
public static File extractFileFromJar(String path) throws IOException {
File tmpDir = Files.createTempDir();
tmpDir.deleteOnExit();
File file = new File(tmpDir, path);
FileUtils.copyURLToFile(Resources.getResource(path), file);
file.deleteOnExit();
return file;
}
}

View File

@ -47,46 +47,58 @@ public class OSDetector {
}
private static Architecture getUnixArchitecture() {
BufferedReader input = null;
try {
String line;
Process proc = Runtime.getRuntime().exec("uname -m");
try (BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
String machine = input.readLine();
switch (machine) {
case "aarch64":
return Architecture.arm64;
case "x86_64":
input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.length() > 0) {
if (line.contains("64")) {
return Architecture.x86_64;
default:
throw new OsDetectionException("unsupported architecture: " + machine);
}
}
}
} catch (Exception e) {
if (e instanceof OsDetectionException) {
throw (OsDetectionException)e;
}
throw new OsDetectionException(e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception ignored) {
// ignore
}
}
return Architecture.x86;
}
private static Architecture getMacOSXArchitecture() {
BufferedReader input = null;
try {
Process proc = Runtime.getRuntime().exec("uname -m");
try (BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
String machine = input.readLine();
switch (machine) {
case "arm64":
return Architecture.arm64;
case "x86_64":
String line;
Process proc = Runtime.getRuntime().exec("sysctl hw");
input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.length() > 0) {
if ((line.contains("cpu64bit_capable")) && (line.trim().endsWith("1"))) {
return Architecture.x86_64;
default:
throw new OsDetectionException("unsupported architecture: " + machine);
}
}
}
} catch (Exception e) {
if (e instanceof OsDetectionException) {
throw (OsDetectionException)e;
}
throw new OsDetectionException(e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception ignored) {
// ignore
}
}
return Architecture.x86;
}
}

View File

@ -6,10 +6,9 @@ public class OsArchitecture {
public static final OsArchitecture UNIX_x86 = new OsArchitecture(OS.UNIX, Architecture.x86);
public static final OsArchitecture UNIX_x86_64 = new OsArchitecture(OS.UNIX, Architecture.x86_64);
public static final OsArchitecture UNIX_arm64 = new OsArchitecture(OS.UNIX, Architecture.arm64);
public static final OsArchitecture MAC_OS_X_x86 = new OsArchitecture(OS.MAC_OS_X, Architecture.x86);
public static final OsArchitecture MAC_OS_X_x86_64 = new OsArchitecture(OS.MAC_OS_X, Architecture.x86_64);
public static final OsArchitecture MAC_OS_X_arm64 = new OsArchitecture(OS.MAC_OS_X, Architecture.arm64);
private final OS os;
private final Architecture arch;

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,3 +0,0 @@
#!/bin/bash
rm -rf ./tests

View File

@ -1,7 +0,0 @@
#!/bin/bash
OUTPUT_DIR="$1"
if [ ! -f "$OUTPUT_DIR/redis.key" -o ! -f "$OUTPUT_DIR/redis.crt" -o ! -f "$OUTPUT_DIR/ca.crt" ]; then
./gen-test-certs.sh
fi

View File

@ -1,73 +0,0 @@
#!/bin/bash
# From https://github.com/redis/redis/blob/4930d19e70c391750479951022e207e19111eb55/redis/util/gen-test-certs.sh, under the license:
#
# Copyright (c) 2006-2020, Salvatore Sanfilippo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# * Neither the name of Redis nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Generate some test certificates which are used by the regression test suite:
#
# tests/tls/ca.{crt,key} Self signed CA certificate.
# tests/tls/redis.{crt,key} A certificate with no key usage/policy restrictions.
# tests/tls/client.{crt,key} A certificate restricted for SSL client usage.
# tests/tls/server.{crt,key} A certificate restricted fro SSL server usage.
# tests/tls/redis.dh DH Params file.
generate_cert() {
local name=$1
local cn="$2"
local opts="$3"
local keyfile=tests/tls/${name}.key
local certfile=tests/tls/${name}.crt
[ -f $keyfile ] || openssl genrsa -out $keyfile 2048
openssl req \
-new -sha256 \
-subj "/O=Redis Test/CN=$cn" \
-key $keyfile | \
openssl x509 \
-req -sha256 \
-CA tests/tls/ca.crt \
-CAkey tests/tls/ca.key \
-CAserial tests/tls/ca.txt \
-CAcreateserial \
-days 365 \
$opts \
-out $certfile
}
mkdir -p tests/tls
[ -f tests/tls/ca.key ] || openssl genrsa -out tests/tls/ca.key 4096
openssl req \
-x509 -new -nodes -sha256 \
-key tests/tls/ca.key \
-days 3650 \
-subj '/O=Redis Test/CN=Certificate Authority' \
-out tests/tls/ca.crt
cat > tests/tls/openssl.cnf <<_END_
[ server_cert ]
keyUsage = digitalSignature, keyEncipherment
nsCertType = server
[ client_cert ]
keyUsage = digitalSignature, keyEncipherment
nsCertType = client
_END_
generate_cert server "Server-only" "-extfile tests/tls/openssl.cnf -extensions server_cert"
generate_cert client "Client-only" "-extfile tests/tls/openssl.cnf -extensions client_cert"
generate_cert redis "Generic-cert"
[ -f tests/tls/redis.dh ] || openssl dhparam -out tests/tls/redis.dh 2048

View File

@ -1,15 +1,12 @@
package redis.embedded;
import com.google.common.collect.Sets;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.embedded.util.JedisUtil;
import java.io.Closeable;
import java.net.Inet4Address;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
@ -20,9 +17,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class RedisClusterTest {
private final RedisSentinelBuilder sentinelBuilder = RedisSentinel.builder();
private String bindAddress;
private Redis sentinel1;
private Redis sentinel2;
private Redis master1;
@ -36,13 +30,6 @@ public class RedisClusterTest {
sentinel2 = mock(Redis.class);
master1 = mock(Redis.class);
master2 = mock(Redis.class);
// Jedis translates localhost to getLocalHost().getHostAddress() (see Jedis HostAndPort#getLocalHostQuietly),
// which can vary from 127.0.0.1 (most notably, Debian/Ubuntu return 127.0.1.1)
if (bindAddress == null) {
bindAddress = Inet4Address.getLocalHost().getHostAddress();
sentinelBuilder.bind(bindAddress);
}
}
@ -110,7 +97,7 @@ public class RedisClusterTest {
@Test
public void testSimpleOperationsAfterRunWithSingleMasterNoSlavesCluster() throws Exception {
//given
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelCount(1).replicationGroup("ourmaster", 0).build();
final RedisCluster cluster = RedisCluster.builder().sentinelCount(1).replicationGroup("ourmaster", 0).build();
cluster.start();
//when
@ -120,7 +107,8 @@ public class RedisClusterTest {
pool = new JedisSentinelPool("ourmaster", Sets.newHashSet("localhost:26379"));
jedis = testPool(pool);
} finally {
closeQuietly(jedis, pool);
if (jedis != null)
pool.returnResource(jedis);
cluster.stop();
}
}
@ -128,7 +116,7 @@ public class RedisClusterTest {
@Test
public void testSimpleOperationsAfterRunWithSingleMasterAndOneSlave() throws Exception {
//given
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelCount(1).replicationGroup("ourmaster", 1).build();
final RedisCluster cluster = RedisCluster.builder().sentinelCount(1).replicationGroup("ourmaster", 1).build();
cluster.start();
//when
@ -138,7 +126,8 @@ public class RedisClusterTest {
pool = new JedisSentinelPool("ourmaster", Sets.newHashSet("localhost:26379"));
jedis = testPool(pool);
} finally {
closeQuietly(jedis, pool);
if (jedis != null)
pool.returnResource(jedis);
cluster.stop();
}
}
@ -146,7 +135,7 @@ public class RedisClusterTest {
@Test
public void testSimpleOperationsAfterRunWithSingleMasterMultipleSlaves() throws Exception {
//given
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelCount(1).replicationGroup("ourmaster", 2).build();
final RedisCluster cluster = RedisCluster.builder().sentinelCount(1).replicationGroup("ourmaster", 2).build();
cluster.start();
//when
@ -156,7 +145,8 @@ public class RedisClusterTest {
pool = new JedisSentinelPool("ourmaster", Sets.newHashSet("localhost:26379"));
jedis = testPool(pool);
} finally {
closeQuietly(jedis, pool);
if (jedis != null)
pool.returnResource(jedis);
cluster.stop();
}
}
@ -164,7 +154,7 @@ public class RedisClusterTest {
@Test
public void testSimpleOperationsAfterRunWithTwoSentinelsSingleMasterMultipleSlaves() throws Exception {
//given
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelCount(2).replicationGroup("ourmaster", 2).build();
final RedisCluster cluster = RedisCluster.builder().sentinelCount(2).replicationGroup("ourmaster", 2).build();
cluster.start();
//when
@ -174,7 +164,8 @@ public class RedisClusterTest {
pool = new JedisSentinelPool("ourmaster", Sets.newHashSet("localhost:26379", "localhost:26380"));
jedis = testPool(pool);
} finally {
closeQuietly(jedis, pool);
if (jedis != null)
pool.returnResource(jedis);
cluster.stop();
}
}
@ -183,7 +174,7 @@ public class RedisClusterTest {
public void testSimpleOperationsAfterRunWithTwoPredefinedSentinelsSingleMasterMultipleSlaves() throws Exception {
//given
List<Integer> sentinelPorts = Arrays.asList(26381, 26382);
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelPorts(sentinelPorts).replicationGroup("ourmaster", 2).build();
final RedisCluster cluster = RedisCluster.builder().sentinelPorts(sentinelPorts).replicationGroup("ourmaster", 2).build();
cluster.start();
final Set<String> sentinelHosts = JedisUtil.portsToJedisHosts(sentinelPorts);
@ -194,7 +185,8 @@ public class RedisClusterTest {
pool = new JedisSentinelPool("ourmaster", sentinelHosts);
jedis = testPool(pool);
} finally {
closeQuietly(jedis, pool);
if (jedis != null)
pool.returnResource(jedis);
cluster.stop();
}
}
@ -205,7 +197,7 @@ public class RedisClusterTest {
final String master1 = "master1";
final String master2 = "master2";
final String master3 = "master3";
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).sentinelCount(3).quorumSize(2)
final RedisCluster cluster = RedisCluster.builder().sentinelCount(3).quorumSize(2)
.replicationGroup(master1, 1)
.replicationGroup(master2, 1)
.replicationGroup(master3, 1)
@ -227,7 +219,12 @@ public class RedisClusterTest {
jedis2 = testPool(pool2);
jedis3 = testPool(pool3);
} finally {
closeQuietly(jedis1, pool1, jedis2, pool2, jedis3, pool3);
if (jedis1 != null)
pool1.returnResource(jedis1);
if (jedis2 != null)
pool2.returnResource(jedis2);
if (jedis3 != null)
pool3.returnResource(jedis3);
cluster.stop();
}
}
@ -238,7 +235,7 @@ public class RedisClusterTest {
final String master1 = "master1";
final String master2 = "master2";
final String master3 = "master3";
final RedisCluster cluster = RedisCluster.builder().withSentinelBuilder(sentinelBuilder).ephemeral().sentinelCount(3).quorumSize(2)
final RedisCluster cluster = RedisCluster.builder().ephemeral().sentinelCount(3).quorumSize(2)
.replicationGroup(master1, 1)
.replicationGroup(master2, 1)
.replicationGroup(master3, 1)
@ -261,7 +258,12 @@ public class RedisClusterTest {
jedis2 = testPool(pool2);
jedis3 = testPool(pool3);
} finally {
closeQuietly(jedis1, pool1, jedis2, pool2, jedis3, pool3);
if (jedis1 != null)
pool1.returnResource(jedis1);
if (jedis2 != null)
pool2.returnResource(jedis2);
if (jedis3 != null)
pool3.returnResource(jedis3);
cluster.stop();
}
}
@ -277,11 +279,4 @@ public class RedisClusterTest {
assertEquals(null, jedis.mget("xyz").get(0));
return jedis;
}
private void closeQuietly(Closeable... closeables) {
for (Closeable closeable : closeables) {
IOUtils.closeQuietly(closeable, null);
}
}
}
}

View File

@ -1,7 +1,6 @@
package redis.embedded;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
@ -9,30 +8,18 @@ import redis.clients.jedis.JedisSentinelPool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class RedisSentinelTest {
private String bindAddress;
private RedisSentinel sentinel;
private RedisServer server;
@Before
public void setup() throws Exception {
// Jedis translates localhost to getLocalHost().getHostAddress() (see Jedis HostAndPort#getLocalHostQuietly),
// which can vary from 127.0.0.1 (most notably, Debian/Ubuntu return 127.0.1.1)
if (bindAddress == null) {
bindAddress = Inet4Address.getLocalHost().getHostAddress();
}
}
@Test(timeout = 3000L)
public void testSimpleRun() throws Exception {
server = new RedisServer();
sentinel = RedisSentinel.builder().bind(bindAddress).build();
sentinel = RedisSentinel.builder().build();
sentinel.start();
server.start();
TimeUnit.SECONDS.sleep(1);
@ -42,7 +29,7 @@ public class RedisSentinelTest {
@Test
public void shouldAllowSubsequentRuns() throws Exception {
sentinel = RedisSentinel.builder().bind(bindAddress).build();
sentinel = RedisSentinel.builder().build();
sentinel.start();
sentinel.stop();
@ -57,7 +44,7 @@ public class RedisSentinelTest {
public void testSimpleOperationsAfterRun() throws Exception {
//given
server = new RedisServer();
sentinel = RedisSentinel.builder().bind(bindAddress).build();
sentinel = RedisSentinel.builder().build();
server.start();
sentinel.start();
TimeUnit.SECONDS.sleep(1);
@ -112,4 +99,4 @@ public class RedisSentinelTest {
assertNotNull(outputLine);
} while (!outputLine.matches(readyPattern));
}
}
}

View File

@ -97,11 +97,9 @@ public class RedisServerTest {
@Test
public void shouldOverrideDefaultExecutable() throws Exception {
RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
.override(OS.UNIX, Architecture.x86, Resources.getResource("redis-server-" + RedisExecProvider.redisVersion + "-linux-386").getFile())
.override(OS.UNIX, Architecture.x86_64, Resources.getResource("redis-server-" + RedisExecProvider.redisVersion + "-linux-amd64").getFile())
.override(OS.UNIX, Architecture.arm64, Resources.getResource("redis-server-" + RedisExecProvider.redisVersion + "-linux-arm64").getFile())
.override(OS.MAC_OS_X, Architecture.x86_64, Resources.getResource("redis-server-" + RedisExecProvider.redisVersion + "-darwin-amd64").getFile())
.override(OS.MAC_OS_X, Architecture.arm64, Resources.getResource("redis-server-" + RedisExecProvider.redisVersion + "-darwin-arm64").getFile());
.override(OS.UNIX, Architecture.x86, Resources.getResource("redis-server-6.0.5-32").getFile())
.override(OS.UNIX, Architecture.x86_64, Resources.getResource("redis-server-6.0.5").getFile())
.override(OS.MAC_OS_X, Resources.getResource("redis-server-6.0.5").getFile());
redisServer = new RedisServerBuilder()
.redisExecProvider(customProvider)
@ -112,6 +110,8 @@ public class RedisServerTest {
public void shouldFailWhenBadExecutableGiven() throws Exception {
RedisExecProvider buggyProvider = RedisExecProvider.defaultProvider()
.override(OS.UNIX, "some")
.override(OS.WINDOWS, Architecture.x86, "some")
.override(OS.WINDOWS, Architecture.x86_64, "some")
.override(OS.MAC_OS_X, "some");
redisServer = new RedisServerBuilder()

View File

@ -1,101 +0,0 @@
package redis.embedded;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.embedded.util.JarUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class RedisTlsTest {
private RedisServer redisServer;
private static File certFile;
private static File keyFile;
private static File caCertFile;
@BeforeClass
public static void setupClass() throws Exception {
certFile = getFile("redis.crt");
keyFile = getFile("redis.key");
caCertFile = getFile("ca.crt");
File trustStore = File.createTempFile("embedded-redis-test-truststore", ".jks");
trustStore.deleteOnExit();
Certificate cert;
try (FileInputStream certInput = new FileInputStream(certFile)) {
cert = CertificateFactory.getInstance("X.509").generateCertificate(certInput);
}
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(null, null);
keyStore.setCertificateEntry("testCaCert", cert);
try (FileOutputStream out = new FileOutputStream(trustStore)) {
keyStore.store(out, new char[0]);
}
System.setProperty("javax.net.ssl.trustStore", trustStore.getAbsolutePath());
System.setProperty("javax.net.ssl.trustStoreType", "jks");
}
@Before
public void setup() throws Exception {
redisServer = RedisServer.builder()
.port(0) // disable non-tls
.tlsPort(6380)
.setting("tls-cert-file " + certFile.getAbsolutePath())
.setting("tls-key-file " + keyFile.getAbsolutePath())
.setting("tls-ca-cert-file " + caCertFile.getAbsolutePath())
.setting("tls-auth-clients no") // disable mTLS, for simplicity
.build();
}
@Test(timeout = 1500L)
public void testSimpleRun() throws Exception {
redisServer.start();
Thread.sleep(1000L);
redisServer.stop();
}
@Test
public void testSimpleOperationsAfterRun() {
redisServer.start();
try (JedisPool pool = new JedisPool("localhost", redisServer.tlsPorts().get(0), true);
Jedis jedis = pool.getResource()) {
jedis.mset("abc", "1", "def", "2");
assertEquals("1", jedis.mget("abc").get(0));
assertEquals("2", jedis.mget("def").get(0));
assertNull(jedis.mget("xyz").get(0));
} finally {
redisServer.stop();
}
}
private static File getFile(String path) throws IOException {
return fileExists(path) ?
new File(path) :
JarUtil.extractFileFromJar(path);
}
private static boolean fileExists(String path) {
return new File(path).exists();
}
}