Socket connect()

in core/src/main/java/com/google/cloud/sql/core/Connector.java [104:151]


  Socket connect(ConnectionConfig config, long timeoutMs) throws IOException {
    // Connect using the specified Unix socket
    String unixSocket = getUnixSocketArg(config);
    String unixPathSuffix = config.getUnixSocketPathSuffix();
    if (unixSocket != null) {
      // Verify it ends with the correct suffix
      if (unixPathSuffix != null && !unixSocket.endsWith(unixPathSuffix)) {
        unixSocket = unixSocket + unixPathSuffix;
      }
      logger.debug(
          String.format(
              "Connecting to Cloud SQL instance [%s] via unix socket at %s.",
              config.getCloudSqlInstance(), unixSocket));
      UnixSocketAddress socketAddress = new UnixSocketAddress(new File(unixSocket));
      return UnixSocketChannel.open(socketAddress).socket();
    }

    MonitoredCache instance = getConnection(config);
    try {
      ConnectionMetadata metadata = instance.getConnectionMetadata(timeoutMs);
      String instanceIp = metadata.getPreferredIpAddress();
      logger.debug(String.format("[%s] Connecting to instance.", instanceIp));

      SSLSocket socket = (SSLSocket) metadata.getSslContext().getSocketFactory().createSocket();
      socket.setKeepAlive(true);
      socket.setTcpNoDelay(true);

      socket.connect(new InetSocketAddress(instanceIp, serverProxyPort));

      try {
        socket.startHandshake();
      } catch (IOException e) {
        logger.debug("TLS handshake failed!");
        throw e;
      }

      logger.debug(String.format("[%s] Connected to instance successfully.", instanceIp));
      instance.addSocket(socket);

      return socket;
    } catch (IOException e) {
      logger.debug(
          String.format(
              "[%s] Socket connection failed! Trigger a refresh.", config.getCloudSqlInstance()));
      instance.forceRefresh();
      throw e;
    }
  }