Class: CloudSQLRubyConnector::SslProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/cloud_sql_ruby_connector/ssl_proxy.rb

Overview

Local TCP proxy that bridges pg (plain) to Cloud SQL (SSL)

This proxy is necessary because Cloud SQL requires direct TLS connections, but libpq (PostgreSQL client) sends an SSLRequest message first, which Cloud SQL doesn’t understand. The proxy accepts plain TCP connections locally and forwards them over the pre-established SSL connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ssl_socket) ⇒ SslProxy

Returns a new instance of SslProxy.



29
30
31
32
33
34
35
36
# File 'lib/cloud_sql_ruby_connector/ssl_proxy.rb', line 29

def initialize(ssl_socket)
  @ssl_socket = ssl_socket
  @server = TCPServer.new("127.0.0.1", 0) # Port 0 = kernel assigns available port
  @port = @server.addr[1]
  @running = false
  @threads = []
  @mutex = Mutex.new
end

Instance Attribute Details

#portObject (readonly)

Returns the value of attribute port.



27
28
29
# File 'lib/cloud_sql_ruby_connector/ssl_proxy.rb', line 27

def port
  @port
end

Instance Method Details

#startObject

Start the proxy server in a background thread



39
40
41
42
# File 'lib/cloud_sql_ruby_connector/ssl_proxy.rb', line 39

def start
  @running = true
  @accept_thread = Thread.new { accept_loop }
end

#stopObject

Stop the proxy server and clean up resources



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/cloud_sql_ruby_connector/ssl_proxy.rb', line 45

def stop
  @mutex.synchronize do
    @running = false
    @accept_thread&.kill if @accept_thread&.alive?
    @threads.each { |t| t.kill if t.alive? }
    @threads.clear
    begin
      @server.close
    rescue StandardError
      nil
    end
    begin
      @ssl_socket.close
    rescue StandardError
      nil
    end
  end
end