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
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import com.github.jasync.sql.db.util.NettyUtils
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.PooledByteBufAllocator
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.util.CharsetUtil
import java.nio.charset.Charset
import java.time.Duration
import java.util.concurrent.Executor
import java.util.function.Supplier
import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

/**
*
Expand All @@ -36,6 +40,7 @@ import java.util.function.Supplier
* @param executionContext the thread pool to run the callbacks on
* @param eventLoopGroup the netty event loop group - use this to select native/nio transport.
* @param currentSchema optional database schema - postgresql only.
* @param socketPath path to unix domain socket file (on the local machine)
*
*/

Expand All @@ -55,8 +60,16 @@ data class Configuration @JvmOverloads constructor(
val interceptors: List<Supplier<QueryInterceptor>> = emptyList(),
val eventLoopGroup: EventLoopGroup = NettyUtils.DefaultEventLoopGroup,
val executionContext: Executor = ExecutorServiceUtils.CommonPool,
val currentSchema: String? = null
)
val currentSchema: String? = null,
val socketPath: String? = null
) {
init {
if (socketPath != null && eventLoopGroup is NioEventLoopGroup) {
logger.warn { "socketPath configured but not supported with NioEventLoopGroup - will ignore configuration. " +
"Please change eventLoopGroup configuration." }
}
}
}

