Skip to content

Commit

Permalink
Automatic region detection for IAM Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
bhvkshah committed Jul 31, 2023
1 parent f85d206 commit 66282e7
Showing 1 changed file with 38 additions and 24 deletions.
62 changes: 38 additions & 24 deletions src/main/java/com/amazon/redshift/Driver.java
Original file line number Diff line number Diff line change
Expand Up @@ -712,30 +712,7 @@ public static RedshiftProperties parseURL(String url, RedshiftProperties default
}
}

if(null == urlProps.getProperty(RedshiftProperty.AWS_REGION.getName()))
{
//fetch region using jndi-dns from cname endpoint
try
{
String cnameHost = urlProps.getProperty(RedshiftProperty.HOST.getName());

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
InitialDirContext idc = new InitialDirContext(env);
Attributes attrs = idc.getAttributes(cnameHost);
Attribute attr = attrs.get("CNAME");
String fqdn = attr.get().toString();

urlProps = parseHostName(urlProps, fqdn);
}
catch (Exception ex)
{
if(RedshiftLogger.isEnable())
{
logger.logInfo("No CNAME detected for URL");
}
}
}
urlProps = detectRegionAutomatically(urlProps);

return urlProps;
}
Expand Down Expand Up @@ -782,6 +759,43 @@ public static RedshiftProperties parseHostName(RedshiftProperties urlProps, Stri
return urlProps;
}

/**
* Determines the region automatically if not provided by user as part of jdbc url or additional properties
* We do not need to do this for non-IAM url as driver does not use the region parameter for non-IAM endpoints
* @param urlProps the redshift properties collection
* @return the redshift properties collection with region if it was missing earlier and connection is iam auth
*/
private static RedshiftProperties detectRegionAutomatically(RedshiftProperties urlProps)
{
if(null == urlProps.getProperty(RedshiftProperty.AWS_REGION.getName())
&& urlProps.getProperty(RedshiftProperty.IAM_AUTH.getName()).equalsIgnoreCase("true"))
{
//fetch region using jndi-dns from cname endpoint
try
{
String cnameHost = urlProps.getProperty(RedshiftProperty.HOST.getName());

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
InitialDirContext idc = new InitialDirContext(env);
Attributes attrs = idc.getAttributes(cnameHost);
Attribute attr = attrs.get("CNAME");
String fqdn = attr.get().toString();

urlProps = parseHostName(urlProps, fqdn);
}
catch (Exception ex)
{
if(RedshiftLogger.isEnable())
{
logger.logInfo("No CNAME detected for URL");
}
}
}

return urlProps;
}

/**
*
* @param props the connection properties.
Expand Down

0 comments on commit 66282e7

Please sign in to comment.