Skip to content
Closed
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 @@ -55,7 +55,8 @@ 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
)

fun Configuration.toDebugString(): String {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
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 mu.KotlinLogging
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
import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

Expand All @@ -43,10 +49,40 @@ 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
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
): Pair<Class<out Channel>, SocketAddress> {
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 socketChannelClass to socketAddress
}

fun createSslContext(sslConfiguration: SSLConfiguration): SslContext {
Expand Down
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 (socketChannelClass, socketAddress) = NettyUtils.getSocketChannelClassAndSocketAddress(
NettyUtils.DefaultEventLoopGroup,
Configuration(username = "root", socketPath = "/tmp/mysql.sock")
)
assertThat(socketChannelClass.simpleName).isEqualTo("NioSocketChannel")
assertThat(socketAddress::class.simpleName).isEqualTo("InetSocketAddress")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,54 +4,19 @@ import com.github.jasync.sql.db.Configuration
import com.github.jasync.sql.db.exceptions.DatabaseException
import com.github.jasync.sql.db.general.MutableResultSet
import com.github.jasync.sql.db.mysql.binary.BinaryRowDecoder
import com.github.jasync.sql.db.mysql.message.client.AuthenticationSwitchResponse
import com.github.jasync.sql.db.mysql.message.client.CapabilityRequestMessage
import com.github.jasync.sql.db.mysql.message.client.CloseStatementMessage
import com.github.jasync.sql.db.mysql.message.client.HandshakeResponseMessage
import com.github.jasync.sql.db.mysql.message.client.PreparedStatementExecuteMessage
import com.github.jasync.sql.db.mysql.message.client.PreparedStatementPrepareMessage
import com.github.jasync.sql.db.mysql.message.client.QueryMessage
import com.github.jasync.sql.db.mysql.message.client.QuitMessage
import com.github.jasync.sql.db.mysql.message.client.SendLongDataMessage
import com.github.jasync.sql.db.mysql.message.server.AuthenticationSwitchRequest
import com.github.jasync.sql.db.mysql.message.server.BinaryRowMessage
import com.github.jasync.sql.db.mysql.message.server.ColumnDefinitionMessage
import com.github.jasync.sql.db.mysql.message.server.EOFMessage
import com.github.jasync.sql.db.mysql.message.server.ErrorMessage
import com.github.jasync.sql.db.mysql.message.server.HandshakeMessage
import com.github.jasync.sql.db.mysql.message.server.OkMessage
import com.github.jasync.sql.db.mysql.message.server.PreparedStatementPrepareResponse
import com.github.jasync.sql.db.mysql.message.server.ResultSetRowMessage
import com.github.jasync.sql.db.mysql.message.server.ServerMessage
import com.github.jasync.sql.db.mysql.message.client.*

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please refrain from using star imports

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My IDEA with default JetBrains code style automatic format to *, could you please provide your code style xml so i can import to my IDEA.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

import com.github.jasync.sql.db.mysql.message.server.*
import com.github.jasync.sql.db.mysql.util.CharsetMapper
import com.github.jasync.sql.db.util.ExecutorServiceUtils
import com.github.jasync.sql.db.util.FP
import com.github.jasync.sql.db.util.NettyUtils
import com.github.jasync.sql.db.util.XXX
import com.github.jasync.sql.db.util.failed
import com.github.jasync.sql.db.util.flatMapAsync
import com.github.jasync.sql.db.util.head
import com.github.jasync.sql.db.util.installOnFuture
import com.github.jasync.sql.db.util.length
import com.github.jasync.sql.db.util.onFailure
import com.github.jasync.sql.db.util.tail
import com.github.jasync.sql.db.util.toCompletableFuture
import com.github.jasync.sql.db.util.*
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.*
import io.netty.handler.codec.CodecException
import java.net.InetSocketAddress
import mu.KotlinLogging
import java.nio.ByteBuffer
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

Expand Down Expand Up @@ -81,7 +46,11 @@ class MySQLConnectionHandler(
private var isPreparedStatement: Boolean? = null

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

override fun initChannel(channel: Channel) {
Expand All @@ -98,8 +67,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(socketAddress)
channelFuture.onFailure(executionContext) { exception ->
this.connectionPromise.completeExceptionally(exception)
}
Expand Down Expand Up @@ -388,7 +356,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
@@ -1,14 +1,15 @@
package com.github.jasync.sql.db.mysql;

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.RowData;
import com.github.jasync.sql.db.*;
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 +21,8 @@ public class ContainerHelper {

public static MySQLContainer mysql;

public static Path domainSocketPath;

public static Integer getPort() {
return defaultConfiguration.getPort();
}
Expand All @@ -46,9 +49,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 = Path.of(result);
}
}
}
} finally {
connection.disconnect().get(1, TimeUnit.SECONDS);
}
logger.info("Using local mysql instance {}", defaultConfiguration);
return true;
} catch (Exception e) {
Expand All @@ -57,7 +76,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 +96,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
@@ -1,10 +1,10 @@
package com.github.jasync.sql.db.mysql

import com.github.jasync.sql.db.Configuration
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
import org.assertj.core.api.Assertions
import org.junit.Test
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals

class MySQLConnectionSpec : ConnectionHelper() {

Expand Down Expand Up @@ -67,6 +67,18 @@ 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()))
}, 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 @@ -4,42 +4,19 @@ import com.github.jasync.sql.db.Configuration
import com.github.jasync.sql.db.SSLConfiguration
import com.github.jasync.sql.db.column.ColumnEncoderRegistry
import com.github.jasync.sql.db.postgresql.exceptions.QueryMustNotBeNullOrEmptyException
import com.github.jasync.sql.db.postgresql.messages.backend.AuthenticationMessage
import com.github.jasync.sql.db.postgresql.messages.backend.CommandCompleteMessage
import com.github.jasync.sql.db.postgresql.messages.backend.DataRowMessage
import com.github.jasync.sql.db.postgresql.messages.backend.ErrorMessage
import com.github.jasync.sql.db.postgresql.messages.backend.NotificationResponse
import com.github.jasync.sql.db.postgresql.messages.backend.ParameterStatusMessage
import com.github.jasync.sql.db.postgresql.messages.backend.ProcessData
import com.github.jasync.sql.db.postgresql.messages.backend.RowDescriptionMessage
import com.github.jasync.sql.db.postgresql.messages.backend.SSLResponseMessage
import com.github.jasync.sql.db.postgresql.messages.backend.ServerMessage
import com.github.jasync.sql.db.postgresql.messages.backend.*
import com.github.jasync.sql.db.postgresql.messages.frontend.ClientMessage
import com.github.jasync.sql.db.postgresql.messages.frontend.CloseMessage
import com.github.jasync.sql.db.postgresql.messages.frontend.SSLRequestMessage
import com.github.jasync.sql.db.postgresql.messages.frontend.StartupMessage
import com.github.jasync.sql.db.util.ExecutorServiceUtils
import com.github.jasync.sql.db.util.Failure
import com.github.jasync.sql.db.util.NettyUtils
import com.github.jasync.sql.db.util.Success
import com.github.jasync.sql.db.util.failed
import com.github.jasync.sql.db.util.onCompleteAsync
import com.github.jasync.sql.db.util.onFailure
import com.github.jasync.sql.db.util.success
import com.github.jasync.sql.db.util.toCompletableFuture
import com.github.jasync.sql.db.util.*
import io.netty.bootstrap.Bootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.*
import io.netty.handler.codec.CodecException
import io.netty.handler.ssl.SslHandler
import java.net.InetSocketAddress
import mu.KotlinLogging
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

Expand Down Expand Up @@ -69,8 +46,12 @@ class PostgreSQLConnectionHandler(
private var currentContext: ChannelHandlerContext? = null

fun connect(): CompletableFuture<PostgreSQLConnectionHandler> {
val (socketChannelClass, socketAddress) = NettyUtils.getSocketChannelClassAndSocketAddress(
this.group,
configuration
)
this.bootstrap.group(this.group)
this.bootstrap.channel(NettyUtils.getSocketChannelClass(this.group))
this.bootstrap.channel(socketChannelClass)
this.bootstrap.handler(object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
ch.pipeline().addLast(
Expand All @@ -87,7 +68,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(socketAddress)
.onFailure(executionContext) { e ->
connectionFuture.failed(e)
}
Expand Down
Loading