fun Configuration.toDebugString(): String {
return this.copy(password = "****").toString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import kotlinx.coroutines.Dispatchers
* @param interceptors optional delegates to call on query execution
* @param maxConnectionTtl number of milliseconds an object in this pool should be kept alive, negative values mean no aging out
* @param currentSchema optional search_path for the database
* @param socketPath path to unix domain socket file (on the local machine)
*
*/
data class ConnectionPoolConfiguration @JvmOverloads constructor(
Expand All @@ -74,7 +75,8 @@ data class ConnectionPoolConfiguration @JvmOverloads constructor(
val applicationName: String? = null,
val interceptors: List<Supplier<QueryInterceptor>> = emptyList(),
val maxConnectionTtl: Long? = null,
val currentSchema: String? = null
val currentSchema: String? = null,
val socketPath: String? = null
) {
init {
require(port > 0) { "port should be positive: $port" }
Expand Down Expand Up @@ -105,7 +107,8 @@ data class ConnectionPoolConfiguration @JvmOverloads constructor(
interceptors = interceptors,
executionContext = executionContext,
eventLoopGroup = eventLoopGroup,
currentSchema = currentSchema
currentSchema = currentSchema,
socketPath = socketPath
)

val poolConfiguration = PoolConfiguration(
Expand All @@ -121,7 +124,7 @@ data class ConnectionPoolConfiguration @JvmOverloads constructor(
)

override fun toString() = """ConnectionPoolConfiguration(host=$host, port=REDACTED,
|database=$database,username=REDACTED, password=REDACTED,
|database=$database,username=REDACTED, password=REDACTED, socketPath=REDACTED,
|currentSchema=$currentSchema
|maxActiveConnections=$maxActiveConnections,
|maxIdleTime=$maxIdleTime,
Expand All @@ -135,7 +138,9 @@ data class ConnectionPoolConfiguration @JvmOverloads constructor(
|maximumMessageSize=$maximumMessageSize,
|allocator=$allocator,
|applicationName=$applicationName,
|interceptors=$interceptors, maxConnectionTtl=$maxConnectionTtl)""".trimMargin()
|interceptors=$interceptors,
|maxConnectionTtl=$maxConnectionTtl
|)""".trimMargin()
}

/**
Expand Down Expand Up @@ -166,7 +171,8 @@ data class ConnectionPoolConfigurationBuilder @JvmOverloads constructor(
var applicationName: String? = null,
var interceptors: MutableList<Supplier<QueryInterceptor>> = mutableListOf<Supplier<QueryInterceptor>>(),
var maxConnectionTtl: Long? = null,
var currentSchema: String? = null
var currentSchema: String? = null,
var socketPath: String? = null
) {
fun build(): ConnectionPoolConfiguration = ConnectionPoolConfiguration(
host = host,
Expand All @@ -190,6 +196,7 @@ data class ConnectionPoolConfigurationBuilder @JvmOverloads constructor(
allocator = allocator,
applicationName = applicationName,
interceptors = interceptors,
currentSchema = currentSchema
currentSchema = currentSchema,
socketPath = socketPath
)
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
package com.github.jasync.sql.db.util

import com.github.jasync.sql.db.Configuration
import com.github.jasync.sql.db.SSLConfiguration
import io.netty.channel.Channel
import io.netty.channel.EventLoopGroup
import io.netty.channel.epoll.Epoll
import io.netty.channel.epoll.EpollDomainSocketChannel
import io.netty.channel.epoll.EpollEventLoopGroup
import io.netty.channel.epoll.EpollSocketChannel
import io.netty.channel.kqueue.KQueue
import io.netty.channel.kqueue.KQueueDomainSocketChannel
import io.netty.channel.kqueue.KQueueEventLoopGroup
import io.netty.channel.kqueue.KQueueSocketChannel
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.channel.unix.DomainSocketAddress
import io.netty.handler.ssl.SslContext
import io.netty.handler.ssl.SslContextBuilder
import io.netty.handler.ssl.util.InsecureTrustManagerFactory
import io.netty.util.internal.logging.InternalLoggerFactory
import io.netty.util.internal.logging.Slf4JLoggerFactory
import java.io.FileInputStream
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.security.KeyStore
import javax.net.ssl.SSLEngine
import javax.net.ssl.TrustManagerFactory
Expand All @@ -43,10 +49,41 @@ object NettyUtils {
}
}

fun getSocketChannelClass(eventLoopGroup: EventLoopGroup): Class<out SocketChannel> = when {
tryOrFalse { eventLoopGroup is EpollEventLoopGroup } -> EpollSocketChannel::class.java
tryOrFalse { eventLoopGroup is KQueueEventLoopGroup } -> KQueueSocketChannel::class.java
else -> NioSocketChannel::class.java
@Deprecated("use getSocketChannelClassAndSocketAddress()", ReplaceWith("getSocketChannelClassAndSocketAddress"))
fun getSocketChannelClass(eventLoopGroup: EventLoopGroup, useDomainSocket: Boolean = false): Class<out Channel> =
when {
tryOrFalse { eventLoopGroup is EpollEventLoopGroup } -> if (useDomainSocket) EpollDomainSocketChannel::class.java else EpollSocketChannel::class.java
tryOrFalse { eventLoopGroup is KQueueEventLoopGroup } -> if (useDomainSocket) KQueueDomainSocketChannel::class.java else KQueueSocketChannel::class.java
else -> {
if (useDomainSocket) {
logger.info { "domain socket is not supported by NioEventLoopGroup, useDomainSocket flag is skipped" }
}
NioSocketChannel::class.java
}
}

fun getSocketChannelClassAndSocketAddress(
eventLoopGroup: EventLoopGroup,
configuration: Configuration
): SocketChannelClassAndSocketAddress {
var useDomainSocket = configuration.socketPath != null
val socketChannelClass = when {
tryOrFalse { eventLoopGroup is EpollEventLoopGroup } -> if (useDomainSocket) EpollDomainSocketChannel::class.java else EpollSocketChannel::class.java
tryOrFalse { eventLoopGroup is KQueueEventLoopGroup } -> if (useDomainSocket) KQueueDomainSocketChannel::class.java else KQueueSocketChannel::class.java
else -> {
if (useDomainSocket) {
logger.info { "domain socket is not supported by NioEventLoopGroup, configuration for socketPath is ignored" }
useDomainSocket = false
}
NioSocketChannel::class.java
}
}
val socketAddress = if (useDomainSocket) {
DomainSocketAddress(configuration.socketPath)
} else {
InetSocketAddress(configuration.host, configuration.port)
}
return SocketChannelClassAndSocketAddress(socketChannelClass, socketAddress)
}

fun createSslContext(sslConfiguration: SSLConfiguration): SslContext {
Expand Down Expand Up @@ -88,4 +125,6 @@ object NettyUtils {
false
}
}

data class SocketChannelClassAndSocketAddress(val socketChannelClass: Class<out Channel>, val socketAddress: SocketAddress)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.github.jasync.sql.db.util

import com.github.jasync.sql.db.Configuration
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

Expand All @@ -16,4 +17,14 @@ class NettyUtilsTest {
assertThat(NettyUtils.getSocketChannelClass(NettyUtils.DefaultEventLoopGroup).simpleName)
.isEqualTo("NioSocketChannel")
}

@Test
fun getSocketChannelClassAndSocketAddress() {
val socketChannelAddress = NettyUtils.getSocketChannelClassAndSocketAddress(
NettyUtils.DefaultEventLoopGroup,
Configuration(username = "root", socketPath = "/tmp/mysql.sock")
)
assertThat(socketChannelAddress.socketChannelClass.simpleName).isEqualTo("NioSocketChannel")
assertThat(socketChannelAddress.socketAddress::class.simpleName).isEqualTo("InetSocketAddress")
}
}
1 change: 1 addition & 0 deletions mysql-async/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies {
compile("org.slf4j:slf4j-api:$SL4J_VERSION")
compile("io.netty:netty-transport:$NETTY_VERSION")
compile("io.netty:netty-handler:$NETTY_VERSION")
testImplementation("io.netty:netty-transport-native-epoll:$NETTY_VERSION:linux-x86_64")
compile("io.github.microutils:kotlin-logging:$KOTLIN_LOGGING_VERSION")
testImplementation("junit:junit:$JUNIT_VERSION")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$KOTLIN_VERSION")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.CodecException
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
Expand Down Expand Up @@ -81,7 +80,11 @@ class MySQLConnectionHandler(
private var isPreparedStatement: Boolean? = null

fun connect(): CompletableFuture<MySQLConnectionHandler> {
this.bootstrap.channel(NettyUtils.getSocketChannelClass(this.group))
val socketChannelAddress = NettyUtils.getSocketChannelClassAndSocketAddress(
this.group,
configuration
)
this.bootstrap.channel(socketChannelAddress.socketChannelClass)
this.bootstrap.handler(object : ChannelInitializer<Channel>() {

override fun initChannel(channel: Channel) {
Expand All @@ -98,8 +101,7 @@ class MySQLConnectionHandler(
this.bootstrap.option(ChannelOption.ALLOCATOR, LittleEndianByteBufAllocator.INSTANCE)
this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.configuration.connectionTimeout)

val channelFuture: ChannelFuture =
this.bootstrap.connect(InetSocketAddress(configuration.host, configuration.port))
val channelFuture: ChannelFuture = this.bootstrap.connect(socketChannelAddress.socketAddress)
channelFuture.onFailure(executionContext) { exception ->
this.connectionPromise.completeExceptionally(exception)
}
Expand Down Expand Up @@ -388,7 +390,7 @@ class MySQLConnectionHandler(

private fun onPreparedStatementPrepareResponse(message: PreparedStatementPrepareResponse) {
this.currentPreparedStatementHolder =
PreparedStatementHolder(this.currentPreparedStatement!!.statement, message)
PreparedStatementHolder(this.currentPreparedStatement!!.statement, message)
}

private fun onColumnDefinitionFinished() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
import com.github.jasync.sql.db.Configuration;
import com.github.jasync.sql.db.Connection;
import com.github.jasync.sql.db.QueryResult;
import com.github.jasync.sql.db.ResultSet;
import com.github.jasync.sql.db.RowData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.MySQLContainer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

Expand All @@ -20,6 +25,8 @@ public class ContainerHelper {

public static MySQLContainer mysql;

public static Path domainSocketPath;

public static Integer getPort() {
return defaultConfiguration.getPort();
}
Expand All @@ -46,9 +53,25 @@ public static Integer getPort() {

private static boolean isLocalMySQLRunning() {
try {
new MySQLConnection(rootConfiguration)
.connect().get(1, TimeUnit.SECONDS)
.disconnect().get(1, TimeUnit.SECONDS);
Connection connection = new MySQLConnection(rootConfiguration);
try {
connection.connect().get(1, TimeUnit.SECONDS);
ResultSet resultSet = connection.sendQuery("select @@socket")
.get(1, TimeUnit.SECONDS)
.getRows();
// unix domain socket not available on Windows
if (!resultSet.isEmpty()) {
RowData firstRow = resultSet.get(0);
if (!firstRow.isEmpty()) {
String result = firstRow.getString(0);
if (!result.isEmpty()) {
domainSocketPath = new File(result).toPath();
}
}
}
} finally {
connection.disconnect().get(1, TimeUnit.SECONDS);
}
logger.info("Using local mysql instance {}", defaultConfiguration);
return true;
} catch (Exception e) {
Expand All @@ -57,7 +80,7 @@ private static boolean isLocalMySQLRunning() {
}
}

private static void startMySQLDocker() {
private static void startMySQLDocker() throws IOException {
if (mysql == null) {
// MySQLContainer always sets the root password to be the same as the
// user password. For legacy reasons, we expect the root password to be
Expand All @@ -77,6 +100,14 @@ protected void configure() {
for (String file : Arrays.asList("ca.pem", "server-key.pem", "server-cert.pem", "update-config.sh")) {
mysql.withClasspathResourceMapping(file, "/docker-entrypoint-initdb.d/" + file, BindMode.READ_ONLY);
}
// expose unix domain socket
Path domainSocketDirectoryPath = Files.createTempDirectory("mysqld");
File domainSocketDirectory = domainSocketDirectoryPath.toFile();
domainSocketDirectory.setReadable(true, false);
domainSocketDirectory.setWritable(true, false);
domainSocketDirectory.setExecutable(true, false);
mysql.withFileSystemBind(domainSocketDirectoryPath.toAbsolutePath().toString(), "/var/run/mysqld");
domainSocketPath = domainSocketDirectoryPath.resolve("mysqld.sock");
}
if (!mysql.isRunning()) {
mysql.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,19 @@ class MySQLConnectionSpec : ConnectionHelper() {
}, configurationWithPasswordWithoutDatabase)
}

@Test
fun `connect to a MySQL instance with unix domain socket`() {
val configurationWithSocketPath = Configuration(
username = "mysql_async",
password = "root",
socketPath = ContainerHelper.domainSocketPath.toAbsolutePath().toString()
)
withNonConnectedConnection({ connection ->
assertEquals(connection, awaitFuture(connection.connect()))
awaitFuture(connection.sendQuery("select 1"))
}, configurationWithSocketPath)
}

fun <T> withNonConnectedConnection(fn: (MySQLConnection) -> T, cfg: Configuration): T {
val connection = MySQLConnection(cfg)
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import io.netty.channel.EventLoopGroup
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.CodecException
import io.netty.handler.ssl.SslHandler
import java.net.InetSocketAddress
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import mu.KotlinLogging
Expand Down Expand Up @@ -69,8 +68,12 @@ class PostgreSQLConnectionHandler(
private var currentContext: ChannelHandlerContext? = null

fun connect(): CompletableFuture<PostgreSQLConnectionHandler> {
val socketChannelAddress = NettyUtils.getSocketChannelClassAndSocketAddress(
this.group,
configuration
)
this.bootstrap.group(this.group)
this.bootstrap.channel(NettyUtils.getSocketChannelClass(this.group))
this.bootstrap.channel(socketChannelAddress.socketChannelClass)
this.bootstrap.handler(object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
ch.pipeline().addLast(
Expand All @@ -87,7 +90,7 @@ class PostgreSQLConnectionHandler(
this.bootstrap.option<Boolean>(ChannelOption.SO_KEEPALIVE, true)
this.bootstrap.option(ChannelOption.ALLOCATOR, configuration.allocator)
this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.configuration.connectionTimeout)
this.bootstrap.connect(InetSocketAddress(configuration.host, configuration.port))
this.bootstrap.connect(socketChannelAddress.socketAddress)
.onFailure(executionContext) { e ->
connectionFuture.failed(e)
}
Expand Down
Loading