protected Connection openConnection()

in wrapper/src/main/java/software/amazon/jdbc/DataSourceConnectionProvider.java [158:226]


  protected Connection openConnection(
      final @NonNull DataSource ds,
      final @NonNull String protocol,
      final @NonNull TargetDriverDialect targetDriverDialect,
      final @NonNull HostSpec hostSpec,
      final @NonNull Properties props)
      throws SQLException {
    final boolean enableGreenNodeReplacement = PropertyDefinition.ENABLE_GREEN_NODE_REPLACEMENT.getBoolean(props);
    try {
      targetDriverDialect.prepareDataSource(
          ds,
          protocol,
          hostSpec,
          props);
      return ds.getConnection();
    } catch (Throwable throwable) {
      if (!enableGreenNodeReplacement) {
        throw throwable;
      }

      UnknownHostException unknownHostException = null;
      int maxDepth = 100;
      Throwable loopThrowable = throwable;
      while (--maxDepth > 0 && loopThrowable != null) {
        if (loopThrowable instanceof UnknownHostException) {
          unknownHostException = (UnknownHostException) loopThrowable;
          break;
        }
        loopThrowable = loopThrowable.getCause();
      }

      if (unknownHostException == null) {
        throw throwable;
      }

      if (!this.rdsUtils.isRdsDns(hostSpec.getHost()) || !this.rdsUtils.isGreenInstance(hostSpec.getHost())) {
        throw throwable;
      }

      // check DNS for such green host name
      InetAddress resolvedAddress = null;
      try {
        resolvedAddress = InetAddress.getByName(hostSpec.getHost());
      } catch (UnknownHostException tmp) {
        // do nothing
      }

      if (resolvedAddress != null) {
        // Green host DNS exists
        throw throwable;
      }

      // Green host DNS doesn't exist. Try to replace it with the corresponding hostname and connect again.

      final String fixedHost = this.rdsUtils.removeGreenInstancePrefix(hostSpec.getHost());
      final HostSpec connectionHostSpec = new HostSpecBuilder(hostSpec.getHostAvailabilityStrategy())
          .copyFrom(hostSpec)
          .host(fixedHost)
          .build();

      targetDriverDialect.prepareDataSource(
          this.dataSource,
          protocol,
          connectionHostSpec,
          props);

      return ds.getConnection();
    }
  }