You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@phoenix.apache.org by lo...@apache.org on 2025/03/30 17:00:26 UTC
(phoenix) branch master updated: PHOENIX-7495 :- Support for HBase Registry Implementations in Phoenix HA Connections (#2074)
This is an automated email from the ASF dual-hosted git repository.
lokiore pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/phoenix.git
The following commit(s) were added to refs/heads/master by this push:
new 3c5e495928 PHOENIX-7495 :- Support for HBase Registry Implementations in Phoenix HA Connections (#2074)
3c5e495928 is described below
commit 3c5e495928b00a862d1a3ad4f3d123eed187284b
Author: Lokesh Khurana <kh...@gmail.com>
AuthorDate: Sun Mar 30 12:00:21 2025 -0500
PHOENIX-7495 :- Support for HBase Registry Implementations in Phoenix HA Connections (#2074)
---
.../org/apache/phoenix/jdbc/ClusterRoleRecord.java | 137 ++++--
.../apache/phoenix/jdbc/HighAvailabilityGroup.java | 129 +++--
.../phoenix/jdbc/HighAvailabilityPolicy.java | 249 ++++++++--
.../phoenix/jdbc/ParallelPhoenixConnection.java | 9 +-
.../org/apache/phoenix/jdbc/PhoenixHAAdmin.java | 18 +-
.../apache/phoenix/jdbc/PhoenixHAAdminTool.java | 1 -
.../java/org/apache/phoenix/util/JDBCUtil.java | 71 ++-
.../jdbc/ClusterRoleRecordGeneratorToolIT.java | 8 +-
.../phoenix/jdbc/FailoverPhoenixConnection2IT.java | 193 ++++++--
.../phoenix/jdbc/FailoverPhoenixConnectionIT.java | 86 ++--
.../HAConnectionWithMasterAndRPCRegistryIT.java | 530 +++++++++++++++++++++
.../phoenix/jdbc/HighAvailabilityGroup2IT.java | 380 +++++++++++++++
.../phoenix/jdbc/HighAvailabilityGroupIT.java | 378 +++------------
.../phoenix/jdbc/HighAvailabilityGroupTestIT.java | 18 +-
.../jdbc/HighAvailabilityTestingUtility.java | 247 +++++++---
.../jdbc/HighAvailabilityTestingUtilityIT.java | 56 ++-
.../phoenix/jdbc/LoggingHAConnectionLimiterIT.java | 21 +-
.../jdbc/ParallelPhoenixConnectionFallbackIT.java | 2 +-
.../phoenix/jdbc/ParallelPhoenixConnectionIT.java | 108 ++++-
.../jdbc/ParallelPhoenixConnectionWorkflowIT.java | 72 ++-
.../ParallelPhoenixNullComparingResultSetIT.java | 12 +-
.../apache/phoenix/jdbc/PhoenixHAAdminToolIT.java | 25 +-
.../apache/phoenix/jdbc/ClusterRoleRecordTest.java | 278 ++++++-----
.../phoenix/jdbc/PhoenixHAAdminToolTest.java | 19 -
.../java/org/apache/phoenix/util/JDBCUtilTest.java | 8 +-
.../src/test/resources/json/test_role_record.json | 10 +
.../json/test_role_record_old_format.json | 9 +
.../json/test_role_record_wrong_format.json | 9 +
.../json/test_role_record_wrong_role_format.json | 9 +
29 files changed, 2266 insertions(+), 826 deletions(-)
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ClusterRoleRecord.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ClusterRoleRecord.java
index c2af18df8b..cc463b7972 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ClusterRoleRecord.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ClusterRoleRecord.java
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
+import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
import org.apache.phoenix.util.JDBCUtil;
import org.apache.phoenix.util.JacksonUtil;
import org.slf4j.Logger;
@@ -77,40 +78,107 @@ public class ClusterRoleRecord {
}
}
+ /**
+ * Enum for HBaseRegistryType being used in current clusterRoleRecord, final connection url
+ * are constructed based on RegistryType and urls stored in clusterRoleRecord
+ */
+ public enum RegistryType {
+ ZK, MASTER, RPC
+ }
+
private final String haGroupName;
private final HighAvailabilityPolicy policy;
- private final String zk1;
+ private final RegistryType registryType;
+ private final String url1;
private final ClusterRole role1;
- private final String zk2;
+ private final String url2;
private final ClusterRole role2;
private final long version;
+ /**
+ * To handle backward compatibility with old ClusterRoleRecords which had zk1 and zk2 as keys
+ * for zk urls, This constructor is only being used {@link ClusterRoleRecord#fromJson} when we
+ * deserialize Cluster Role Record read from ZooKeeper ZNode. If CRR is in old format we will
+ * read zk1 and zk2 and url1 and url2 will be null and if it is in new format zk1 and zk2 will
+ * be null in both cases final url is being stored in url1 and url2
+ * url will be stored in normalized forms which looks like zk1\\:port1,zk2\\:port2,zk3\\:port3,
+ * zk4\\:port4,zk5\\:port5::znode or master1\\:port1,master2\\:port2,master3\\:port3,
+ * master4\\:port4,master5\\:port5
+ * @param haGroupName HighAvailability Group name / CRR name
+ * @param policy Policy used by give CRR
+ * @param registryType {@link RegistryType} to be used for given urls
+ * @param url1 ZK/HMaster url based on registry type for first cluster
+ * @param role1 {@link ClusterRole} which describes the current state of first cluster
+ * @param url2 ZK/HMaster url based on registry type for second cluster
+ * @param role2 {@link ClusterRole} which describes the current state of second cluster
+ * @param version version of a given CRR
+ * @param zk1 ZK url of first cluster when CRR is in old format for backward compatibility
+ * @param zk2 ZK url of second cluster when CRR is in old format for backward compatibility
+ */
@JsonCreator
public ClusterRoleRecord(@JsonProperty("haGroupName") String haGroupName,
- @JsonProperty("policy") HighAvailabilityPolicy policy,
- @JsonProperty("zk1") String zk1, @JsonProperty("role1") ClusterRole role1,
- @JsonProperty("zk2") String zk2, @JsonProperty("role2") ClusterRole role2,
- @JsonProperty("version") long version) {
+ @JsonProperty("policy") HighAvailabilityPolicy policy,
+ @JsonProperty("registryType") RegistryType registryType,
+ @JsonProperty("url1") String url1,
+ @JsonProperty("role1") ClusterRole role1,
+ @JsonProperty("url2") String url2,
+ @JsonProperty("role2") ClusterRole role2,
+ @JsonProperty("version") long version,
+ @JsonProperty("zk1") String zk1,
+ @JsonProperty("zk2") String zk2) {
this.haGroupName = haGroupName;
this.policy = policy;
+ this.registryType = registryType != null ? registryType : RegistryType.ZK;
+
+ String resolvedUrl1 = (url1 != null) ? url1 : zk1; //For Backward Compatibility
+ String resolvedUrl2 = (url2 != null) ? url2 : zk2; //For Backward Compatibility
+
//Do we really need to normalize here ?
- zk1 = JDBCUtil.formatZookeeperUrl(zk1);
- zk2 = JDBCUtil.formatZookeeperUrl(zk2);
+ //We are normalizing to have urls in specific formats for each registryType for getting
+ //accurate comparisons. We are passing registryType as these url most probably won't have
+ //protocol in url, and it might be normalized based to wrong registry type, as we normalize
+ //w.r.t {@link ConnectionInfo.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY},
+ //but considering source of truth of registryType is present in CLusterRoleRecord we are
+ //normalizing based on that.
+ //url will be in form :- zk1\\:port1,zk2\\:port2,zk3\\:port3,zk4\\:port4,zk5\\:port5::znode
+ //or master1\\:port1,master2\\:port2,master3\\:port3,master4\\:port4,master5\\:port5
+ url1 = JDBCUtil.formatUrl(resolvedUrl1, this.registryType);
+ url2 = JDBCUtil.formatUrl(resolvedUrl2, this.registryType);
+
+ Preconditions.checkArgument(!url1.equals(url2), "Two clusters have the same URLS!");
+ Preconditions.checkNotNull(role1, "Role of a cluster cannot be null!");
+ Preconditions.checkNotNull(role2, "Role of a cluster cannot be null!");
+
// Ignore the given order of url1 and url2
- if (zk1.compareTo(zk2) < 0) {
- this.zk1 = zk1;
+ if (url1.compareTo(url2) < 0) {
+ this.url1 = url1;
this.role1 = role1;
- this.zk2 = zk2;
+ this.url2 = url2;
this.role2 = role2;
} else {
- this.zk1 = zk2;
+ this.url1 = url2;
this.role1 = role2;
- this.zk2 = zk1;
+ this.url2 = url1;
this.role2 = role1;
}
this.version = version;
}
+ public ClusterRoleRecord(String haGroupName, HighAvailabilityPolicy policy,
+ String url1, ClusterRole role1,
+ String url2, ClusterRole role2,
+ long version) {
+ this(haGroupName, policy, RegistryType.ZK, url1, role1, url2, role2, version, null, null);
+ }
+
+ public ClusterRoleRecord(String haGroupName, HighAvailabilityPolicy policy,
+ RegistryType registryType,
+ String url1, ClusterRole role1,
+ String url2, ClusterRole role2,
+ long version) {
+ this(haGroupName, policy, registryType, url1, role1, url2, role2, version, null, null);
+ }
+
public static Optional<ClusterRoleRecord> fromJson(byte[] bytes) {
if (bytes == null) {
return Optional.empty();
@@ -130,10 +198,10 @@ public class ClusterRoleRecord {
@JsonIgnore
public Optional<String> getActiveUrl() {
if (role1 == ClusterRole.ACTIVE) {
- return Optional.of(zk1);
+ return Optional.of(url1);
}
if (role2 == ClusterRole.ACTIVE) {
- return Optional.of(zk2);
+ return Optional.of(url2);
}
return Optional.empty();
}
@@ -150,18 +218,16 @@ public class ClusterRoleRecord {
public boolean hasSameInfo(ClusterRoleRecord other) {
return haGroupName.equals(other.haGroupName) &&
- policy.equals(other.policy) &&
- zk1.equalsIgnoreCase(other.zk1) &&
- zk2.equalsIgnoreCase(other.zk2);
+ policy.equals(other.policy);
}
/**
- * @return role by ZK url or UNKNOWN if the zkUrl does not belong to this HA group
+ * @return role by url or UNKNOWN if the Url does not belong to this HA group
*/
- public ClusterRole getRole(String zkUrl) {
- if (zk1.equals(zkUrl)) {
+ public ClusterRole getRole(String url) {
+ if (url1.equals(url)) {
return role1;
- } else if (zk2.equals(zkUrl)) {
+ } else if (url2.equals(url)) {
return role2;
} else {
return ClusterRole.UNKNOWN;
@@ -176,16 +242,20 @@ public class ClusterRoleRecord {
return policy;
}
- public String getZk1() {
- return zk1;
+ public RegistryType getRegistryType() {
+ return registryType;
+ }
+
+ public String getUrl1() {
+ return url1;
}
public ClusterRole getRole1() {
return role1;
}
- public String getZk2() {
- return zk2;
+ public String getUrl2() {
+ return url2;
}
public ClusterRole getRole2() {
@@ -201,9 +271,10 @@ public class ClusterRoleRecord {
return new HashCodeBuilder()
.append(haGroupName)
.append(policy)
- .append(zk1)
+ .append(registryType)
+ .append(url1)
.append(role1)
- .append(zk2)
+ .append(url2)
.append(role2)
.append(version)
.hashCode();
@@ -222,9 +293,10 @@ public class ClusterRoleRecord {
return new EqualsBuilder()
.append(haGroupName, otherRecord.haGroupName)
.append(policy, otherRecord.policy)
- .append(zk1, otherRecord.zk1)
+ .append(registryType, otherRecord.registryType)
+ .append(url1, otherRecord.url1)
.append(role1, otherRecord.role1)
- .append(zk2, otherRecord.zk2)
+ .append(url2, otherRecord.url2)
.append(role2, otherRecord.role2)
.append(version, otherRecord.version)
.isEquals();
@@ -236,9 +308,10 @@ public class ClusterRoleRecord {
return "ClusterRoleRecord{"
+ "haGroupName='" + haGroupName + '\''
+ ", policy=" + policy
- + ", zk1='" + zk1 + '\''
+ + ", registryType=" + registryType
+ + ", url1='" + url1 + '\''
+ ", role1=" + role1
- + ", zk2='" + zk2 + '\''
+ + ", url2='" + url2 + '\''
+ ", role2=" + role2
+ ", version=" + version
+ '}';
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityGroup.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityGroup.java
index 938b60275b..c00e533dac 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityGroup.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityGroup.java
@@ -17,6 +17,7 @@
*/
package org.apache.phoenix.jdbc;
+import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -32,7 +33,6 @@ import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole;
import org.apache.phoenix.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
-import org.apache.phoenix.thirdparty.com.google.common.base.Strings;
import org.apache.phoenix.thirdparty.com.google.common.cache.Cache;
import org.apache.phoenix.thirdparty.com.google.common.cache.CacheBuilder;
import org.apache.phoenix.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
@@ -269,6 +269,13 @@ public class HighAvailabilityGroup {
}
}
+ //If additional parameter is only ; then making it null as while building back jdbc url
+ //if we don't have principal we need additional checks to make sure we are not appending
+ //additionalJDBCParams after JDBC_PROTOCOL_SEPARATOR.
+ additionalJDBCParams = additionalJDBCParams != null
+ ? (additionalJDBCParams.equals(String.valueOf(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR))
+ ? null : additionalJDBCParams) : null;
+
String name = properties.getProperty(PHOENIX_HA_GROUP_ATTR);
if (StringUtils.isEmpty(name)) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.HA_INVALID_PROPERTIES)
@@ -397,7 +404,11 @@ public class HighAvailabilityGroup {
}
String fallbackCluster = properties.getProperty(PHOENIX_HA_FALLBACK_CLUSTER_KEY);
if (StringUtils.isEmpty(fallbackCluster)) {
- fallbackCluster = haGroupInfo.getUrl1();
+ LOG.error("Fallback to single cluster is enabled for the HA group {} but cluster key is"
+ + "empty per configuration 'phoenix.ha.fallback.cluster', and boostrap url "
+ + "cannot be used as fallback cluster as it can be different that urls present in"
+ + "ClusterRoleRecords which are source of truth. HA url: '{}'.", haGroupInfo.getName(), url);
+ return Optional.empty();
}
// Ensure the fallback cluster URL includes the JDBC protocol prefix
@@ -665,7 +676,7 @@ public class HighAvailabilityGroup {
return false;
}
return roleRecord.getActiveUrl()
- .equals(Optional.of(JDBCUtil.formatZookeeperUrl(connection.getURL())));
+ .equals(Optional.of(JDBCUtil.formatUrl(connection.getURL())));
}
/**
@@ -682,11 +693,11 @@ public class HighAvailabilityGroup {
Preconditions.checkArgument(url.length() > PhoenixRuntime.JDBC_PROTOCOL.length(),
"The URL '" + url + "' is not a valid Phoenix connection string");
}
- url = JDBCUtil.formatZookeeperUrl(url);
- Preconditions.checkArgument(url.equals(info.getUrl1()) || url.equals(info.getUrl2()),
- "The URL '" + url + "' does not belong to this HA group " + info);
+ //we don't need to normalize here? as we already store url in roleRecord object as
+ //normalized, or we are just normalizing for tests?
+ url = JDBCUtil.formatUrl(url, roleRecord.getRegistryType());
- String jdbcString = info.getJDBCUrl(url, haurlInfo);
+ String jdbcString = getJDBCUrl(url, haurlInfo, roleRecord.getRegistryType());
ClusterRole role = roleRecord.getRole(url);
if (!role.canConnect()) {
@@ -696,7 +707,7 @@ public class HighAvailabilityGroup {
.buildException();
}
- // Get driver instead of using PhoenixDriver.INSTANCE since it can be test or mocked driver
+ //Get driver instead of using PhoenixDriver.INSTANCE since it can be a test or mocked driver
Driver driver = DriverManager.getDriver(jdbcString);
Preconditions.checkArgument(driver instanceof PhoenixEmbeddedDriver,
"No JDBC driver is registered for Phoenix high availability (HA) framework");
@@ -787,7 +798,7 @@ public class HighAvailabilityGroup {
LOG.info("HA group {} is in {} to set V{} record", info, state, newRoleRecord.getVersion());
Future<?> future = nodeChangedExecutor.submit(() -> {
try {
- roleRecord.getPolicy().transitClusterRole(this, roleRecord, newRoleRecord);
+ roleRecord.getPolicy().transitClusterRoleRecord(this, roleRecord, newRoleRecord);
} catch (SQLException e) {
throw new CompletionException(e);
}
@@ -856,8 +867,10 @@ public class HighAvailabilityGroup {
Preconditions.checkNotNull(url1);
Preconditions.checkNotNull(url2);
this.name = name;
- url1 = JDBCUtil.formatZookeeperUrl(url1);
- url2 = JDBCUtil.formatZookeeperUrl(url2);
+ //Normalizing these urls with ZK protocol as these are the ZK urls of clusters where
+ //roleRecords resides.
+ url1 = JDBCUtil.formatUrl(url1, ClusterRoleRecord.RegistryType.ZK);
+ url2 = JDBCUtil.formatUrl(url2, ClusterRoleRecord.RegistryType.ZK);
Preconditions.checkArgument(!url1.equals(url2), "Two clusters have the same ZK!");
// Ignore the given order of url1 and url2, and reorder for equals comparison.
if (url1.compareTo(url2) > 0) {
@@ -879,47 +892,12 @@ public class HighAvailabilityGroup {
return urls.getSecond();
}
-
- public String getJDBCUrl(String zkUrl, HAURLInfo haURLInfo) {
- Preconditions.checkArgument(zkUrl.equals(getUrl1()) || zkUrl.equals(getUrl2())
- || zkUrl.equals("[" + getUrl1() + "|" + getUrl2() + "]")
- || zkUrl.equals("[" + getUrl2() + "|" + getUrl1() + "]"),
- "The URL '" + zkUrl + "' does not belong to this HA group " + this);
- StringBuilder sb = new StringBuilder();
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_ZK);
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- sb.append(zkUrl);
- if (haURLInfo != null) {
- if (!Strings.isNullOrEmpty(haURLInfo.getPrincipal())
- && !Strings.isNullOrEmpty(haURLInfo.getAdditionalJDBCParams())) {
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- sb.append(haURLInfo.getPrincipal());
- if (!haURLInfo.getAdditionalJDBCParams().
- equals(String.valueOf(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR))) {
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- }
- sb.append(haURLInfo.getAdditionalJDBCParams());
- } else if (!Strings.isNullOrEmpty(haURLInfo.getPrincipal())) {
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- sb.append(haURLInfo.getPrincipal());
- } else if (!Strings.isNullOrEmpty(haURLInfo.getAdditionalJDBCParams())) {
- if (!haURLInfo.getAdditionalJDBCParams().
- equals(String.valueOf(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR))) {
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
- }
- sb.append(haURLInfo.getAdditionalJDBCParams());
- }
- }
- return sb.toString();
- }
-
public String getJDBCUrl1(HAURLInfo haURLInfo) {
- return getJDBCUrl(getUrl1(), haURLInfo);
+ return getJDBCUrl(getUrl1(), haURLInfo, ClusterRoleRecord.RegistryType.ZK);
}
public String getJDBCUrl2(HAURLInfo haURLInfo) {
- return getJDBCUrl(getUrl2(), haURLInfo);
+ return getJDBCUrl(getUrl2(), haURLInfo, ClusterRoleRecord.RegistryType.ZK);
}
/**
@@ -960,6 +938,60 @@ public class HighAvailabilityGroup {
}
}
+ /**
+ * Helper method to construct the jdbc url back from the given information for a HAGroup
+ * Url are expected to be passed in correct format i.e. zk1\\:port1,zk2\\:port2,zk3\\:port3,zk4\\:port4,zk5\\:port5::znode
+ * or master1\\:port1,master2\\:port2,master3\\:port3,master4\\:port4,master5\\:port5
+ * @param url contains host and port part of jdbc url, to get ha url in jdbc format
+ * this function can be used, but needs url in ha format already i.e. [url1|url2]
+ * for MASTER and RPC registry
+ * @param haURLInfo contains principal and additional information
+ * @param type Registry Type for which url has to be constructed
+ * @return jdbc url in proper format i.e. jdbc:phoenix+<registry>:url:principal:additionalParam
+ * example :- jdbc:phoenix+zk:zk1\\:port1,zk2\\:port2,zk3\\:port3,zk4\\:port4,zk5\\:port5::znode:principal:additionalParams
+ * or jdbc:phoenix+master:master1\\:port1,master2\\:port2,master3\\:port3,master4\\:port4,master5\\:port5::principal:additionParams
+ */
+ public static String getJDBCUrl(String url, HAURLInfo haURLInfo,
+ ClusterRoleRecord.RegistryType type) {
+ //Need extra separator for Master and RPC connections for principal as no znode path is there
+ boolean extraSeparator = false;
+ StringBuilder sb = new StringBuilder();
+ switch (type) {
+ case ZK:
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_ZK);
+ break;
+ case RPC:
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_RPC);
+ extraSeparator = true;
+ break;
+ case MASTER:
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_MASTER);
+ extraSeparator = true;
+ break;
+ default:
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL);
+ }
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
+ sb.append(url);
+ if (haURLInfo != null) {
+ if (ObjectUtils.anyNotNull(haURLInfo.getPrincipal(), haURLInfo.getAdditionalJDBCParams())) {
+ if (extraSeparator) {
+ //For Master and RPC connection url we need 2 extra separator between port and
+ //principal as there is no ZNode
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR).
+ append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR);
+ }
+ sb.append(haURLInfo.getPrincipal() == null ? PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR
+ : PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + haURLInfo.getPrincipal());
+ }
+ if (ObjectUtils.anyNotNull(haURLInfo.getAdditionalJDBCParams())) {
+ sb.append(PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR).
+ append(haURLInfo.getAdditionalJDBCParams());
+ }
+ }
+ return sb.toString();
+ }
+
/**
* Maintains the client view of cluster roles for the HA group using data retrieved from one ZK.
* <p>
@@ -1028,5 +1060,6 @@ public class HighAvailabilityGroup {
roleManagerLatch.countDown();
}
}
+
}
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityPolicy.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityPolicy.java
index ea026a6806..64c60a4a71 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityPolicy.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/HighAvailabilityPolicy.java
@@ -24,6 +24,8 @@ import static org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole.STANDBY;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import java.util.Properties;
import org.apache.phoenix.exception.SQLExceptionCode;
@@ -44,63 +46,103 @@ public enum HighAvailabilityPolicy {
FailoverPhoenixContext context = new FailoverPhoenixContext(info, haGroup, haURLInfo);
return new FailoverPhoenixConnection(context);
}
+
@Override
void transitClusterRole(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
ClusterRoleRecord newRecord) throws SQLException {
+ if (newRecord.getRole1() == ACTIVE && newRecord.getRole2() == ACTIVE) {
+ LOG.warn("Both cluster roles are ACTIVE which is invalid state for FailoverPolicy" +
+ "Doing nothing for Cluster Role Change");
+ return;
+ }
if (oldRecord.getRole1() == ACTIVE && newRecord.getRole1() == STANDBY) {
- transitStandby(haGroup, oldRecord.getZk1());
+ transitStandby(haGroup, oldRecord.getUrl1(), oldRecord.getRegistryType());
}
if (oldRecord.getRole2() == ACTIVE && newRecord.getRole2() == STANDBY) {
- transitStandby(haGroup, oldRecord.getZk2());
+ transitStandby(haGroup, oldRecord.getUrl2(), oldRecord.getRegistryType());
}
if (oldRecord.getRole1() != ACTIVE && newRecord.getRole1() == ACTIVE) {
- transitActive(haGroup, oldRecord.getZk1());
+ transitActive(haGroup, oldRecord.getUrl1(), oldRecord.getRegistryType());
}
if (oldRecord.getRole2() != ACTIVE && newRecord.getRole2() == ACTIVE) {
- transitActive(haGroup, oldRecord.getZk2());
+ transitActive(haGroup, oldRecord.getUrl2(), oldRecord.getRegistryType());
}
}
- private void transitStandby(HighAvailabilityGroup haGroup, String zkUrl)
- throws SQLException {
- // Close connections when a previously ACTIVE HBase cluster becomes STANDBY.
- LOG.info("Cluster {} becomes STANDBY in HA group {}, now close all its connections",
- zkUrl, haGroup.getGroupInfo());
- ConnectionQueryServices cqs = null;
-
- //Close connections for every HAURLInfo's (different principal) conn for a give HAGroup
- for (HAURLInfo haurlInfo : HighAvailabilityGroup.URLS.get(haGroup.getGroupInfo())) {
- try {
- String jdbcZKUrl = haGroup.getGroupInfo().getJDBCUrl(zkUrl, haurlInfo);
- cqs = PhoenixDriver.INSTANCE.getConnectionQueryServices(
- jdbcZKUrl, haGroup.getProperties());
- cqs.closeAllConnections(new SQLExceptionInfo
- .Builder(SQLExceptionCode.HA_CLOSED_AFTER_FAILOVER)
- .setMessage("Phoenix connection got closed due to failover")
- .setHaGroupInfo(haGroup.getGroupInfo().toString()));
- LOG.info("Closed all connections to cluster {} for HA group {}",
- jdbcZKUrl, haGroup.getGroupInfo());
- } finally {
- if (cqs != null) {
- //CQS is closed but it is not invalidated from global cache in PhoenixDriver
- //so that any new connection will get error instead of creating a new CQS
- LOG.info("Closing CQS after cluster '{}' becomes STANDBY", zkUrl);
- cqs.close();
- LOG.info("Successfully closed CQS after cluster '{}' becomes STANDBY",
- zkUrl);
+
+ @Override
+ void transitRoleRecordRegistry(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException {
+ Optional<String> activeUrl = oldRecord.getActiveUrl();
+
+ //Close connections for Active HBase cluster as there is a change in Registry Type
+ if (activeUrl.isPresent()) {
+ LOG.info("Cluster {} has a change in registryType in HA group {}, now closing "
+ + "all its connections", activeUrl.get(), oldRecord.getRegistryType());
+ closeConnections(haGroup, activeUrl.get(), oldRecord.getRegistryType());
+ } else {
+ LOG.info("None of the cluster in HA Group {} is active", haGroup);
+ }
+ }
+
+ /**
+ * For FAILOVER Policy if there is a change in active url or there is no new active url then close all connections.
+ * In below examples only a portion of CRR is shown, url1, url2 are current urls present in
+ * clusterRoleRecord and url3, url4 are new urls in clusterRoleRecord
+ * (url1, ACTIVE, url2, STANDBY) --> (url1, ACTIVE, url3, STANDBY) //Nothing is needed as only Standby url changed
+ * (url1, ACTIVE, url2, STANDBY) --> (url3, ACTIVE, url2, STANDBY) //Active url change close connections
+ * (url1, ACTIVE, url2, STANDBY) --> (url3, ACTIVE, url4, STANDBY) //Active url change close connections
+ * (url1, ACTIVE, url2, STANDBY) --> (url3, ACTIVE, url1, STANDBY)
+ * //Here active became standby but other url changed close connections
+ * (url1, OFFLINE, url2, STANDBY) --> (url3, ACTIVE, url2, STANDBY) //Nothing to do as there were no connections
+ * (url1, ACTIVE, url2, STANDBY) --> (url3, OFFLINE, url2, STANDBY) //Closing old connections as no new active url
+ * @param haGroup The high availability (HA) group
+ * @param oldRecord The older cluster role record cached in this client for the given HA group
+ * @param newRecord New cluster role record read from one ZooKeeper cluster znode
+ * @throws SQLException when not able to close connections
+ */
+ @Override
+ void transitClusterUrl(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException {
+ Optional<String> activeUrl = oldRecord.getActiveUrl();
+ Optional<String> newActiveUrl = newRecord.getActiveUrl();
+ if (activeUrl.isPresent()) {
+ if (newActiveUrl.isPresent()) {
+ if (activeUrl.get().equals(newActiveUrl.get())) {
+ LOG.info("Active URL is same after cluster role record transition" +
+ "Doing nothing for FailoverPhoenixConnections");
+ } else {
+ LOG.info("Active url of clusterRoleRecord changed from {} to {}, " +
+ "closing old connections", activeUrl.get(), newActiveUrl.get());
+ closeConnections(haGroup, activeUrl.get(), oldRecord.getRegistryType());
}
+ } else {
+ LOG.info("Couldn't find active url in new ClusterRoleRecord," +
+ "Closing old connections");
+ closeConnections(haGroup, activeUrl.get(), oldRecord.getRegistryType());
}
+ } else {
+ LOG.info("Couldn't find active url in old ClusterRoleRecord, " +
+ "Doing nothing for FailoverPhoenixConnections");
}
}
- private void transitActive(HighAvailabilityGroup haGroup, String zkUrl)
- throws SQLException {
+ private void transitStandby(HighAvailabilityGroup haGroup, String url,
+ ClusterRoleRecord.RegistryType registryType) throws SQLException {
+ // Close connections when a previously ACTIVE HBase cluster becomes STANDBY.
+ LOG.info("Cluster {} becomes STANDBY in HA group {}, now close all its connections",
+ url, haGroup.getGroupInfo());
+ closeConnections(haGroup, url, registryType);
+ }
+
+ private void transitActive(HighAvailabilityGroup haGroup, String url,
+ ClusterRoleRecord.RegistryType registryType) throws SQLException {
// Invalidate CQS cache if any that has been closed but has not been cleared
- for (HAURLInfo haurlInfo : HighAvailabilityGroup.URLS.get(haGroup.getGroupInfo())) {
- String jdbcZKUrl = haGroup.getGroupInfo().getJDBCUrl(zkUrl, haurlInfo);
- LOG.info("invalidating cqs cache for zkUrl: " + jdbcZKUrl);
- PhoenixDriver.INSTANCE.invalidateCache(jdbcZKUrl,
- haGroup.getProperties());
- }
+ for (HAURLInfo haurlInfo : HighAvailabilityGroup.URLS.get(haGroup.getGroupInfo())) {
+ String jdbcUrl = HighAvailabilityGroup.getJDBCUrl(url, haurlInfo, registryType);
+ LOG.info("invalidating cqs cache for zkUrl: " + jdbcUrl);
+ PhoenixDriver.INSTANCE.invalidateCache(jdbcUrl,
+ haGroup.getProperties());
+ }
}
},
@@ -123,14 +165,89 @@ public enum HighAvailabilityPolicy {
return haGroup.connectActive(info, haURLInfo);
}
}
+
@Override
void transitClusterRole(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
ClusterRoleRecord newRecord) {
- LOG.info("Cluster role changed for parallel HA policy.");
+ //No Action for Parallel Policy
+ }
+
+
+ @Override
+ void transitRoleRecordRegistry(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException {
+ //Close connections of both clusters as there is a change in registryType
+ LOG.info("Cluster {} and {} has a change in registryType in HA group {}, now closing all its connections",
+ oldRecord.getUrl1(), oldRecord.getUrl2() , oldRecord.getRegistryType());
+ //close connections for cluster 1
+ closeConnections(haGroup, oldRecord.getUrl1(), oldRecord.getRegistryType());
+ //close connections for cluster 2
+ closeConnections(haGroup, oldRecord.getUrl2(), oldRecord.getRegistryType());
+ }
+
+ /**
+ * For PARALLEL policy if there is a change in any of the url then ParallelPhoenixConnection
+ * objects are invalid
+ * @param haGroup The high availability (HA) group
+ * @param oldRecord The older cluster role record cached in this client for the given HA group
+ * @param newRecord New cluster role record read from one ZooKeeper cluster znode
+ * @throws SQLException when not able to close connections
+ */
+ @Override
+ void transitClusterUrl(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException {
+ if (!Objects.equals(oldRecord.getUrl1(), newRecord.getUrl1()) &&
+ !Objects.equals(oldRecord.getUrl1(), newRecord.getUrl2())) {
+ LOG.info("Cluster {} is changed to {} in HA group {}, now closing all its connections",
+ oldRecord.getUrl1(), newRecord.getUrl1(), haGroup);
+ closeConnections(haGroup, oldRecord.getUrl1(), oldRecord.getRegistryType());
+ }
+ if (!Objects.equals(oldRecord.getUrl2(), newRecord.getUrl2()) &&
+ !Objects.equals(oldRecord.getUrl2(), newRecord.getUrl1())) {
+ LOG.info("Cluster {} is changed to {} in HA group {}, now closing all its connections",
+ oldRecord.getUrl2(), newRecord.getUrl2(), haGroup);
+ closeConnections(haGroup, oldRecord.getUrl2(), oldRecord.getRegistryType());
+ }
+
}
};
- private static final Logger LOG = LoggerFactory.getLogger(HighAvailabilityGroup.class);
+ private static final Logger LOG = LoggerFactory.getLogger(HighAvailabilityPolicy.class);
+
+ /**
+ * Utility to close cqs and all it's connection for specific url of a HAGroup
+ * @param haGroup The High Availability (HA) Group
+ * @param url The url on which cqs and connections are present
+ * @param registryType The registry Type of connections
+ * @throws SQLException if fails to close the connections
+ */
+ private static void closeConnections(HighAvailabilityGroup haGroup, String url,
+ ClusterRoleRecord.RegistryType registryType) throws SQLException {
+ ConnectionQueryServices cqs = null;
+ //Close connections for every HAURLInfo's (different principal) conn for a give HAGroup
+ for (HAURLInfo haurlInfo : HighAvailabilityGroup.URLS.get(haGroup.getGroupInfo())) {
+ try {
+ cqs = PhoenixDriver.INSTANCE.getConnectionQueryServices(
+ HighAvailabilityGroup.getJDBCUrl(url, haurlInfo, registryType), haGroup.getProperties());
+ cqs.closeAllConnections(new SQLExceptionInfo
+ .Builder(SQLExceptionCode.HA_CLOSED_AFTER_FAILOVER)
+ .setMessage("Phoenix connection got closed due to failover")
+ .setHaGroupInfo(haGroup.getGroupInfo().toString()));
+ LOG.info("Closed all connections to cluster {} for HA group {}", url,
+ haGroup.getGroupInfo());
+ } finally {
+ if (cqs != null) {
+ // CQS is closed, but it is not invalidated from global cache in PhoenixDriver
+ // so that any new connection will get error instead of creating a new CQS,
+ // CQS entry will stay in map until the cache expires and repopulated in cases
+ // of URL and registryType changes
+ LOG.info("Closing CQS after clusterRoleRecord change for '{}'", url);
+ cqs.close();
+ LOG.info("Successfully closed CQS after clusterRoleRecord change for '{}'", url);
+ }
+ }
+ }
+ }
/**
* Provides a JDBC connection from given connection string and properties.
@@ -145,7 +262,31 @@ public enum HighAvailabilityPolicy {
throws SQLException;
/**
- * Call-back function when a cluster role transition is detected in the high availability group.
+ * Call-back function when a cluster role record transition is detected in the high availability group.
+ *
+ * @param haGroup The high availability (HA) group
+ * @param oldRecord The older cluster role record cached in this client for the given HA group
+ * @param newRecord New cluster role record read from one ZooKeeper cluster znode
+ * @throws SQLException if fails to handle the cluster role record transition
+ */
+ public void transitClusterRoleRecord(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException {
+ if (oldRecord.getRegistryType() != newRecord.getRegistryType()) {
+ transitRoleRecordRegistry(haGroup, oldRecord, newRecord);
+ } else if (!oldRecord.getUrl1().equals(newRecord.getUrl1()) ||
+ !oldRecord.getUrl2().equals(newRecord.getUrl2())) {
+ //If registryType is not changing then we need to check if any of the url is changing
+ //as change in registryType closes all the current connections
+ transitClusterUrl(haGroup, oldRecord, newRecord);
+ } else {
+ //If both registryType and url is not changing then we need to check if there is a
+ //role transition.
+ transitClusterRole(haGroup, oldRecord, newRecord);
+ }
+ }
+
+ /**
+ * Call-back function when only role transition is detected in the high availability group or clusterRoleRecord.
*
* @param haGroup The high availability (HA) group
* @param oldRecord The older cluster role record cached in this client for the given HA group
@@ -154,4 +295,28 @@ public enum HighAvailabilityPolicy {
*/
abstract void transitClusterRole(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
ClusterRoleRecord newRecord) throws SQLException;
+
+
+ /**
+ * Call-back function when only registry transition is detected in the high availability group or clusterRoleRecord.
+ *
+ * @param haGroup The high availability (HA) group
+ * @param oldRecord The older cluster role record cached in this client for the given HA group
+ * @param newRecord New cluster role record read from one ZooKeeper cluster znode
+ * @throws SQLException if fails to handle the cluster role record registry transition
+ */
+ abstract void transitRoleRecordRegistry(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException;
+
+ /**
+ * Call-back function when only url transition is detected in the high availability group or clusterRoleRecord.
+ *
+ * @param haGroup The high availability (HA) group
+ * @param oldRecord The older cluster role record cached in this client for the given HA group
+ * @param newRecord New cluster role record read from one ZooKeeper cluster znode
+ * @throws SQLException if fails to handle the cluster url transition
+ */
+ abstract void transitClusterUrl(HighAvailabilityGroup haGroup, ClusterRoleRecord oldRecord,
+ ClusterRoleRecord newRecord) throws SQLException;
+
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ParallelPhoenixConnection.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ParallelPhoenixConnection.java
index c067027493..9ac38cbd8d 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ParallelPhoenixConnection.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/ParallelPhoenixConnection.java
@@ -69,14 +69,13 @@ public class ParallelPhoenixConnection implements PhoenixMonitoredConnection {
CompletableFuture<PhoenixConnection> futureConnection2;
public ParallelPhoenixConnection(ParallelPhoenixContext context) throws SQLException {
this.context = context;
- LOG.trace("First Url: {} Second Url: {}", context.getHaGroup().getGroupInfo().
- getJDBCUrl1(context.getHaurlInfo()), context.getHaGroup().getGroupInfo().
- getJDBCUrl2(context.getHaurlInfo()));
+ LOG.trace("First Url: {} Second Url: {}", context.getHaGroup().getRoleRecord().getUrl1(),
+ context.getHaGroup().getRoleRecord().getUrl2());
futureConnection1 = context.chainOnConn1(() -> getConnection(context.getHaGroup(),
- context.getHaGroup().getGroupInfo().getJDBCUrl1(context.getHaurlInfo()),
+ context.getHaGroup().getRoleRecord().getUrl1(),
context.getProperties(), context.getHaurlInfo()));
futureConnection2 = context.chainOnConn2(() -> getConnection(context.getHaGroup(),
- context.getHaGroup().getGroupInfo().getJDBCUrl2(context.getHaurlInfo()),
+ context.getHaGroup().getRoleRecord().getUrl2(),
context.getProperties(), context.getHaurlInfo()));
// Ensure one connection is successful before returning
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdmin.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdmin.java
index c9019b6c1a..0ef78372e0 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdmin.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdmin.java
@@ -90,7 +90,7 @@ public class PhoenixHAAdmin implements Closeable {
Preconditions.checkNotNull(zkUrl);
Preconditions.checkNotNull(conf);
Preconditions.checkNotNull(highAvailibilityCuratorProvider);
- this.zkUrl = JDBCUtil.formatZookeeperUrl(zkUrl);
+ this.zkUrl = JDBCUtil.formatUrl(zkUrl);
this.conf = conf;
conf.iterator().forEachRemaining(k -> properties.setProperty(k.getKey(), k.getValue()));
this.highAvailibilityCuratorProvider = highAvailibilityCuratorProvider;
@@ -219,8 +219,8 @@ public class PhoenixHAAdmin implements Closeable {
Map<String, List<String>> failedHaGroups = new HashMap<>();
for (ClusterRoleRecord record : records) {
String haGroupName = record.getHaGroupName();
- try (PhoenixHAAdmin admin1 = new PhoenixHAAdmin(record.getZk1(), conf, HighAvailibilityCuratorProvider.INSTANCE);
- PhoenixHAAdmin admin2 = new PhoenixHAAdmin(record.getZk2(), conf, HighAvailibilityCuratorProvider.INSTANCE)) {
+ try (PhoenixHAAdmin admin1 = new PhoenixHAAdmin(record.getUrl1(), conf, HighAvailibilityCuratorProvider.INSTANCE);
+ PhoenixHAAdmin admin2 = new PhoenixHAAdmin(record.getUrl2(), conf, HighAvailibilityCuratorProvider.INSTANCE)) {
// Update the cluster previously ACTIVE cluster first.
// It reduces the chances of split-brain between clients and clusters.
// If can not determine previous ACTIVE cluster, update new STANDBY cluster first.
@@ -277,7 +277,7 @@ public class PhoenixHAAdmin implements Closeable {
zkUrl, record);
continue;
}
- String remoteZkUrl = record.getZk1().equals(zkUrl) ? record.getZk2() : record.getZk1();
+ String remoteZkUrl = record.getUrl1().equals(zkUrl) ? record.getUrl2() : record.getUrl1();
try (PhoenixHAAdmin remoteAdmin = new PhoenixHAAdmin(remoteZkUrl, conf,
HighAvailibilityCuratorProvider.INSTANCE)) {
ClusterRoleRecord remoteRecord;
@@ -338,16 +338,6 @@ public class PhoenixHAAdmin implements Closeable {
* @throws IOException if it fails to update the cluster role data on ZK
*/
public boolean createOrUpdateDataOnZookeeper(ClusterRoleRecord record) throws IOException {
- if (!zkUrl.equals(record.getZk1()) && !zkUrl.equals(record.getZk2())) {
- String
- msg =
- String.format(
- "INTERNAL ERROR: " + "ZK cluster is not associated with cluster role record! " + "ZK cluster URL: '%s'. Cluster role record: %s",
- zkUrl, record);
- LOG.error(msg);
- throw new IOException(msg);
- }
-
String haGroupName = record.getHaGroupName();
byte[] data;
try {
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdminTool.java b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdminTool.java
index a59dc9fd8d..d4fed4e1f0 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdminTool.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/jdbc/PhoenixHAAdminTool.java
@@ -155,7 +155,6 @@ public class PhoenixHAAdminTool extends Configured implements Tool {
}
}
-
/**
* Parses the commandline arguments, throw exception if validation fails.
*
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/JDBCUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/JDBCUtil.java
index c4f64c47a2..68c313e309 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/JDBCUtil.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/JDBCUtil.java
@@ -28,6 +28,8 @@ import javax.annotation.Nullable;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Consistency;
+import org.apache.phoenix.jdbc.AbstractRPCConnectionInfo;
+import org.apache.phoenix.jdbc.ClusterRoleRecord;
import org.apache.phoenix.jdbc.ConnectionInfo;
import org.apache.phoenix.jdbc.ZKConnectionInfo;
import org.apache.phoenix.query.QueryServices;
@@ -208,37 +210,66 @@ public class JDBCUtil {
}
/**
- * Get the ZK quorom and root and node part of the URL, which is used by the HA code internally
- * to identify the clusters.
+ * Get the ZK quorum and root and node part of the URL in case of ZKRegistry and bootstrap nodes for other registry
+ * which is used by the HA code internally to identify the clusters.
* As we interpret a missing protocol as ZK, this is mostly idempotent for zk quorum strings.
*
- * @param jdbcUrl JDBC URL
- * @return part of the URL determining the ZK quorum and node
+ * @param jdbcUrl JDBC URL with proper protocol present in string
+ * @return part of the URL determining the ZK quorum and node or bootstrapServers
* @throws RuntimeException if the URL is invalid, or does not resolve to a ZK Registry
* connection
*/
- public static String formatZookeeperUrl(String jdbcUrl) {
+ public static String formatUrl(String jdbcUrl) {
ConnectionInfo connInfo;
try {
- Properties info = new Properties();
- // Make sure we use ZK on HBase 3.x
- info.put(HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY,
- ZKConnectionInfo.ZK_REGISTRY_NAME);
- connInfo = ConnectionInfo.create(jdbcUrl, null, info);
- // TODO in theory we could support non-ZK registries for HA.
- // However, as HA already relies on ZK, this wouldn't be particularly useful,
- // and would require significant changes.
- if (!(connInfo instanceof ZKConnectionInfo)) {
- throw new SQLException("HA connections must use ZooKeeper registry. " + jdbcUrl
- + " is not a Zookeeper HBase connection");
- }
- ZKConnectionInfo zkInfo = (ZKConnectionInfo) connInfo;
+ connInfo = ConnectionInfo.create(jdbcUrl, null, null);
StringBuilder sb = new StringBuilder();
- sb.append(zkInfo.getZkHosts().replaceAll(":", "\\\\:")).append("::")
- .append(zkInfo.getZkRootNode());
+ if (connInfo instanceof AbstractRPCConnectionInfo) {
+ //TODO: check if anything else is needed for RPCRegistry connections and do we need to store them in CRR
+ AbstractRPCConnectionInfo rpcInfo = (AbstractRPCConnectionInfo) connInfo;
+ sb.append(rpcInfo.getBoostrapServers().replaceAll(":", "\\\\:"));
+ } else {
+ //Here we are appending '::' because ZKConnectionInfo.getZKHosts return formatted
+ //ZKQuorum which is in format zk1:port1,zk2:port2.. and we need double separator to
+ //add ZNode
+ ZKConnectionInfo zkInfo = (ZKConnectionInfo) connInfo;
+ sb.append(zkInfo.getZkHosts().replaceAll(":", "\\\\:")).append("::")
+ .append(zkInfo.getZkRootNode());
+ }
return sb.toString();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
+
+ /**
+ * Get the formatted URL, in case of ZK URL it returns ZK quorum and root and node part of the URL and in case of
+ * Master or RPC URL it returns bootstrap servers with ports
+ * Use this method instead of {@link #formatUrl(String)} if you want to format url specific to a protocol or
+ * for urls coming from roleRecord as urls for fetching roleRecords those don't have protocol in the url and could
+ * be normalized differently based on configs.
+ * @param url that needs to be formatted
+ * @param registryType format based on the given registryType
+ * @return formatted url without protocol
+ */
+ public static String formatUrl(String url, ClusterRoleRecord.RegistryType registryType) {
+ if (!url.startsWith(PhoenixRuntime.JDBC_PROTOCOL)) {
+ switch (registryType) {
+ case ZK:
+ return formatUrl(PhoenixRuntime.JDBC_PROTOCOL_ZK +
+ PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + url);
+ case MASTER:
+ return formatUrl(PhoenixRuntime.JDBC_PROTOCOL_MASTER +
+ PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + url);
+ case RPC:
+ return formatUrl(PhoenixRuntime.JDBC_PROTOCOL_RPC +
+ PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + url);
+ default:
+ return formatUrl(PhoenixRuntime.JDBC_PROTOCOL +
+ PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + url);
+
+ }
+ }
+ return formatUrl(url);
+ }
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ClusterRoleRecordGeneratorToolIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ClusterRoleRecordGeneratorToolIT.java
index 0cc5048bcc..25953354e6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ClusterRoleRecordGeneratorToolIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ClusterRoleRecordGeneratorToolIT.java
@@ -104,8 +104,8 @@ public class ClusterRoleRecordGeneratorToolIT {
assertEquals(1, records.size());
for (ClusterRoleRecord record : records) {
assertEquals(HighAvailabilityPolicy.FAILOVER, record.getPolicy());
- assertEquals(ClusterRole.ACTIVE, record.getRole(CLUSTERS.getUrl1()));
- assertEquals(ClusterRole.STANDBY, record.getRole(CLUSTERS.getUrl2()));
+ assertEquals(ClusterRole.ACTIVE, record.getRole(CLUSTERS.getZkUrl1()));
+ assertEquals(ClusterRole.STANDBY, record.getRole(CLUSTERS.getZkUrl2()));
}
}
@@ -126,8 +126,8 @@ public class ClusterRoleRecordGeneratorToolIT {
assertEquals(3, records.size());
for (ClusterRoleRecord record : records) {
assertEquals(HighAvailabilityPolicy.PARALLEL, record.getPolicy());
- assertEquals(ClusterRole.ACTIVE, record.getRole(CLUSTERS.getUrl2()));
- assertEquals(ClusterRole.STANDBY, record.getRole(CLUSTERS.getUrl1()));
+ assertEquals(ClusterRole.ACTIVE, record.getRole(CLUSTERS.getZkUrl2()));
+ assertEquals(ClusterRole.STANDBY, record.getRole(CLUSTERS.getZkUrl1()));
}
}
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnection2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnection2IT.java
index 8d3361fd2f..a93a13c4f6 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnection2IT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnection2IT.java
@@ -17,38 +17,41 @@
*/
package org.apache.phoenix.jdbc;
- import static org.apache.hadoop.test.GenericTestUtils.waitFor;
- import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneZKDown;
- import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
- import static org.apache.phoenix.jdbc.HighAvailabilityGroup.PHOENIX_HA_GROUP_ATTR;
- import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertFalse;
- import static org.junit.Assert.assertTrue;
- import static org.junit.Assert.fail;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.TimeUnit;
-
- import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
- import org.junit.After;
- import org.junit.AfterClass;
- import org.junit.Before;
- import org.junit.BeforeClass;
- import org.junit.Rule;
- import org.junit.Test;
- import org.junit.experimental.categories.Category;
- import org.junit.rules.TestName;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
+import static org.apache.hadoop.test.GenericTestUtils.waitFor;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneZKDown;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
+import static org.apache.phoenix.jdbc.HighAvailabilityGroup.PHOENIX_HA_GROUP_ATTR;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Test failover basics for {@link FailoverPhoenixConnection}.
@@ -94,7 +97,7 @@ public class FailoverPhoenixConnection2IT {
haGroup = getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), clientProperties);
LOG.info("Initialized haGroup {} with URL {}", haGroup, CLUSTERS.getJdbcHAUrl());
tableName = testName.getMethodName().toUpperCase();
- CLUSTERS.createTableOnClusterPair(tableName);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
}
@After
@@ -102,10 +105,10 @@ public class FailoverPhoenixConnection2IT {
try {
haGroup.close();
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), haGroup.getProperties())
.close();
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(haGroup), haGroup.getProperties())
.close();
} catch (Exception e) {
LOG.error("Fail to tear down the HA group and the CQS. Will ignore", e);
@@ -134,7 +137,7 @@ public class FailoverPhoenixConnection2IT {
try (Connection conn = createFailoverConnection()) {
FailoverPhoenixConnection failoverConn = (FailoverPhoenixConnection) conn;
- assertEquals(CLUSTERS.getJdbcUrl2(), failoverConn.getWrappedConnection().getURL());
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), failoverConn.getWrappedConnection().getURL());
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
}
});
@@ -155,7 +158,7 @@ public class FailoverPhoenixConnection2IT {
// Try to make a connection to current ACTIVE cluster, which should fail.
try {
createFailoverConnection();
- fail("Should have failed since ACTIVE ZK '" + CLUSTERS.getUrl1() + "' is down");
+ fail("Should have failed since ACTIVE ZK '" + CLUSTERS.getZkUrl1() + "' is down");
} catch (SQLException e) {
LOG.info("Got expected exception when ACTIVE ZK cluster is down", e);
}
@@ -167,7 +170,7 @@ public class FailoverPhoenixConnection2IT {
try (Connection conn = createFailoverConnection()) {
FailoverPhoenixConnection failoverConn = (FailoverPhoenixConnection) conn;
- assertEquals(CLUSTERS.getJdbcUrl2(), failoverConn.getWrappedConnection().getURL());
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), failoverConn.getWrappedConnection().getURL());
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
}
});
@@ -216,7 +219,7 @@ public class FailoverPhoenixConnection2IT {
LOG.info("Testing failover connection when both clusters are up and running");
try (Connection conn = createFailoverConnection()) {
FailoverPhoenixConnection failoverConn = conn.unwrap(FailoverPhoenixConnection.class);
- assertEquals(CLUSTERS.getJdbcUrl2(), failoverConn.getWrappedConnection().getURL());
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), failoverConn.getWrappedConnection().getURL());
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
}
@@ -251,11 +254,9 @@ public class FailoverPhoenixConnection2IT {
fail("Should have failed since ACTIVE ZK cluster was shutdown");
} catch (SQLException e) {
LOG.info("Got expected exception when ACTIVE ZK cluster {} was shutdown",
- CLUSTERS.getUrl2(), e);
+ CLUSTERS.getZkUrl2(), e);
}
});
-
- // After the second cluster (ACTIVE) ZK restarts, this should still work
try (Connection conn = createFailoverConnection()) {
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
}
@@ -286,7 +287,7 @@ public class FailoverPhoenixConnection2IT {
fail("Should have failed since ACTIVE ZK cluster was shutdown");
} catch (SQLException e) {
LOG.info("Got expected exception when ACTIVE ZK cluster {} was shutdown",
- CLUSTERS.getUrl2(), e);
+ CLUSTERS.getZkUrl2(), e);
}
// So on-call engineer comes into play, and triggers a failover
@@ -354,7 +355,7 @@ public class FailoverPhoenixConnection2IT {
try {
Connection c = future.get(100, TimeUnit.MILLISECONDS);
PhoenixConnection pc = ((FailoverPhoenixConnection) c).getWrappedConnection();
- if (!pc.isClosed() && !pc.getURL().equals(CLUSTERS.getUrl2())) {
+ if (!pc.isClosed() && !pc.getURL().equals(CLUSTERS.getZkUrl2())) {
fail("Found one connection to cluster1 but it is not closed");
}
} catch (Exception e) {
@@ -365,6 +366,110 @@ public class FailoverPhoenixConnection2IT {
}, 100, 120_000);
}
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR. ZK --> MASTER
+ *
+ * Test with many connections.
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterRegistryChangeToMaster() throws Exception {
+ short numberOfConnections = 10;
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(createFailoverConnection());
+ }
+ ClusterRoleRecord.RegistryType newRegistry = ClusterRoleRecord.RegistryType.MASTER;
+ CLUSTERS.transitClusterRoleRecordRegistry(haGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+ }
+ }
+
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR. ZK --> RPC
+ *
+ * Test with many connections.
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterRegistryChangeToRpc() throws Exception {
+ short numberOfConnections = 10;
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(createFailoverConnection());
+ }
+ ClusterRoleRecord.RegistryType newRegistry = ClusterRoleRecord.RegistryType.RPC;
+ CLUSTERS.transitClusterRoleRecordRegistry(haGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+ }
+ }
+
+ /**
+ * Testing connection closure for roleRecord change from
+ * (URL1, ACTIVE, URL2, STANDBY) -> (URL3, ACTIVE, URL2, STANDBY)
+ * All wrapped connections should have been closed
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterActiveURLChange() throws Exception {
+ short numberOfConnections = 10;
+ //Create FailoverPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(createFailoverConnection());
+ }
+
+ //Restart Cluster 1 with new ports
+ CLUSTERS.restartCluster1();
+ //Basically applying new url for cluster 1
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(haGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+ conn.close();
+ }
+ }
+
+ /**
+ * Testing connection closure for roleRecord change from
+ * (URL1, ACTIVE, URL2, STANDBY) -> (URL1, ACTIVE, URL3, STANDBY)
+ * It should not have affected connections at all
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsNotClosedAfterStandbyURLChange() throws Exception {
+ short numberOfConnections = 10;
+ //Create FailoverPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(createFailoverConnection());
+ }
+
+ //Restart Cluster 2 with new ports
+ CLUSTERS.restartCluster2();
+ //Basically applying new url for cluster 2
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(haGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertFalse(conn.getWrappedConnection().isClosed());
+ conn.close();
+ }
+ }
+
/**
* Create a failover connection using {@link #clientProperties}.
*/
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java
index de2486fb51..ab26000567 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/FailoverPhoenixConnectionIT.java
@@ -39,6 +39,8 @@ import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -67,6 +69,8 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -90,6 +94,7 @@ public class FailoverPhoenixConnectionIT {
private String tableName;
/** HA Group name for this test. */
private String haGroupName;
+ private final ClusterRoleRecord.RegistryType registryType = ClusterRoleRecord.RegistryType.ZK;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@@ -115,7 +120,7 @@ public class FailoverPhoenixConnectionIT {
haGroup = getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), clientProperties);
LOG.info("Initialized haGroup {} with URL {}", haGroup, CLUSTERS.getJdbcHAUrl());
tableName = testName.getMethodName().toUpperCase();
- CLUSTERS.createTableOnClusterPair(tableName);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
}
@After
@@ -123,10 +128,10 @@ public class FailoverPhoenixConnectionIT {
try {
haGroup.close();
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), haGroup.getProperties())
.close();
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(haGroup), haGroup.getProperties())
.close();
} catch (Exception e) {
LOG.error("Fail to tear down the HA group and the CQS. Will ignore", e);
@@ -215,7 +220,7 @@ public class FailoverPhoenixConnectionIT {
// The wrapped connection is still against the first cluster, and is closed
PhoenixConnection pc = ((FailoverPhoenixConnection)conn).getWrappedConnection();
assertNotNull(pc);
- assertEquals(CLUSTERS.getJdbcUrl1(), pc.getURL());
+ assertEquals(CLUSTERS.getJdbcUrl1(haGroup), pc.getURL());
assertTrue(pc.isClosed());
doTestActionShouldFailBecauseOfFailover(conn::createStatement);
}
@@ -245,7 +250,7 @@ public class FailoverPhoenixConnectionIT {
*/
@Test(timeout = 300000)
public void testNonHAConnectionNotClosedAfterFailover() throws Exception {
- String firstUrl = String.format("jdbc:phoenix+zk:%s", CLUSTERS.getUrl1());
+ String firstUrl = String.format("jdbc:phoenix+zk:%s", CLUSTERS.getZkUrl1());
// This is a vanilla Phoenix connection without using high availability (HA) feature.
Connection phoenixConn = DriverManager.getConnection(firstUrl, new Properties());
Connection failoverConn = createFailoverConnection();
@@ -272,7 +277,7 @@ public class FailoverPhoenixConnectionIT {
PhoenixConnection wrappedConn = ((FailoverPhoenixConnection) conn).getWrappedConnection();
// Following we create a new HA group and create a connection against this HA group
String haGroupName2 = haGroup.getGroupInfo().getName() + "2";
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+ initClusterRoleRecord(haGroupName2);
Properties clientProperties2 = new Properties(clientProperties);
clientProperties2.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
Connection conn2 = DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), clientProperties2);
@@ -302,7 +307,7 @@ public class FailoverPhoenixConnectionIT {
public void testFailoverCanFinishWhenOneConnectionGotStuckClosing() throws Exception {
Connection conn = createFailoverConnection();
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
- assertEquals(CLUSTERS.getJdbcUrl1(), // active connection is against the first cluster
+ assertEquals(CLUSTERS.getJdbcUrl1(haGroup), // active connection is against the first cluster
conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
// Spy the wrapped connection
@@ -316,7 +321,7 @@ public class FailoverPhoenixConnectionIT {
return null;
}).when(spy).close();
ConnectionQueryServices cqs = PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), clientProperties);
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), clientProperties);
// replace the wrapped connection with the spied connection in CQS
cqs.removeConnection(wrapped.unwrap(PhoenixConnection.class));
cqs.addConnection(spy.unwrap(PhoenixConnection.class));
@@ -335,7 +340,7 @@ public class FailoverPhoenixConnectionIT {
try (Connection conn2 = createFailoverConnection()) {
doTestBasicOperationsWithConnection(conn2, tableName, haGroupName);
- assertEquals(CLUSTERS.getJdbcUrl2(), // active connection is against the second cluster
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), // active connection is against the second cluster
conn2.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
}
@@ -456,7 +461,7 @@ public class FailoverPhoenixConnectionIT {
public void testFailoverTwice() throws Exception {
try (Connection conn = createFailoverConnection()) {
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
- assertEquals(CLUSTERS.getJdbcUrl1(), // active connection is against the first cluster
+ assertEquals(CLUSTERS.getJdbcUrl1(haGroup), // active connection is against the first cluster
conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
}
@@ -465,7 +470,7 @@ public class FailoverPhoenixConnectionIT {
try (Connection conn = createFailoverConnection()) {
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
- assertEquals(CLUSTERS.getJdbcUrl2(), // active connection is against the second cluster
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), // active connection is against the second cluster
conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
}
@@ -474,7 +479,7 @@ public class FailoverPhoenixConnectionIT {
try (Connection conn = createFailoverConnection()) {
doTestBasicOperationsWithConnection(conn, tableName, haGroupName);
- assertEquals(CLUSTERS.getJdbcUrl1(), // active connection is against the first cluster
+ assertEquals(CLUSTERS.getJdbcUrl1(haGroup), // active connection is against the first cluster
conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
}
}
@@ -526,7 +531,7 @@ public class FailoverPhoenixConnectionIT {
@Test(timeout = 300000)
public void testTenantSpecificPhoenixConnection() throws Exception {
tableName = tableName + "Tenant";
- CLUSTERS.createTenantSpecificTable(tableName);
+ CLUSTERS.createTenantSpecificTable(haGroup, tableName);
clientProperties.setProperty("TenantId", "mytenant");
Connection tenantConn = createFailoverConnection();
@@ -613,7 +618,7 @@ public class FailoverPhoenixConnectionIT {
// Following we create a new HA group and create a connection against this HA group with default PRINCIPAL
String haGroupName2 = haGroup.getGroupInfo().getName() + "2";
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+ initClusterRoleRecord(haGroupName2);
Properties clientProperties2 = new Properties(clientProperties);
clientProperties2.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
Connection conn3 = DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), clientProperties2);
@@ -642,31 +647,35 @@ public class FailoverPhoenixConnectionIT {
public void testUserPrincipal() throws Exception {
Connection conn = createFailoverConnection(); //PRINCIPAL, haGroupName
FailoverPhoenixConnection fconn = (FailoverPhoenixConnection) conn;
- ConnectionQueryServices cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), clientProperties);
+ ConnectionQueryServices cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), clientProperties);
String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);;
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+ initClusterRoleRecord(haGroupName2);
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+ HighAvailabilityGroup haGroup2 = getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), clientProperties);
Connection conn2 = DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), clientProperties); //PRINCIPAL,haGroupName2
FailoverPhoenixConnection fconn2 = (FailoverPhoenixConnection) conn2;
- ConnectionQueryServices cqsi2 = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), clientProperties);
+ ConnectionQueryServices cqsi2 = PhoenixDriver.INSTANCE.getConnectionQueryServices(
+ CLUSTERS.getJdbcUrl1(haGroup2), clientProperties);
Connection conn3 = DriverManager.getConnection(CLUSTERS.getJdbcHAUrlWithoutPrincipal(), clientProperties); //null,haGroupName2
FailoverPhoenixConnection fconn3 = (FailoverPhoenixConnection) conn3;
ConnectionQueryServices cqsi3 = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.
- getJdbcUrlWithoutPrincipal(CLUSTERS.getUrl1()), clientProperties);
+ getJdbcUrlWithoutPrincipal(haGroup2, CLUSTERS.getURL(1,
+ haGroup2.getRoleRecord().getRegistryType())), clientProperties);
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName);
String principal4 = RandomStringUtils.randomAlphabetic(5);
Connection conn4 = DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(principal4), clientProperties);//principal4, haGroupName
FailoverPhoenixConnection fconn4 = (FailoverPhoenixConnection) conn4;
- ConnectionQueryServices cqsi4 = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(principal4), clientProperties);
+ ConnectionQueryServices cqsi4 = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup, principal4), clientProperties);
//Check wrapped connection urls
- Assert.assertEquals(CLUSTERS.getJdbcUrl1(), fconn.getWrappedConnection().getURL());
- Assert.assertEquals(CLUSTERS.getJdbcUrl1(), fconn2.getWrappedConnection().getURL());
- Assert.assertEquals(CLUSTERS.getJdbcUrlWithoutPrincipal(CLUSTERS.getUrl1()), fconn3.getWrappedConnection().getURL());
- Assert.assertEquals(CLUSTERS.getJdbcUrl1(principal4), fconn4.getWrappedConnection().getURL());
+ Assert.assertEquals(CLUSTERS.getJdbcUrl1(haGroup), fconn.getWrappedConnection().getURL());
+ Assert.assertEquals(CLUSTERS.getJdbcUrl1(haGroup2), fconn2.getWrappedConnection().getURL());
+ Assert.assertEquals(CLUSTERS.getJdbcUrlWithoutPrincipal(haGroup2, CLUSTERS.getURL(1,
+ haGroup2.getRoleRecord().getRegistryType())), fconn3.getWrappedConnection().getURL());
+ Assert.assertEquals(CLUSTERS.getJdbcUrl1(haGroup, principal4), fconn4.getWrappedConnection().getURL());
//Check cqsi objects should be same with what we get from connections
Assert.assertEquals(HBaseTestingUtilityPair.PRINCIPAL,cqsi.getUserName());
@@ -686,21 +695,27 @@ public class FailoverPhoenixConnectionIT {
@Test(timeout = 300000)
public void testHAGroupMappingsWithDifferentPrincipalsOnDifferentThreads() throws Exception {
int numThreads = RandomUtils.nextInt(3, 5);
- List<Thread> connectionThreads = new ArrayList<>(numThreads);
- AtomicBoolean isPrincipalNull = new AtomicBoolean(false);
+ List<Thread> connectionThreads = new ArrayList<>(numThreads + 4);
//Creating random number of connections one connection per thread with different principal
//Including one connection will null principal all of them will be using given haGroupName
//which is specific to test
for (int i = 0; i < numThreads; i++) {
- isPrincipalNull.set((i + 1) % 3 == 0);
connectionThreads.add(new Thread(() -> {
try {
- createConnectionWithRandomPrincipal(isPrincipalNull.get());
+ createConnectionWithRandomPrincipal(false);
} catch (SQLException e) {
e.printStackTrace();
}
}));
}
+ //Add connections without principal
+ connectionThreads.add(new Thread(() -> {
+ try {
+ createConnectionWithRandomPrincipal(true);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }));
//Create multiple connections with given principal
String principal = RandomStringUtils.randomAlphabetic(3);
@@ -724,9 +739,9 @@ public class FailoverPhoenixConnectionIT {
}
//For the given ha group of current test the value in URLS set for current haGroupInfo
- //should be numThreads + 1 as all the connections created with same principal should have
- //one entry in map.
- Assert.assertEquals(numThreads + 1, URLS.get(haGroup.getGroupInfo()).size());
+ //should be numThreads + 2 as all the connections created with same principal should have
+ //one entry in map and one extra for null principal
+ Assert.assertEquals(numThreads + 2, URLS.get(haGroup.getGroupInfo()).size());
}
/**
@@ -774,11 +789,16 @@ public class FailoverPhoenixConnectionIT {
} // all other type of exception will fail this test.
}
- private Connection createConnectionWithRandomPrincipal(boolean isPrincipalNull) throws SQLException {
+ private void createConnectionWithRandomPrincipal(boolean isPrincipalNull) throws SQLException {
String principal = RandomStringUtils.randomAlphabetic(5);
if (isPrincipalNull) {
- return DriverManager.getConnection(CLUSTERS.getJdbcHAUrlWithoutPrincipal(), clientProperties);
+ DriverManager.getConnection(CLUSTERS.getJdbcHAUrlWithoutPrincipal(), clientProperties);
+ return;
}
- return DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(principal), clientProperties);
+ DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(principal), clientProperties);
+ }
+
+ private void initClusterRoleRecord(String haGroupName) throws Exception {
+ CLUSTERS.initClusterRole(haGroupName, HighAvailabilityPolicy.FAILOVER);
}
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HAConnectionWithMasterAndRPCRegistryIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HAConnectionWithMasterAndRPCRegistryIT.java
new file mode 100644
index 0000000000..4facc114ea
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HAConnectionWithMasterAndRPCRegistryIT.java
@@ -0,0 +1,530 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.jdbc;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
+import org.apache.phoenix.jdbc.ClusterRoleRecord.RegistryType;
+import org.apache.phoenix.query.ConnectionQueryServices;
+import org.apache.phoenix.query.ConnectionQueryServicesImpl;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.mockito.Mockito;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.*;
+import java.util.concurrent.CountDownLatch;
+
+import static org.apache.hadoop.test.GenericTestUtils.waitFor;
+import static org.apache.phoenix.jdbc.HighAvailabilityGroup.PHOENIX_HA_GROUP_ATTR;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneHBaseDown;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+/**
+ * Test HA basics for {@link ClusterRoleRecord} with {@link RegistryType} as MASTER.
+ */
+@RunWith(Parameterized.class)
+@Category(NeedsOwnMiniClusterTest.class)
+public class HAConnectionWithMasterAndRPCRegistryIT {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HAConnectionWithMasterAndRPCRegistryIT.class);
+ private static final HighAvailabilityTestingUtility.HBaseTestingUtilityPair CLUSTERS = new HighAvailabilityTestingUtility.HBaseTestingUtilityPair();
+
+ @Rule
+ public final TestName testName = new TestName();
+ /** Client properties to create a connection per test. */
+ private Properties parallelClientProperties;
+ private Properties failoverClientProperties;
+ /** HA group for this test. */
+ private HighAvailabilityGroup parallelHAGroup;
+ private HighAvailabilityGroup failoverHAGroup;
+ /** Table name per test case. */
+ private String tableName;
+ /** HA Group name for this test. */
+ private String parallelHAGroupName;
+ private String failoverHAGroupName;
+ /** Registry Type for this test */
+ private final RegistryType registryType;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ CLUSTERS.start();
+ DriverManager.registerDriver(PhoenixDriver.INSTANCE);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ DriverManager.deregisterDriver(PhoenixDriver.INSTANCE);
+ CLUSTERS.close();
+ }
+
+ @Before
+ public void setup() throws Exception {
+ parallelHAGroupName = testName.getMethodName() + "_" + HighAvailabilityPolicy.PARALLEL.name();
+ failoverHAGroupName = testName.getMethodName() + "_" + HighAvailabilityPolicy.FAILOVER.name();
+ parallelClientProperties = HighAvailabilityTestingUtility.getHATestProperties();
+ parallelClientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, parallelHAGroupName);
+
+ failoverClientProperties = HighAvailabilityTestingUtility.getHATestProperties();
+ failoverClientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, failoverHAGroupName);
+
+ // Make first cluster ACTIVE
+ CLUSTERS.initClusterRole(parallelHAGroupName, HighAvailabilityPolicy.PARALLEL, registryType);
+ CLUSTERS.initClusterRole(failoverHAGroupName, HighAvailabilityPolicy.FAILOVER, registryType);
+
+ parallelHAGroup = getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), parallelClientProperties);
+ LOG.info("Initialized haGroup {} with URL {}", parallelHAGroup, CLUSTERS.getJdbcHAUrl());
+ failoverHAGroup = getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), failoverClientProperties);
+ LOG.info("Initialized haGroup {} with URL {}", failoverHAGroup, CLUSTERS.getJdbcHAUrl());
+ tableName = RandomStringUtils.randomAlphabetic(10).toUpperCase();
+ CLUSTERS.createTableOnClusterPair(parallelHAGroup, tableName);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ try {
+ parallelHAGroup.close();
+ failoverHAGroup.close();
+ PhoenixDriver.INSTANCE
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(parallelHAGroup), parallelHAGroup.getProperties())
+ .close();
+ PhoenixDriver.INSTANCE
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(parallelHAGroup), parallelHAGroup.getProperties())
+ .close();
+ } catch (Exception e) {
+ LOG.error("Fail to tear down the HA group and the CQS. Will ignore", e);
+ }
+ }
+
+ @Parameterized.Parameters(name="ClusterRoleRecord_registryType={0}")
+ public static Collection<Object> data() {
+ return Arrays.asList(new Object[] {
+ ClusterRoleRecord.RegistryType.MASTER,
+ ClusterRoleRecord.RegistryType.RPC,
+ });
+ }
+
+ public HAConnectionWithMasterAndRPCRegistryIT(ClusterRoleRecord.RegistryType registryType) {
+ this.registryType = registryType;
+ }
+
+ /**
+ * Test that failover can finish even if one connection can not be closed.
+ *
+ * When once cluster becomes STANDBY from ACTIVE, all its connections and the associated CQS
+ * will get closed asynchronously. In case of errors when closing those connections and CQS,
+ * the HA group is still able to transit to target state after the maximum timeout.
+ * Closing the existing connections is guaranteed with the best effort and timeout in favor of
+ * improved availability.
+ *
+ * {@link FailoverPhoenixConnectionIT#testFailoverTwice()} which fails over back to the first cluster
+ */
+ @Test(timeout = 300000)
+ public void testFailoverCanFinishWhenOneConnectionGotStuckClosing() throws Exception {
+ Connection conn = getFailoverConnection();
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ assertEquals(CLUSTERS.getJdbcUrl1(failoverHAGroup), // active connection is against the first cluster
+ conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
+
+ // Spy the wrapped connection
+ Connection wrapped = conn.unwrap(FailoverPhoenixConnection.class).getWrappedConnection();
+ Connection spy = Mockito.spy(wrapped);
+ final CountDownLatch latch = new CountDownLatch(1);
+ // Make close() stuck before closing
+ doAnswer((invocation) -> {
+ latch.await();
+ invocation.callRealMethod();
+ return null;
+ }).when(spy).close();
+ ConnectionQueryServices cqs = PhoenixDriver.INSTANCE
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(failoverHAGroup), failoverClientProperties);
+ // replace the wrapped connection with the spied connection in CQS
+ cqs.removeConnection(wrapped.unwrap(PhoenixConnection.class));
+ cqs.addConnection(spy.unwrap(PhoenixConnection.class));
+
+ // (ACTIVE, STANDBY) -> (STANDBY, ACTIVE)
+ // The transition will finish as we set PHOENIX_HA_TRANSITION_TIMEOUT_MS_KEY for this class
+ // even though the spied connection is stuck at the latch when closing
+ CLUSTERS.transitClusterRole(failoverHAGroup, ClusterRoleRecord.ClusterRole.STANDBY, ClusterRoleRecord.ClusterRole.ACTIVE);
+
+ // Verify the spied object has been called once
+ verify(spy, times(1)).close();
+ // The spy is not closed because the real method was blocked by latch
+ assertFalse(spy.isClosed());
+ // connection is not closed as Phoenix HA does not close failover connections.
+ assertFalse(conn.isClosed());
+
+ try (Connection conn2 = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn2, tableName, failoverHAGroupName);
+ assertEquals(CLUSTERS.getJdbcUrl2(failoverHAGroup), // active connection is against the second cluster
+ conn2.unwrap(FailoverPhoenixConnection.class).getWrappedConnection().getURL());
+ }
+
+ latch.countDown();
+ conn.close();
+ // The CQS should be closed eventually.
+ waitFor(() -> {
+ try {
+ ((ConnectionQueryServicesImpl) cqs).checkClosed();
+ return false;
+ } catch (IllegalStateException e) {
+ LOG.info("CQS got closed as we get expected exception.", e);
+ return true;
+ }
+ }, 100, 10_000);
+ }
+
+ /**
+ * Tests the scenario where ACTIVE HBase cluster restarts.
+ *
+ * When ACTIVE HBase cluster shutdown, client can not connect to this HA group.
+ * After failover, client can connect to this HA group (against the new ACTIVE cluster2).
+ * After restarts and fails back, client can connect to this HA group (against cluster 1).
+ */
+ @Test(timeout = 300000)
+ public void testConnectionWhenActiveHBaseRestarts() throws Exception {
+ // This creates the cqsi for the active cluster upfront.
+ // If we don't do that then later when we try to transition
+ // the cluster role it tries to create cqsi for the cluster
+ // which is down and that takes forever causing timeouts
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster1(), () -> {
+ try {
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ fail("Should have failed since ACTIVE ZK cluster was shutdown");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when ACTIVE ZK cluster is down", e);
+ }
+
+ // So on-call engineer comes into play, and triggers a failover
+ // Because cluster1 is down, new version record will only be updated in cluster2
+ CLUSTERS.transitClusterRole(failoverHAGroup, ClusterRoleRecord.ClusterRole.STANDBY, ClusterRoleRecord.ClusterRole.ACTIVE);
+
+ // After failover, the FailoverPhoenixConnection should go to the second cluster
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ });
+
+ LOG.info("Testing failover connection when both clusters are up and running");
+ try (Connection conn = getFailoverConnection()) {
+ FailoverPhoenixConnection failoverConn = conn.unwrap(FailoverPhoenixConnection.class);
+ assertEquals(CLUSTERS.getJdbcUrl2(failoverHAGroup), failoverConn.getWrappedConnection().getURL());
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+
+ LOG.info("Testing failover back to cluster1 when bot clusters are up and running");
+ // Failover back to the first cluster since it is healthy after restart
+ CLUSTERS.transitClusterRole(failoverHAGroup, ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ // After ACTIVE ZK restarts and fail back, this should still work
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ }
+
+ /**
+ * Tests the scenario where STANDBY HBase cluster restarts.
+ *
+ * When STANDBY HBase cluster shutdown, client can still connect to this HA group.
+ * After failover, client can not connect to this HA group (ACTIVE cluster 2 is down).
+ * After cluster 2 (ACTIVE) restarts, client can connect to this HA group.
+ */
+ @Test(timeout = 300000)
+ public void testConnectionWhenStandbyHBaseRestarts() throws Exception {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+
+ // Innocent on-call engineer triggers a failover to second cluster
+ CLUSTERS.transitClusterRole(failoverHAGroup, ClusterRoleRecord.ClusterRole.STANDBY, ClusterRoleRecord.ClusterRole.ACTIVE);
+
+ try {
+ getFailoverConnection();
+ fail("Should have failed since ACTIVE HBase cluster was shutdown");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when ACTIVE HBase cluster {} was shutdown",
+ CLUSTERS.getZkUrl2(), e);
+ }
+ });
+
+ /* As restarting HBase minicluster it changes the port of HMasters need to refresh the CRR */
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(failoverHAGroup,
+ ClusterRoleRecord.ClusterRole.STANDBY, ClusterRoleRecord.ClusterRole.ACTIVE);
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ }
+
+ /**
+ * Tests the scenario where two HBase clusters both restart.
+ *
+ * Client can not connect to this HA group when two HBase clusters are both down.
+ * When STANDBY HBase cluster2 first restarts, client still can not connect to this HA group.
+ * After failover, client can connect to this HA group because cluster 2 is ACTIVE and healthy.
+ */
+ @Test(timeout = 300000)
+ public void testConnectionWhenTwoHBaseRestarts() throws Exception {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster1(), () -> {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
+ try {
+ getFailoverConnection();
+ fail("Should have failed since ACTIVE HBase cluster was shutdown");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when both clusters are down", e);
+ }
+ });
+
+ // Client cannot connect to HA group because cluster 2 is still STANDBY after restarted
+ try {
+ getFailoverConnection();
+ fail("Should have failed since ACTIVE HBase cluster was shutdown");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when ACTIVE HBase cluster {} was shutdown",
+ CLUSTERS.getZkUrl2(), e);
+ }
+
+ // So on-call engineer comes into play, and triggers a failover
+ CLUSTERS.transitClusterRole(failoverHAGroup, ClusterRoleRecord.ClusterRole.STANDBY, ClusterRoleRecord.ClusterRole.ACTIVE);
+
+ // After the second cluster (ACTIVE) HBase restarts, this should still work
+ try (Connection conn = getFailoverConnection()) {
+ doTestBasicOperationsWithConnection(conn, tableName, failoverHAGroupName);
+ }
+ });
+ }
+
+ /**
+ * Testing connection closure for roleRecord change from
+ * (URL1, ACTIVE, URL2, STANDBY) -> (URL3, ACTIVE, URL2, STANDBY)
+ * All wrapped connections should have been closed
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterActiveURLChange() throws Exception {
+ short numberOfConnections = 5;
+ //Create FailoverPhoenixConnections and ParallelPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ List<Connection> parallelConnectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getFailoverConnection());
+ parallelConnectionList.add(getParallelConnection());
+ }
+ //url of cluster which is being restarted
+ String url = CLUSTERS.getJdbcUrl1(parallelHAGroup);
+ //Restart Cluster 1 with new ports
+ CLUSTERS.restartCluster1();
+ //Basically applying new url for cluster 1
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(failoverHAGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(parallelHAGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+ conn.close();
+
+ ParallelPhoenixConnection conn2 = ((ParallelPhoenixConnection) parallelConnectionList.get(i));
+ assertFalse(conn2.isClosed());
+ //Only connections to cluster 1 should be closed
+ if (conn2.futureConnection1.get().getURL().equals(url)) {
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ assertFalse(conn2.futureConnection2.get().isClosed());
+ } else {
+ assertTrue(conn2.futureConnection2.get().isClosed());
+ assertFalse(conn2.futureConnection1.get().isClosed());
+ }
+ conn2.close();
+ }
+ }
+
+ /**
+ * Testing connection closure for roleRecord change from
+ * (URL1, ACTIVE, URL2, STANDBY) -> (URL1, ACTIVE, URL3, STANDBY)
+ * It should not have affected connections at all
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsNotClosedAfterStandbyURLChange() throws Exception {
+ short numberOfConnections = 5;
+ //Create FailoverPhoenixConnections and ParallelPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ List<Connection> parallelConnectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getFailoverConnection());
+ parallelConnectionList.add(getParallelConnection());
+ }
+
+ //url of cluster which is being restarted
+ String url = CLUSTERS.getJdbcUrl2(parallelHAGroup);
+ //Restart Cluster 2 with new ports
+ CLUSTERS.restartCluster2();
+ //Basically applying new url for cluster 2
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(failoverHAGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ CLUSTERS.refreshClusterRoleRecordAfterClusterRestart(parallelHAGroup,
+ ClusterRoleRecord.ClusterRole.ACTIVE, ClusterRoleRecord.ClusterRole.STANDBY);
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertFalse(conn.getWrappedConnection().isClosed());
+ conn.close();
+
+ ParallelPhoenixConnection conn2 = ((ParallelPhoenixConnection) parallelConnectionList.get(i));
+ assertFalse(conn2.isClosed());
+ //Only connections to cluster 2 should be closed
+ if (conn2.futureConnection1.get().getURL().equals(url)) {
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ assertFalse(conn2.futureConnection2.get().isClosed());
+ } else {
+ assertTrue(conn2.futureConnection2.get().isClosed());
+ assertFalse(conn2.futureConnection1.get().isClosed());
+ }
+ conn2.close();
+ }
+ }
+
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR.
+ * MASTER --> ZK
+ * RPC --> MASTER
+ *
+ * Test with many connections.
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterRegistryChange() throws Exception {
+ short numberOfConnections = 5;
+ //Create FailoverPhoenixConnections and ParallelPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ List<Connection> parallelConnectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getFailoverConnection());
+ parallelConnectionList.add(getParallelConnection());
+ }
+
+ ClusterRoleRecord.RegistryType newRegistry;
+ if (registryType == RegistryType.MASTER) {
+ newRegistry = RegistryType.ZK;
+ } else {
+ newRegistry = RegistryType.MASTER;
+ }
+
+ CLUSTERS.transitClusterRoleRecordRegistry(failoverHAGroup, newRegistry);
+ CLUSTERS.transitClusterRoleRecordRegistry(parallelHAGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+
+ ParallelPhoenixConnection conn2 = ((ParallelPhoenixConnection) parallelConnectionList.get(i));
+ assertFalse(conn2.isClosed());
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ conn2.close();
+ }
+ }
+
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR.
+ * MASTER --> RPC
+ * RPC --> ZK
+ *
+ * Test with many connections.
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterRegistryChange2() throws Exception {
+ short numberOfConnections = 5;
+ //Create FailoverPhoenixConnections and ParallelPhoenixConnections with default urls
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ List<Connection> parallelConnectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getFailoverConnection());
+ parallelConnectionList.add(getParallelConnection());
+ }
+
+ ClusterRoleRecord.RegistryType newRegistry;
+ if (registryType == RegistryType.MASTER) {
+ newRegistry = RegistryType.RPC;
+ } else {
+ newRegistry = RegistryType.ZK;
+ }
+
+ CLUSTERS.transitClusterRoleRecordRegistry(failoverHAGroup, newRegistry);
+ CLUSTERS.transitClusterRoleRecordRegistry(parallelHAGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ FailoverPhoenixConnection conn = ((FailoverPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.getWrappedConnection().isClosed());
+
+ ParallelPhoenixConnection conn2 = ((ParallelPhoenixConnection) parallelConnectionList.get(i));
+ assertFalse(conn2.isClosed());
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ assertTrue(conn2.futureConnection1.get().isClosed());
+ conn2.close();
+ }
+ }
+
+
+ /**
+ * Create a failover connection using {@link #failoverClientProperties}.
+ */
+ private Connection getFailoverConnection() throws SQLException {
+ return DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), failoverClientProperties);
+ }
+
+ /**
+ * Returns a Parallel Phoenix Connection
+ * @return Parallel Phoenix Connection
+ * @throws SQLException
+ */
+ private Connection getParallelConnection() throws SQLException {
+ return DriverManager.getConnection(CLUSTERS.getJdbcHAUrl(), parallelClientProperties);
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroup2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroup2IT.java
new file mode 100644
index 0000000000..7f5d9fa1aa
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroup2IT.java
@@ -0,0 +1,380 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.jdbc;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.curator.utils.ZKPaths;
+import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+import org.junit.rules.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.hadoop.test.GenericTestUtils.waitFor;
+import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_ESTABLISH_CONNECTION;
+import static org.apache.phoenix.jdbc.HighAvailabilityGroup.*;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneHBaseDown;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneZKDown;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class HighAvailabilityGroup2IT {
+ private static final Logger LOG = LoggerFactory.getLogger(HighAvailabilityGroup2IT.class);
+ private static final HighAvailabilityTestingUtility.HBaseTestingUtilityPair CLUSTERS = new HighAvailabilityTestingUtility.HBaseTestingUtilityPair();
+
+ /** Client properties to create a connection per test. */
+ private Properties clientProperties;
+ /** JDBC connection string for this test HA group. */
+ private String jdbcHAUrl;
+ /** Failover HA group for to test. */
+ private HighAvailabilityGroup haGroup;
+ private HAURLInfo haURLInfo;
+ /** HA Group name for this test. */
+ private String haGroupName;
+
+ @Rule
+ public final TestName testName = new TestName();
+ @Rule
+ public final Timeout globalTimeout = new Timeout(180, TimeUnit.SECONDS);
+ private final ClusterRoleRecord.RegistryType registryType = ClusterRoleRecord.RegistryType.ZK;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ CLUSTERS.start();
+ DriverManager.registerDriver(PhoenixDriver.INSTANCE);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ HighAvailabilityGroup.CURATOR_CACHE.invalidateAll();
+ DriverManager.deregisterDriver(PhoenixDriver.INSTANCE);
+ CLUSTERS.close();
+ }
+
+ @Before
+ public void setup() throws Exception {
+ haGroupName = testName.getMethodName();
+ clientProperties = HighAvailabilityTestingUtility.getHATestProperties();
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName);
+
+ // Make first cluster ACTIVE
+ CLUSTERS.initClusterRole(haGroupName, HighAvailabilityPolicy.FAILOVER);
+ jdbcHAUrl = CLUSTERS.getJdbcHAUrl();
+ haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup = getHighAvailibilityGroup(jdbcHAUrl,clientProperties);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ haGroup.close();
+ try {
+ PhoenixDriver.INSTANCE
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), haGroup.getProperties())
+ .close();
+ PhoenixDriver.INSTANCE
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(haGroup), haGroup.getProperties())
+ .close();
+ } catch (Exception e) {
+ LOG.error("Fail to tear down the HA group and the CQS. Will ignore", e);
+ }
+ }
+
+
+
+
+ /**
+ * Test that if STANDBY HBase cluster is down, the connect should work.
+ */
+ @Test
+ public void testCanConnectWhenStandbyHBaseClusterDown() throws Exception {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
+ // HA group is already initialized
+ Connection connection = haGroup.connect(clientProperties, haURLInfo);
+ assertNotNull(connection);
+ assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
+ });
+ }
+
+ /**
+ * Test that if STANDBY ZK cluster is down, the connect should work.
+ *
+ * This differs from {@link #testCanConnectWhenStandbyHBaseClusterDown} because this stops the
+ * ZK cluster, not the HBase cluster.
+ */
+ @Test
+ public void testCanConnectWhenStandbyZKClusterDown() throws Exception {
+ doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
+ // Clear the HA Cache
+ HighAvailabilityGroup.CURATOR_CACHE.invalidateAll();
+
+ // HA group is already initialized
+ Connection connection = haGroup.connect(clientProperties, haURLInfo);
+ assertNotNull(connection);
+ assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
+ });
+ }
+
+ /**
+ * Test that if STANDBY HBase cluster is down, connect to new HA group should work.
+ *
+ * This test covers only HBase cluster is down, and both ZK clusters are still healthy so
+ * clients will be able to get latest clusters role record from both clusters. This tests a new
+ * HA group which will get initialized during the STANDBY HBase cluster down time.
+ */
+ @Test
+ public void testCanConnectNewGroupWhenStandbyHBaseClusterDown() throws Exception {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
+ // get and initialize a new HA group when cluster2 is down
+ String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+ CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+ Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
+ try {
+ HAURLInfo haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
+ assertTrue(haGroup2.isPresent());
+ assertNotSame(haGroup2.get(), haGroup);
+ // get a new connection in this new HA group; should be pointing to ACTIVE cluster1
+ try (Connection connection = haGroup2.get().connect(clientProperties, haURLInfo)) {
+ assertNotNull(connection);
+ assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
+ }
+ } finally {
+ haGroup2.ifPresent(HighAvailabilityGroup::close);
+ }
+ });
+ }
+
+ /**
+ * Test that if STANDBY cluster ZK service is down, connect to new HA group should work.
+ *
+ * This differs from {@link #testCanConnectNewGroupWhenStandbyHBaseClusterDown} because this is
+ * testing scenarios when STANDBY ZK cluster is down.
+ */
+ @Test
+ public void testCanConnectNewGroupWhenStandbyZKClusterDown() throws Exception {
+ // get and initialize a new HA group when cluster2 is down
+ String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+ CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+
+ doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
+ Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
+ try {
+ HAURLInfo haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
+ assertTrue(haGroup2.isPresent());
+ assertNotSame(haGroup2.get(), haGroup);
+ // get a new connection in this new HA group; should be pointing to ACTIVE cluster1
+ Connection connection = haGroup2.get().connect(clientProperties, haURLInfo);
+ assertNotNull(connection);
+ assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
+ } finally {
+ haGroup2.ifPresent(HighAvailabilityGroup::close);
+ }
+ });
+ }
+
+ /**
+ * Test it can not establish active connection to the ACTIVE HBase cluster if it is down.
+ */
+ @Test
+ public void testCanNotEstablishConnectionWhenActiveHBaseClusterDown() throws Exception {
+ doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster1(), () -> {
+ try {
+ haGroup.connectActive(clientProperties, haURLInfo);
+ fail("Should have failed because ACTIVE HBase cluster is down.");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when ACTIVE HBase cluster is down", e);
+ assertEquals(CANNOT_ESTABLISH_CONNECTION.getErrorCode(), e.getErrorCode());
+ }
+ });
+ }
+
+ /**
+ * Test that client can not establish connection to when the ACTIVE ZK cluster is down,
+ * while client can establish active connection after active ZK cluster restarts.
+ *
+ * This differs from the {@link #testCanNotEstablishConnectionWhenActiveHBaseClusterDown()}
+ * because this is for ZK cluster down while the other is for HBase cluster down.
+ */
+ @Test
+ public void testConnectActiveWhenActiveZKClusterRestarts() throws Exception {
+ doTestWhenOneZKDown(CLUSTERS.getHBaseCluster1(), () -> {
+ try {
+ haGroup.connectActive(clientProperties, haURLInfo);
+ fail("Should have failed because of ACTIVE ZK cluster is down.");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when ACTIVE ZK cluster is down", e);
+ assertEquals(CANNOT_ESTABLISH_CONNECTION.getErrorCode(), e.getErrorCode());
+ }
+ });
+
+ try (Connection conn = haGroup.connectActive(clientProperties, haURLInfo)) {
+ assertNotNull(conn);
+ LOG.info("Successfully connect to HA group {} after restarting ACTIVE ZK", haGroup);
+ } // all other exceptions will fail the test
+ }
+
+ /**
+ * Test when one ZK starts after the HA group has been initialized.
+ *
+ * In this case, both cluster role managers will start and apply discovered cluster role record.
+ */
+ @Test
+ public void testOneZKStartsAfterInit() throws Exception {
+ String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+
+ // create cluster role records with different versions on two ZK clusters
+ final String zpath = ZKPaths.PATH_SEPARATOR + haGroupName2;
+ ClusterRoleRecord record1 = new ClusterRoleRecord(
+ haGroupName2, HighAvailabilityPolicy.FAILOVER, registryType,
+ CLUSTERS.getURL(1, registryType), ClusterRoleRecord.ClusterRole.ACTIVE,
+ CLUSTERS.getURL(2, registryType), ClusterRoleRecord.ClusterRole.STANDBY,
+ 1);
+ CLUSTERS.createCurator1().create().forPath(zpath, ClusterRoleRecord.toJson(record1));
+ ClusterRoleRecord record2 = new ClusterRoleRecord(
+ record1.getHaGroupName(), record1.getPolicy(), record1.getRegistryType(),
+ record1.getUrl1(), record1.getRole1(),
+ record1.getUrl2(), record1.getRole2(),
+ record1.getVersion() + 1); // record2 is newer
+ CLUSTERS.createCurator2().create().forPath(zpath, ClusterRoleRecord.toJson(record2));
+
+ doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
+ Optional<HighAvailabilityGroup> haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
+ assertTrue(haGroup2.isPresent());
+ assertNotSame(haGroup2.get(), haGroup);
+ // apparently the HA group cluster role record should be from the healthy cluster
+ assertEquals(record1, haGroup2.get().getRoleRecord());
+ });
+
+ // When ZK2 is connected, its cluster role manager should apply newer cluster role record
+ waitFor(() -> {
+ try {
+ Optional<HighAvailabilityGroup> haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
+ return haGroup2.isPresent() && record2.equals(haGroup2.get().getRoleRecord());
+ } catch (SQLException e) {
+ LOG.warn("Fail to get HA group {}", haGroupName2);
+ return false;
+ }
+ }, 100, 30_000);
+
+ // clean up HA group 2
+ HighAvailabilityGroup.get(jdbcHAUrl, clientProperties).ifPresent(HighAvailabilityGroup::close);
+ }
+
+ /**
+ * Test that HA connection request will fall back to the first cluster when HA group fails
+ * to initialize due to missing cluster role record (CRR).
+ */
+ @Test
+ public void testFallbackToSingleConnection() throws Exception {
+ final String tableName = RandomStringUtils.randomAlphabetic(10);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
+
+ String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+ clientProperties.setProperty(PHOENIX_HA_FALLBACK_CLUSTER_KEY, CLUSTERS.getJdbcUrl1(haGroup));
+ // no cluster role record for the HA group with name haGroupName2
+ try (Connection conn = DriverManager.getConnection(jdbcHAUrl, clientProperties)) {
+ // connection is PhoenixConnection instead of HA connection (failover or parallel)
+ assertTrue(conn instanceof PhoenixConnection);
+ // Deterministically talking to the first cluster: first means "smaller" URL
+ String firstClusterUrl = CLUSTERS.getJdbcUrl1(haGroup);
+ assertEquals(firstClusterUrl, ((PhoenixConnection) conn).getURL());
+ doTestBasicOperationsWithConnection(conn, tableName, haGroupName2);
+ }
+
+ // disable fallback feature even if the cluster role record is missing for this group
+ clientProperties.setProperty(PHOENIX_HA_SHOULD_FALLBACK_WHEN_MISSING_CRR_KEY, "false");
+ try {
+ DriverManager.getConnection(jdbcHAUrl, clientProperties);
+ fail("Should have failed when disabling fallback to single cluster");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception when disabling fallback");
+ }
+ clientProperties.remove(PHOENIX_HA_SHOULD_FALLBACK_WHEN_MISSING_CRR_KEY);
+
+ clientProperties.remove(PHOENIX_HA_FALLBACK_CLUSTER_KEY);
+ //If we don't have a fallback cluster key then connection creation should fail
+ try {
+ DriverManager.getConnection(jdbcHAUrl, clientProperties);
+ fail("Should have failed when fallback cluster key is missing");
+ } catch (SQLException e) {
+ LOG.info("Should have failed when fallback cluster key is missing");
+ }
+
+
+ // Now create the cluster role record
+ CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
+ // And invalidate the negative cache. We are doing it manually because the default time for
+ // expireAfterWrite is too long for testing. We do not need to test the cache per se.
+ HighAvailabilityGroup.MISSING_CRR_GROUPS_CACHE.invalidateAll();
+
+ // After it is expired in the negative cache, the HA group will start serving HA connections
+ try (Connection conn = DriverManager.getConnection(jdbcHAUrl, clientProperties)) {
+ assertTrue(conn instanceof FailoverPhoenixConnection);
+ doTestBasicOperationsWithConnection(conn, tableName, haGroupName2);
+ }
+ }
+
+ /**
+ * Test that HA connection request will not fall back to the first cluster when one ZK is down.
+ */
+ @Test
+ public void testNotFallbackToSingleConnection() throws Exception {
+ final String tableName = RandomStringUtils.randomAlphabetic(10);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
+ String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
+ clientProperties.setProperty(PHOENIX_HA_FALLBACK_CLUSTER_KEY, CLUSTERS.getJdbcUrl1(haGroup));
+
+ doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
+ try {
+ DriverManager.getConnection(jdbcHAUrl, clientProperties);
+ fail("Should have failed since one HA group can not initialized. Not falling back");
+ } catch (SQLException e) {
+ LOG.info("Got expected exception as HA group fails to initialize", e);
+ }
+ });
+
+ // After cluster 2 is up and running again, fallback to single cluster will work
+ try (Connection conn = DriverManager.getConnection(jdbcHAUrl, clientProperties)) {
+ // connection is PhoenixConnection instead of HA connection (failover or parallel)
+ assertTrue(conn instanceof PhoenixConnection);
+ }
+ }
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupIT.java
index 9acad37044..b13a84a4f0 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupIT.java
@@ -20,7 +20,6 @@ package org.apache.phoenix.jdbc;
import static org.apache.hadoop.test.GenericTestUtils.waitFor;
import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_ESTABLISH_CONNECTION;
import static org.apache.phoenix.jdbc.HighAvailabilityGroup.*;
-import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneHBaseDown;
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneZKDown;
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
@@ -37,7 +36,8 @@ import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
-import java.util.Map;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
@@ -76,7 +76,7 @@ public class HighAvailabilityGroupIT {
/** Client properties to create a connection per test. */
private Properties clientProperties;
/** JDBC connection string for this test HA group. */
- private String jdbcUrl;
+ private String jdbcHAUrl;
/** Failover HA group for to test. */
private HighAvailabilityGroup haGroup;
private HAURLInfo haURLInfo;
@@ -87,6 +87,7 @@ public class HighAvailabilityGroupIT {
public final TestName testName = new TestName();
@Rule
public final Timeout globalTimeout = new Timeout(180, TimeUnit.SECONDS);
+ private final ClusterRoleRecord.RegistryType registryType = ClusterRoleRecord.RegistryType.ZK;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@@ -109,9 +110,9 @@ public class HighAvailabilityGroupIT {
// Make first cluster ACTIVE
CLUSTERS.initClusterRole(haGroupName, HighAvailabilityPolicy.FAILOVER);
- jdbcUrl = CLUSTERS.getJdbcHAUrl();
- haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcUrl, clientProperties);
- haGroup = getHighAvailibilityGroup(jdbcUrl,clientProperties);
+ jdbcHAUrl = CLUSTERS.getJdbcHAUrl();
+ haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup = getHighAvailibilityGroup(jdbcHAUrl,clientProperties);
}
@After
@@ -119,10 +120,10 @@ public class HighAvailabilityGroupIT {
haGroup.close();
try {
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), haGroup.getProperties())
.close();
PhoenixDriver.INSTANCE
- .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(), haGroup.getProperties())
+ .getConnectionQueryServices(CLUSTERS.getJdbcUrl2(haGroup), haGroup.getProperties())
.close();
} catch (Exception e) {
LOG.error("Fail to tear down the HA group and the CQS. Will ignore", e);
@@ -137,7 +138,7 @@ public class HighAvailabilityGroupIT {
// Client will get the same HighAvailabilityGroup using the same information as key
Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
try {
- haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup2.isPresent());
assertSame(haGroup, haGroup2.get());
} finally {
@@ -150,7 +151,7 @@ public class HighAvailabilityGroupIT {
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName3);
Optional<HighAvailabilityGroup> haGroup3 = Optional.empty();
try {
- haGroup3 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ haGroup3 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup3.isPresent());
assertNotSame(haGroup, haGroup3.get());
} finally {
@@ -161,7 +162,7 @@ public class HighAvailabilityGroupIT {
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroup.getGroupInfo().getName());
Optional<HighAvailabilityGroup> haGroup4 = Optional.empty();
try {
- haGroup4 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ haGroup4 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup4.isPresent());
assertSame(haGroup, haGroup4.get());
} finally {
@@ -178,10 +179,7 @@ public class HighAvailabilityGroupIT {
public void testGetWithDifferentPrincipals() throws Exception {
//Client will get same HAGroup if we have difference in principal only but JDBCURLs should have different
//principals
- assertEquals(CLUSTERS.getJdbcUrl1(), haGroup.getGroupInfo().getJDBCUrl(CLUSTERS.getUrl1(), haURLInfo));
- assertEquals(CLUSTERS.getJdbcUrl2(), haGroup.getGroupInfo().getJDBCUrl(CLUSTERS.getUrl2(), haURLInfo));
- assertEquals(CLUSTERS.getJdbcHAUrl(), haGroup.getGroupInfo().
- getJDBCUrl(String.format("[%s|%s]", CLUSTERS.getUrl1(), CLUSTERS.getUrl2()), haURLInfo));
+ assertJDBCUrlForGivenHAGroup(haGroup, haURLInfo, null);
//Try creating new HAGroup with same params except Principal
Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
@@ -196,12 +194,7 @@ public class HighAvailabilityGroupIT {
//URLs we are getting for haGroup2 should have newer principal i.e. Current HAURLInfo should have new
//principal instead default PRINCIPAL
- assertEquals(CLUSTERS.getJdbcUrl(CLUSTERS.getUrl1(), principal),
- haGroup2.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl1(), haURLInfo2));
- assertEquals(CLUSTERS.getJdbcUrl(CLUSTERS.getUrl2(), principal),
- haGroup2.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl2(), haURLInfo2));
- assertEquals(CLUSTERS.getJdbcHAUrl(principal), haGroup2.get().getGroupInfo().
- getJDBCUrl(String.format("[%s|%s]", CLUSTERS.getUrl1(), CLUSTERS.getUrl2()), haURLInfo2));
+ assertJDBCUrlForGivenHAGroup(haGroup2.get(), haURLInfo2, principal);
} finally {
haGroup2.ifPresent(HighAvailabilityGroup::close);
}
@@ -214,20 +207,15 @@ public class HighAvailabilityGroupIT {
Optional<HighAvailabilityGroup> haGroup3 = Optional.empty();
Optional<HighAvailabilityGroup> haGroup4 = Optional.empty();
try {
- HAURLInfo haurlInfo3 = HighAvailabilityGroup.getUrlInfo(jdbcUrl, clientProperties);
- haGroup3 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ HAURLInfo haurlInfo3 = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup3 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup3.isPresent());
assertNotSame(haGroup, haGroup3.get());
assertNotSame(haGroup.getGroupInfo(), haGroup3.get().getGroupInfo());
//URLs we are getting for haGroup3 should have same principal as default PRINCIPAL.
- assertEquals(CLUSTERS.getJdbcUrl1(),
- haGroup3.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl1(), haurlInfo3));
- assertEquals(CLUSTERS.getJdbcUrl2(),
- haGroup3.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl2(), haurlInfo3));
- assertEquals(CLUSTERS.getJdbcHAUrl(), haGroup3.get().getGroupInfo().
- getJDBCUrl(String.format("[%s|%s]", CLUSTERS.getUrl1(), CLUSTERS.getUrl2()), haurlInfo3));
+ assertJDBCUrlForGivenHAGroup(haGroup3.get(), haurlInfo3, null);
// should get same ha Group without principal
String haUrl4 = CLUSTERS.getJdbcHAUrlWithoutPrincipal();
@@ -260,12 +248,7 @@ public class HighAvailabilityGroupIT {
//URLs we are getting for haGroup4 should have newer principal i.e. Current HAURLInfo should have new
//principal instead default PRINCIPAL
- assertEquals(CLUSTERS.getJdbcUrl(CLUSTERS.getUrl1(), principal),
- haGroup4.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl1(), haURLInfo5));
- assertEquals(CLUSTERS.getJdbcUrl(CLUSTERS.getUrl2(), principal),
- haGroup4.get().getGroupInfo().getJDBCUrl(CLUSTERS.getUrl2(), haURLInfo5));
- assertEquals(CLUSTERS.getJdbcHAUrl(principal), haGroup4.get().getGroupInfo().
- getJDBCUrl(String.format("[%s|%s]", CLUSTERS.getUrl1(), CLUSTERS.getUrl2()), haURLInfo5));
+ assertJDBCUrlForGivenHAGroup(haGroup5.get(), haURLInfo5, principal);
} finally {
haGroup5.ifPresent(HighAvailabilityGroup::close);
@@ -301,8 +284,8 @@ public class HighAvailabilityGroupIT {
Optional<HighAvailabilityGroup> haGroup3 = Optional.empty();
Optional<HighAvailabilityGroup> haGroup4 = Optional.empty();
try {
- HAURLInfo haurlInfo3 = HighAvailabilityGroup.getUrlInfo(jdbcUrl, clientProperties);
- haGroup3 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ HAURLInfo haurlInfo3 = HighAvailabilityGroup.getUrlInfo(jdbcHAUrl, clientProperties);
+ haGroup3 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup3.isPresent());
assertNotSame(haGroup, haGroup3.get());
assertNotSame(haGroup.getGroupInfo(), haGroup3.get().getGroupInfo());
@@ -359,21 +342,21 @@ public class HighAvailabilityGroupIT {
// create cluster role records with different versions on two ZK clusters
final String zpath = ZKPaths.PATH_SEPARATOR + haGroupName2;
ClusterRoleRecord record1 = new ClusterRoleRecord(
- haGroupName2, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.ACTIVE,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
+ haGroupName2, HighAvailabilityPolicy.FAILOVER, registryType,
+ CLUSTERS.getURL(1, registryType), ClusterRole.ACTIVE,
+ CLUSTERS.getURL(2, registryType), ClusterRole.STANDBY,
1);
CLUSTERS.createCurator1().create().forPath(zpath, ClusterRoleRecord.toJson(record1));
ClusterRoleRecord record2 = new ClusterRoleRecord(
- record1.getHaGroupName(), record1.getPolicy(),
- record1.getZk1(), record1.getRole1(),
- record1.getZk2(), record1.getRole2(),
+ record1.getHaGroupName(), record1.getPolicy(), record1.getRegistryType(),
+ record1.getUrl1(), record1.getRole1(),
+ record1.getUrl2(), record1.getRole2(),
record1.getVersion() + 1); // record2 is newer
CLUSTERS.createCurator2().create().forPath(zpath, ClusterRoleRecord.toJson(record2));
Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
try {
- haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ haGroup2 = HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
assertTrue(haGroup2.isPresent());
assertNotSame(haGroup2.get(), haGroup);
// HA group should see latest version when both role managers are started
@@ -403,7 +386,7 @@ public class HighAvailabilityGroupIT {
doTestWhenOneZKDown(CLUSTERS.getHBaseCluster1(), () -> {
HighAvailabilityGroup haGroup2 = null;
try {
- haGroup2 = getHighAvailibilityGroup(jdbcUrl, clientProperties);
+ haGroup2 = getHighAvailibilityGroup(jdbcHAUrl, clientProperties);
LOG.info("Can get the new HA group {} after both ZK clusters restart", haGroup2);
} finally {
if (haGroup2 != null) {
@@ -432,7 +415,7 @@ public class HighAvailabilityGroupIT {
doTestWhenOneZKDown(CLUSTERS.getHBaseCluster1(), () ->
doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
try {
- HighAvailabilityGroup.get(jdbcUrl, clientProperties);
+ HighAvailabilityGroup.get(jdbcHAUrl, clientProperties);
fail("Should have failed because both ZK cluster were shutdown!");
} catch (SQLException e) {
LOG.info("Got expected SQLException because both ZK clusters are down", e);
@@ -444,7 +427,7 @@ public class HighAvailabilityGroupIT {
HighAvailabilityGroup haGroup2 = null;
try {
- haGroup2 = getHighAvailibilityGroup(jdbcUrl, clientProperties);
+ haGroup2 = getHighAvailibilityGroup(jdbcHAUrl, clientProperties);
LOG.info("Can get the new HA group {} after both ZK clusters restart", haGroup2);
} finally {
if (haGroup2 != null) {
@@ -478,7 +461,7 @@ public class HighAvailabilityGroupIT {
public void testGetShouldFailWithoutClusterRoleData() throws SQLException {
String invalidHaGroupName = testName.getMethodName() + RandomStringUtils.randomAlphanumeric(3);
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, invalidHaGroupName);
- assertFalse(HighAvailabilityGroup.get(jdbcUrl, clientProperties).isPresent());
+ assertFalse(HighAvailabilityGroup.get(jdbcHAUrl, clientProperties).isPresent());
}
/**
@@ -486,7 +469,7 @@ public class HighAvailabilityGroupIT {
*/
@Test
public void testGetShouldFailWithNonHAJdbcString() {
- final String oldJdbcString = CLUSTERS.getJdbcUrl1();
+ final String oldJdbcString = CLUSTERS.getJdbcUrl1(haGroup);
try {
HighAvailabilityGroup.get(oldJdbcString, clientProperties);
fail("Should have failed with invalid connection string '" + oldJdbcString + "'");
@@ -511,7 +494,7 @@ public class HighAvailabilityGroupIT {
*/
@Test
public void testConnectToOneCluster() throws SQLException {
- final String url = CLUSTERS.getJdbcUrl1();
+ final String url = CLUSTERS.getJdbcUrl1(haGroup);
PhoenixConnection connection = haGroup.connectToOneCluster(url, clientProperties, haURLInfo);
assertEquals(url, connection.getURL());
@@ -527,7 +510,7 @@ public class HighAvailabilityGroupIT {
try {
haGroup.connectToOneCluster(randomHostUrl, clientProperties, haURLInfo);
fail("Should have failed since '" + randomHostUrl + "' is not in HA group " + haGroup);
- } catch (IllegalArgumentException e) {
+ } catch (SQLException e) {
LOG.info("Got expected exception with invalid host url '{}'", randomHostUrl, e);
}
}
@@ -542,11 +525,10 @@ public class HighAvailabilityGroupIT {
*/
@Test
public void testConnectToOneClusterAfterZKRestart() throws Exception {
- final String tableName = testName.getMethodName();
- CLUSTERS.createTableOnClusterPair(tableName);
+ final String tableName = RandomStringUtils.randomAlphabetic(10);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
- final String url1 = CLUSTERS.getUrl1();
- final String jdbcUrlToCluster1 = CLUSTERS.getJdbcUrl1();
+ final String jdbcUrlToCluster1 = CLUSTERS.getJdbcUrl1(haGroup);
doTestWhenOneZKDown(CLUSTERS.getHBaseCluster1(), () -> {
try {
DriverManager.getConnection(jdbcUrlToCluster1);
@@ -570,9 +552,9 @@ public class HighAvailabilityGroupIT {
*/
@Test
public void testIsConnectionActive() throws Exception {
- PhoenixConnection conn1 = haGroup.connectToOneCluster(CLUSTERS.getUrl1(), clientProperties, haURLInfo);
+ PhoenixConnection conn1 = haGroup.connectToOneCluster(CLUSTERS.getJdbcUrl1(haGroup), clientProperties, haURLInfo);
assertTrue(haGroup.isActive(conn1));
- PhoenixConnection conn2 = haGroup.connectToOneCluster(CLUSTERS.getUrl2(), clientProperties, haURLInfo);
+ PhoenixConnection conn2 = haGroup.connectToOneCluster(CLUSTERS.getJdbcUrl2(haGroup), clientProperties, haURLInfo);
assertFalse(haGroup.isActive(conn2));
CLUSTERS.transitClusterRole(haGroup, ClusterRole.STANDBY, ClusterRole.ACTIVE);
@@ -586,267 +568,47 @@ public class HighAvailabilityGroupIT {
*/
@Test
public void testNodeChange() throws Exception {
- assertEquals(ClusterRole.ACTIVE, haGroup.getRoleRecord().getRole(CLUSTERS.getUrl1()));
- assertEquals(ClusterRole.STANDBY, haGroup.getRoleRecord().getRole(CLUSTERS.getUrl2()));
+ assertEquals(ClusterRole.ACTIVE, haGroup.getRoleRecord().getRole(CLUSTERS.getURL(1, registryType)));
+ assertEquals(ClusterRole.STANDBY, haGroup.getRoleRecord().getRole(CLUSTERS.getURL(2, registryType)));
CLUSTERS.transitClusterRole(haGroup, ClusterRole.STANDBY, ClusterRole.ACTIVE);
- assertEquals(ClusterRole.STANDBY, haGroup.getRoleRecord().getRole(CLUSTERS.getUrl1()));
- assertEquals(ClusterRole.ACTIVE, haGroup.getRoleRecord().getRole(CLUSTERS.getUrl2()));
+ assertEquals(ClusterRole.STANDBY, haGroup.getRoleRecord().getRole(CLUSTERS.getURL(1, registryType)));
+ assertEquals(ClusterRole.ACTIVE, haGroup.getRoleRecord().getRole(CLUSTERS.getURL(2, registryType)));
}
- /**
- * Test that if STANDBY HBase cluster is down, the connect should work.
- */
- @Test
- public void testCanConnectWhenStandbyHBaseClusterDown() throws Exception {
- doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
- // HA group is already initialized
- Connection connection = haGroup.connect(clientProperties, haURLInfo);
- assertNotNull(connection);
- assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
- });
+ //private helper methods
+ private void assertJDBCUrlForGivenHAGroup(HighAvailabilityGroup haGroup,
+ HAURLInfo haURLInfo, String testPrincipal) {
+ String testUrl1 = testPrincipal == null ? CLUSTERS.getJdbcUrl1(haGroup) :
+ CLUSTERS.getJdbcUrl1(haGroup, testPrincipal);
+ String testUrl2 = testPrincipal == null ? CLUSTERS.getJdbcUrl2(haGroup) :
+ CLUSTERS.getJdbcUrl2(haGroup, testPrincipal);
+ String testHAUrl = testPrincipal == null ? CLUSTERS.getJdbcHAUrl() :
+ CLUSTERS.getJdbcHAUrl(testPrincipal);
+
+ //As roleRecord store url in ascending order it might be the case that minicluster2 have
+ //port smaller than minicluster1 and urls are stored in reverse order.
+ assertTrue(getJdbcUrl1ForGivenHAGroup(haGroup, haURLInfo).equals(testUrl1) ||
+ getJdbcUrl1ForGivenHAGroup(haGroup, haURLInfo).equals(testUrl2));
+ assertTrue(getJdbcUrl2ForGivenHAGroup(haGroup, haURLInfo).equals(testUrl1) ||
+ getJdbcUrl2ForGivenHAGroup(haGroup, haURLInfo).equals(testUrl2));
+ assertEquals(testHAUrl, getJdbcHAUrlForGivenHAGroup(haURLInfo));
}
- /**
- * Test that if STANDBY ZK cluster is down, the connect should work.
- *
- * This differs from {@link #testCanConnectWhenStandbyHBaseClusterDown} because this stops the
- * ZK cluster, not the HBase cluster.
- */
- @Test
- public void testCanConnectWhenStandbyZKClusterDown() throws Exception {
- doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
- // Clear the HA Cache
- HighAvailabilityGroup.CURATOR_CACHE.invalidateAll();
-
- // HA group is already initialized
- Connection connection = haGroup.connect(clientProperties, haURLInfo);
- assertNotNull(connection);
- assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
- });
+ private String getJdbcUrl1ForGivenHAGroup(HighAvailabilityGroup haGroup, HAURLInfo haURLInfo) {
+ return HighAvailabilityGroup.getJDBCUrl(haGroup.getRoleRecord().getUrl1(), haURLInfo,
+ haGroup.getRoleRecord().getRegistryType());
}
- /**
- * Test that if STANDBY HBase cluster is down, connect to new HA group should work.
- *
- * This test covers only HBase cluster is down, and both ZK clusters are still healthy so
- * clients will be able to get latest clusters role record from both clusters. This tests a new
- * HA group which will get initialized during the STANDBY HBase cluster down time.
- */
- @Test
- public void testCanConnectNewGroupWhenStandbyHBaseClusterDown() throws Exception {
- doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
- // get and initialize a new HA group when cluster2 is down
- String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
- clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
- Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
- try {
- HAURLInfo haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcUrl, clientProperties);
- haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
- assertTrue(haGroup2.isPresent());
- assertNotSame(haGroup2.get(), haGroup);
- // get a new connection in this new HA group; should be pointing to ACTIVE cluster1
- try (Connection connection = haGroup2.get().connect(clientProperties, haURLInfo)) {
- assertNotNull(connection);
- assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
- }
- } finally {
- haGroup2.ifPresent(HighAvailabilityGroup::close);
- }
- });
+ private String getJdbcUrl2ForGivenHAGroup(HighAvailabilityGroup haGroup, HAURLInfo haURLInfo) {
+ return HighAvailabilityGroup.getJDBCUrl(haGroup.getRoleRecord().getUrl2(), haURLInfo,
+ haGroup.getRoleRecord().getRegistryType());
}
- /**
- * Test that if STANDBY cluster ZK service is down, connect to new HA group should work.
- *
- * This differs from {@link #testCanConnectNewGroupWhenStandbyHBaseClusterDown} because this is
- * testing scenarios when STANDBY ZK cluster is down.
- */
- @Test
- public void testCanConnectNewGroupWhenStandbyZKClusterDown() throws Exception {
- // get and initialize a new HA group when cluster2 is down
- String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
- clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
-
- doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
- Optional<HighAvailabilityGroup> haGroup2 = Optional.empty();
- try {
- HAURLInfo haURLInfo = HighAvailabilityGroup.getUrlInfo(jdbcUrl, clientProperties);
- haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
- assertTrue(haGroup2.isPresent());
- assertNotSame(haGroup2.get(), haGroup);
- // get a new connection in this new HA group; should be pointing to ACTIVE cluster1
- Connection connection = haGroup2.get().connect(clientProperties, haURLInfo);
- assertNotNull(connection);
- assertNotNull(connection.unwrap(FailoverPhoenixConnection.class));
- } finally {
- haGroup2.ifPresent(HighAvailabilityGroup::close);
- }
- });
- }
-
- /**
- * Test it can not establish active connection to the ACTIVE HBase cluster if it is down.
- */
- @Test
- public void testCanNotEstablishConnectionWhenActiveHBaseClusterDown() throws Exception {
- doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster1(), () -> {
- try {
- haGroup.connectActive(clientProperties, haURLInfo);
- fail("Should have failed because ACTIVE HBase cluster is down.");
- } catch (SQLException e) {
- LOG.info("Got expected exception when ACTIVE HBase cluster is down", e);
- assertEquals(CANNOT_ESTABLISH_CONNECTION.getErrorCode(), e.getErrorCode());
- }
- });
- }
-
- /**
- * Test that client can not establish connection to when the ACTIVE ZK cluster is down,
- * while client can establish active connection after active ZK cluster restarts.
- *
- * This differs from the {@link #testCanNotEstablishConnectionWhenActiveHBaseClusterDown()}
- * because this is for ZK cluster down while the other is for HBase cluster down.
- */
- @Test
- public void testConnectActiveWhenActiveZKClusterRestarts() throws Exception {
- doTestWhenOneZKDown(CLUSTERS.getHBaseCluster1(), () -> {
- try {
- haGroup.connectActive(clientProperties, haURLInfo);
- fail("Should have failed because of ACTIVE ZK cluster is down.");
- } catch (SQLException e) {
- LOG.info("Got expected exception when ACTIVE ZK cluster is down", e);
- assertEquals(CANNOT_ESTABLISH_CONNECTION.getErrorCode(), e.getErrorCode());
- }
- });
-
- try (Connection conn = haGroup.connectActive(clientProperties, haURLInfo)) {
- assertNotNull(conn);
- LOG.info("Successfully connect to HA group {} after restarting ACTIVE ZK", haGroup);
- } // all other exceptions will fail the test
- }
-
- /**
- * Test when one ZK starts after the HA group has been initialized.
- *
- * In this case, both cluster role managers will start and apply discovered cluster role record.
- */
- @Test
- public void testOneZKStartsAfterInit() throws Exception {
- String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
- clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
-
- // create cluster role records with different versions on two ZK clusters
- final String zpath = ZKPaths.PATH_SEPARATOR + haGroupName2;
- ClusterRoleRecord record1 = new ClusterRoleRecord(
- haGroupName2, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.ACTIVE,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
- 1);
- CLUSTERS.createCurator1().create().forPath(zpath, ClusterRoleRecord.toJson(record1));
- ClusterRoleRecord record2 = new ClusterRoleRecord(
- record1.getHaGroupName(), record1.getPolicy(),
- record1.getZk1(), record1.getRole1(),
- record1.getZk2(), record1.getRole2(),
- record1.getVersion() + 1); // record2 is newer
- CLUSTERS.createCurator2().create().forPath(zpath, ClusterRoleRecord.toJson(record2));
-
- doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
- Optional<HighAvailabilityGroup> haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
- assertTrue(haGroup2.isPresent());
- assertNotSame(haGroup2.get(), haGroup);
- // apparently the HA group cluster role record should be from the healthy cluster
- assertEquals(record1, haGroup2.get().getRoleRecord());
- });
-
- // When ZK2 is connected, its cluster role manager should apply newer cluster role record
- waitFor(() -> {
- try {
- Optional<HighAvailabilityGroup> haGroup2 = HighAvailabilityGroup.get(jdbcUrl, clientProperties);
- return haGroup2.isPresent() && record2.equals(haGroup2.get().getRoleRecord());
- } catch (SQLException e) {
- LOG.warn("Fail to get HA group {}", haGroupName2);
- return false;
- }
- }, 100, 30_000);
-
- // clean up HA group 2
- HighAvailabilityGroup.get(jdbcUrl, clientProperties).ifPresent(HighAvailabilityGroup::close);
- }
-
- /**
- * Test that HA connection request will fall back to the first cluster when HA group fails
- * to initialize due to missing cluster role record (CRR).
- */
- @Test
- public void testFallbackToSingleConnection() throws Exception {
- final String tableName = testName.getMethodName();
- CLUSTERS.createTableOnClusterPair(tableName);
-
- String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
- clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
- // no cluster role record for the HA group with name haGroupName2
- try (Connection conn = DriverManager.getConnection(jdbcUrl, clientProperties)) {
- // connection is PhoenixConnection instead of HA connection (failover or parallel)
- assertTrue(conn instanceof PhoenixConnection);
- // Deterministically talking to the first cluster: first means "smaller" URL
- String firstClusterUrl = CLUSTERS.getUrl1();
- if (CLUSTERS.getUrl1().compareTo(CLUSTERS.getUrl2()) > 0) {
- firstClusterUrl = CLUSTERS.getUrl2();
- }
- assertEquals(PhoenixRuntime.JDBC_PROTOCOL_ZK + PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + firstClusterUrl, ((PhoenixConnection) conn).getURL());
- doTestBasicOperationsWithConnection(conn, tableName, haGroupName2);
- }
-
- // disable fallback feature even if the cluster role record is missing for this group
- clientProperties.setProperty(PHOENIX_HA_SHOULD_FALLBACK_WHEN_MISSING_CRR_KEY, "false");
- try {
- DriverManager.getConnection(jdbcUrl, clientProperties);
- fail("Should have failed when disabling fallback to single cluster");
- } catch (SQLException e) {
- LOG.info("Got expected exception when disabling fallback");
- }
- clientProperties.remove(PHOENIX_HA_SHOULD_FALLBACK_WHEN_MISSING_CRR_KEY);
-
- // Now create the cluster role record
- CLUSTERS.initClusterRole(haGroupName2, HighAvailabilityPolicy.FAILOVER);
- // And invalidate the negative cache. We are doing it manually because the default time for
- // expireAfterWrite is too long for testing. We do not need to test the cache per se.
- HighAvailabilityGroup.MISSING_CRR_GROUPS_CACHE.invalidateAll();
-
- // After it is expired in the negative cache, the HA group will start serving HA connections
- try (Connection conn = DriverManager.getConnection(jdbcUrl, clientProperties)) {
- assertTrue(conn instanceof FailoverPhoenixConnection);
- doTestBasicOperationsWithConnection(conn, tableName, haGroupName2);
- }
- }
-
- /**
- * Test that HA connection request will not fall back to the first cluster when one ZK is down.
- */
- @Test
- public void testNotFallbackToSingleConnection() throws Exception {
- final String tableName = testName.getMethodName();
- CLUSTERS.createTableOnClusterPair(tableName);
- String haGroupName2 = testName.getMethodName() + RandomStringUtils.randomAlphabetic(3);
- clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName2);
-
- doTestWhenOneZKDown(CLUSTERS.getHBaseCluster2(), () -> {
- try {
- DriverManager.getConnection(jdbcUrl, clientProperties);
- fail("Should have failed since one HA group can not initialized. Not falling back");
- } catch (SQLException e) {
- LOG.info("Got expected exception as HA group fails to initialize", e);
- }
- });
-
- // After cluster 2 is up and running again, fallback to single cluster will work
- try (Connection conn = DriverManager.getConnection(jdbcUrl, clientProperties)) {
- // connection is PhoenixConnection instead of HA connection (failover or parallel)
- assertTrue(conn instanceof PhoenixConnection);
- }
+ private String getJdbcHAUrlForGivenHAGroup(HAURLInfo haURLInfo) {
+ return HighAvailabilityGroup.getJDBCUrl(String.format("[%s|%s]", CLUSTERS.getZkUrl1(),
+ CLUSTERS.getZkUrl2()), haURLInfo,
+ ClusterRoleRecord.RegistryType.ZK);
}
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupTestIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupTestIT.java
index b8bd5c61fa..eb7ddc5505 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupTestIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityGroupTestIT.java
@@ -56,10 +56,7 @@ import org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.ConnectionQueryServicesImpl;
import org.apache.phoenix.util.PhoenixRuntime;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.*;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;
@@ -82,6 +79,7 @@ public class HighAvailabilityGroupTestIT {
private static final Logger LOG = LoggerFactory.getLogger(HighAvailabilityGroupTestIT.class);
private static final String ZK1 = "zk1-1\\:2181,zk1-2\\:2181::/hbase";
private static final String ZK2 = "zk2-1\\:2181,zk2-2\\:2181::/hbase";
+ private static final String DUMMY_URL = "jdbc:phoenix:dummyhost";
private static final PhoenixEmbeddedDriver DRIVER = mock(PhoenixEmbeddedDriver.class);
/** The client properties to create a JDBC connection. */
@@ -122,8 +120,11 @@ public class HighAvailabilityGroupTestIT {
// By default the HA policy is FAILOVER
when(record.getPolicy()).thenReturn(HighAvailabilityPolicy.FAILOVER);
when(record.getHaGroupName()).thenReturn(haGroupName);
+ when(record.getRegistryType()).thenReturn(ClusterRoleRecord.RegistryType.ZK);
// Make ZK1 ACTIVE
when(record.getActiveUrl()).thenReturn(Optional.of(ZK1));
+ when(record.getUrl1()).thenReturn(ZK1);
+ when(record.getUrl2()).thenReturn(ZK2);
when(record.getRole(eq(ZK1))).thenReturn(ClusterRole.ACTIVE);
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName);
@@ -221,10 +222,15 @@ public class HighAvailabilityGroupTestIT {
/**
* Test {@link HighAvailabilityGroup#connectToOneCluster} with invalid connection string.
*/
- @Test (expected = IllegalArgumentException.class)
+ @Test
public void testConnectToOneClusterShouldFailWithNonHAJdbcString() throws SQLException {
final String jdbcString = "jdbc:phoenix:dummyhost";
- haGroup.connectToOneCluster(jdbcString, clientProperties, haURLInfo);
+ when(record.getRole(eq("dummyhost\\:2181::/hbase"))).thenReturn(ClusterRole.UNKNOWN);
+ try {
+ haGroup.connectToOneCluster(jdbcString, clientProperties, haURLInfo);
+ } catch (SQLException e) {
+ Assert.assertEquals(SQLExceptionCode.HA_CLUSTER_CAN_NOT_CONNECT.getErrorCode(), e.getErrorCode());
+ }
verify(DRIVER, never()).getConnectionQueryServices(anyString(), eq(clientProperties));
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtility.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtility.java
index 4a7c6bce91..a45f5d4497 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtility.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtility.java
@@ -17,7 +17,7 @@
*/
package org.apache.phoenix.jdbc;
-import org.apache.hadoop.hbase.StartMiniClusterOption;
+import org.apache.hadoop.hbase.*;
import org.apache.phoenix.end2end.PhoenixRegionServerEndpointTestImpl;
import org.apache.phoenix.end2end.ServerMetadataCacheTestImpl;
import org.apache.phoenix.thirdparty.com.google.common.annotations.VisibleForTesting;
@@ -25,9 +25,6 @@ import org.apache.phoenix.thirdparty.com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.RandomUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.GenericTestUtils;
-import org.apache.hadoop.hbase.HBaseTestingUtility;
-import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.ipc.PhoenixRpcSchedulerFactory;
import org.apache.hadoop.hbase.regionserver.RSRpcServices;
@@ -64,6 +61,9 @@ import static org.apache.phoenix.jdbc.HighAvailabilityGroup.*;
import static org.apache.phoenix.jdbc.PhoenixHAAdmin.HighAvailibilityCuratorProvider;
import static org.apache.phoenix.query.QueryServices.COLLECT_REQUEST_LEVEL_METRICS;
+import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_MASTER;
+import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_RPC;
+import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_ZK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -83,9 +83,9 @@ public class HighAvailabilityTestingUtility {
private final HBaseTestingUtility hbaseCluster1 = new HBaseTestingUtility();
private final HBaseTestingUtility hbaseCluster2 = new HBaseTestingUtility();
/** The host\:port::/hbase format of the JDBC string for HBase cluster 1. */
- private String url1;
+ private String zkUrl1;
/** The host\:port::/hbase format of the JDBC string for HBase cluster 2. */
- private String url2;
+ private String zkUrl2;
private PhoenixHAAdmin haAdmin1;
private PhoenixHAAdmin haAdmin2;
private Admin admin1;
@@ -118,11 +118,11 @@ public class HighAvailabilityTestingUtility {
String confAddress1 = hbaseCluster1.getConfiguration().get(HConstants.ZOOKEEPER_QUORUM);
String confAddress2 = hbaseCluster2.getConfiguration().get(HConstants.ZOOKEEPER_QUORUM);
- url1 = String.format("%s\\:%d::/hbase", confAddress1, hbaseCluster1.getZkCluster().getClientPort());
- url2 = String.format("%s\\:%d::/hbase", confAddress2, hbaseCluster2.getZkCluster().getClientPort());
+ zkUrl1 = String.format("%s\\:%d::/hbase", confAddress1, hbaseCluster1.getZkCluster().getClientPort());
+ zkUrl2 = String.format("%s\\:%d::/hbase", confAddress2, hbaseCluster2.getZkCluster().getClientPort());
- haAdmin1 = new PhoenixHAAdmin(getUrl1(), hbaseCluster1.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
- haAdmin2 = new PhoenixHAAdmin(getUrl2(), hbaseCluster2.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
+ haAdmin1 = new PhoenixHAAdmin(getZkUrl1(), hbaseCluster1.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
+ haAdmin2 = new PhoenixHAAdmin(getZkUrl2(), hbaseCluster2.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
admin1 = hbaseCluster1.getConnection().getAdmin();
admin2 = hbaseCluster2.getConnection().getAdmin();
@@ -135,19 +135,52 @@ public class HighAvailabilityTestingUtility {
admin2.addReplicationPeer(PHOENIX_HA_GROUP_STORE_PEER_ID_DEFAULT, replicationPeerConfig2);
LOG.info("MiniHBase DR cluster pair is ready for testing. Cluster Urls [{},{}]",
- getUrl1(), getUrl2());
+ getZkUrl1(), getZkUrl2());
logClustersStates();
}
+ /**
+ * Get Specific url of specific cluster based on index and registryType
+ */
+ public String getURL(int clusterIndex, ClusterRoleRecord.RegistryType registryType) {
+ if (registryType == null) {
+ return clusterIndex == 1 ? zkUrl1 : zkUrl2;
+ }
+ String masterAddress1 = hbaseCluster1.getConfiguration().get(HConstants.MASTER_ADDRS_KEY);
+ String masterAddress2 = hbaseCluster2.getConfiguration().get(HConstants.MASTER_ADDRS_KEY);
+ switch (registryType) {
+ case RPC:
+ case MASTER:
+ return clusterIndex == 1 ? masterAddress1.replaceAll(":", "\\\\:") :
+ masterAddress2.replaceAll(":", "\\\\:");
+ case ZK:
+ default:
+ return clusterIndex == 1 ? zkUrl1 : zkUrl2;
+ }
+ }
+
/** initialize two ZK clusters for cluster role znode. */
public void initClusterRole(String haGroupName, HighAvailabilityPolicy policy)
throws Exception {
ClusterRoleRecord record = new ClusterRoleRecord(
haGroupName, policy,
- getUrl1(), ClusterRole.ACTIVE,
- getUrl2(), ClusterRole.STANDBY,
+ getZkUrl1(), ClusterRole.ACTIVE,
+ getZkUrl2(), ClusterRole.STANDBY,
+ 1);
+ addRoleRecordToClusters(record);
+ }
+
+ public void initClusterRole(String haGroupName, HighAvailabilityPolicy policy,
+ ClusterRoleRecord.RegistryType type) throws Exception {
+ ClusterRoleRecord record = new ClusterRoleRecord(
+ haGroupName, policy, type,
+ getURL(1, type), ClusterRole.ACTIVE,
+ getURL(2, type), ClusterRole.STANDBY,
1);
+ addRoleRecordToClusters(record);
+ }
+ private void addRoleRecordToClusters(ClusterRoleRecord record) throws Exception {
int failures = 0;
do {
try {
@@ -178,9 +211,43 @@ public class HighAvailabilityTestingUtility {
ClusterRole role2) throws Exception {
final ClusterRoleRecord newRoleRecord = new ClusterRoleRecord(
haGroup.getGroupInfo().getName(), haGroup.getRoleRecord().getPolicy(),
- getUrl1(), role1,
- getUrl2(), role2,
+ haGroup.getRoleRecord().getRegistryType(),
+ getURL(1, haGroup.getRoleRecord().getRegistryType()), role1,
+ getURL(2, haGroup.getRoleRecord().getRegistryType()), role2,
+ haGroup.getRoleRecord().getVersion() + 1); // always use a newer version
+ applyNewRoleRecord(newRoleRecord, haGroup);
+ }
+
+ /**
+ * Set registryType for roleRecord and wait the cluster role transition to happen.
+ *
+ * @param haGroup the HA group name
+ * @param type RegistryType to change roleRecord to
+ */
+ public void transitClusterRoleRecordRegistry(HighAvailabilityGroup haGroup,
+ ClusterRoleRecord.RegistryType type) throws Exception {
+ final ClusterRoleRecord newRoleRecord = new ClusterRoleRecord(
+ haGroup.getGroupInfo().getName(), haGroup.getRoleRecord().getPolicy(),
+ type,
+ getURL(1, type), ClusterRole.ACTIVE,
+ getURL(2, type), ClusterRole.STANDBY,
+ haGroup.getRoleRecord().getVersion() + 1); // always use a newer version
+ applyNewRoleRecord(newRoleRecord, haGroup);
+ }
+
+ public void refreshClusterRoleRecordAfterClusterRestart(HighAvailabilityGroup haGroup,
+ ClusterRole role1, ClusterRole role2) throws Exception {
+ final ClusterRoleRecord newRoleRecord = new ClusterRoleRecord(
+ haGroup.getGroupInfo().getName(), haGroup.getRoleRecord().getPolicy(),
+ haGroup.getRoleRecord().getRegistryType(),
+ getURL(1, haGroup.getRoleRecord().getRegistryType()), role1,
+ getURL(2, haGroup.getRoleRecord().getRegistryType()), role2,
haGroup.getRoleRecord().getVersion() + 1); // always use a newer version
+ applyNewRoleRecord(newRoleRecord, haGroup);
+ }
+
+ private void applyNewRoleRecord(ClusterRoleRecord newRoleRecord,
+ HighAvailabilityGroup haGroup) throws Exception {
LOG.info("Transiting cluster role for HA group {} V{}->V{}, existing: {}, new: {}",
haGroup.getGroupInfo().getName(), haGroup.getRoleRecord().getVersion(),
newRoleRecord.getVersion(), haGroup.getRoleRecord(), newRoleRecord);
@@ -189,13 +256,13 @@ public class HighAvailabilityTestingUtility {
haAdmin1.createOrUpdateDataOnZookeeper(newRoleRecord);
successAtLeastOnce = true;
} catch (IOException e) {
- LOG.warn("Fail to update new record on {} because {}", getUrl1(), e.getMessage());
+ LOG.warn("Fail to update new record on {} because {}", getZkUrl1(), e.getMessage());
}
try {
haAdmin2.createOrUpdateDataOnZookeeper(newRoleRecord);
successAtLeastOnce = true;
} catch (IOException e) {
- LOG.warn("Fail to update new record on {} because {}", getUrl2(), e.getMessage());
+ LOG.warn("Fail to update new record on {} because {}", getZkUrl2(), e.getMessage());
}
if (!successAtLeastOnce) {
@@ -247,10 +314,9 @@ public class HighAvailabilityTestingUtility {
* @param clusterIndex 1 based
* @return a Phoenix Connection to the indexed cluster
*/
- public Connection getClusterConnection(int clusterIndex) throws SQLException {
- String clusterUrl = clusterIndex == 1 ? getUrl1() : getUrl2();
+ public Connection getClusterConnection(int clusterIndex, HighAvailabilityGroup haGroup) throws SQLException {
Properties props = new Properties();
- String url = getJdbcUrl(clusterUrl);
+ String url = getJdbcUrl(haGroup, getURL(clusterIndex, haGroup.getRoleRecord().getRegistryType()));
return DriverManager.getConnection(url, props);
}
@@ -258,16 +324,16 @@ public class HighAvailabilityTestingUtility {
* Returns a Phoenix Connection to cluster 1
* @return a Phoenix Connection to the cluster
*/
- public Connection getCluster1Connection() throws SQLException {
- return getClusterConnection(1);
+ public Connection getCluster1Connection(HighAvailabilityGroup haGroup) throws SQLException {
+ return getClusterConnection(1, haGroup);
}
/**
* Returns a Phoenix Connection to cluster 2
* @return a Phoenix Connection to the cluster
*/
- public Connection getCluster2Connection() throws SQLException {
- return getClusterConnection(2);
+ public Connection getCluster2Connection(HighAvailabilityGroup haGroup) throws SQLException {
+ return getClusterConnection(2, haGroup);
}
//TODO: Replace with a real check for replication complete
@@ -344,51 +410,83 @@ public class HighAvailabilityTestingUtility {
}
/**
- * @return the JDBC connection URL for this pair of HBase cluster in the HA format
+ * The JDBC connection url for the given clusters in particular format.
+ * Note that HAUrl will contain ZK as host which is used to create HA Connection
+ * from client, although wrapped connections can be using master url based on the
+ * registry Type set in roleRecord.
+ *
+ * below methods will return urls based on registryType and HAUrl will be zk based
*/
public String getJdbcHAUrl() {
- return getJdbcUrl(String.format("[%s|%s]", url1, url2));
+ return getJdbcHAUrl(PRINCIPAL);
}
public String getJdbcHAUrl(String principal) {
- return getJdbcUrl(String.format("[%s|%s]", url1, url2), principal);
+ return String.format("%s:[%s|%s]:%s", JDBC_PROTOCOL_ZK, getZkUrl1(), getZkUrl2(), principal);
}
public String getJdbcHAUrlWithoutPrincipal() {
- return getJdbcUrlWithoutPrincipal(String.format("[%s|%s]", url1, url2));
+ return String.format("%s:[%s|%s]", JDBC_PROTOCOL_ZK, getZkUrl1(), getZkUrl2());
}
- public String getJdbcUrl1() {
- return getJdbcUrl(url1);
+ public String getJdbcUrl1(HighAvailabilityGroup haGroup) {
+ return getJdbcUrl(haGroup, getURL(1, haGroup.getRoleRecord().getRegistryType()));
}
- public String getJdbcUrl1(String principal) {
- return getJdbcUrl(url1, principal);
+ public String getJdbcUrl1(HighAvailabilityGroup haGroup, String principal) {
+ return getJdbcUrl(haGroup, getURL(1, haGroup.getRoleRecord().getRegistryType()), principal);
}
- public String getJdbcUrl2() {
- return getJdbcUrl(url2);
+ public String getJdbcUrl2(HighAvailabilityGroup haGroup) {
+ return getJdbcUrl(haGroup, getURL(2, haGroup.getRoleRecord().getRegistryType()));
}
- public String getJdbcUrl(String zkUrl) {
- return String.format("jdbc:phoenix+zk:%s:%s", zkUrl, PRINCIPAL);
+ public String getJdbcUrl2(HighAvailabilityGroup haGroup, String principal) {
+ return getJdbcUrl(haGroup, getURL(2, haGroup.getRoleRecord().getRegistryType()), principal);
}
- public String getJdbcUrl(String zkUrl, String principal) {
- return String.format("jdbc:phoenix+zk:%s:%s", zkUrl, principal);
+ public String getJdbcUrl(HighAvailabilityGroup haGroup, String url) {
+ String interimUrl = getUrlWithoutPrincipal(haGroup, url);
+ return String.format("%s:%s",interimUrl, PRINCIPAL);
}
- public String getJdbcUrlWithoutPrincipal(String zkUrl) {
- return String.format("jdbc:phoenix+zk:%s", zkUrl);
+ public String getJdbcUrl(HighAvailabilityGroup haGroup, String url, String principal) {
+ String interimUrl = getUrlWithoutPrincipal(haGroup, url);
+ return String.format("%s:%s",interimUrl, principal);
}
- public String getUrl1() {
- return url1;
+ public String getJdbcUrl(String url) {
+ return String.format("jdbc:phoenix+zk:%s:%s", url, PRINCIPAL);
}
- public String getUrl2() {
- return url2;
+ public String getJdbcUrlWithoutPrincipal(HighAvailabilityGroup haGroup, String url) {
+ String interimUrl = getUrlWithoutPrincipal(haGroup, url);
+ if (interimUrl.endsWith("::")) {
+ interimUrl = interimUrl.substring(0, interimUrl.length() - 2);
+ }
+ return interimUrl;
+ }
+
+ public String getZkUrl1() {
+ return zkUrl1;
+ }
+
+ public String getZkUrl2() {
+ return zkUrl2;
+ }
+
+ private String getUrlWithoutPrincipal(HighAvailabilityGroup haGroup, String url) {
+ StringBuilder sb = new StringBuilder();
+ switch (haGroup.getRoleRecord().getRegistryType()) {
+ case MASTER:
+ return sb.append(JDBC_PROTOCOL_MASTER).append(":").append(url).append("::").toString();
+ case RPC:
+ return sb.append(JDBC_PROTOCOL_RPC).append(":").append(url).append("::").toString();
+ case ZK:
+ default:
+ return sb.append(JDBC_PROTOCOL_ZK).append(":").append(url).toString();
+ }
}
/**
@@ -399,7 +497,7 @@ public class HighAvailabilityTestingUtility {
getHBaseCluster1().getConfiguration()
.iterator()
.forEachRemaining(k -> properties.setProperty(k.getKey(), k.getValue()));
- return HighAvailabilityGroup.getCurator(getUrl1(), properties);
+ return HighAvailabilityGroup.getCurator(getZkUrl1(), properties);
}
/**
@@ -410,7 +508,7 @@ public class HighAvailabilityTestingUtility {
getHBaseCluster2().getConfiguration()
.iterator()
.forEachRemaining(k -> properties.setProperty(k.getKey(), k.getValue()));
- return HighAvailabilityGroup.getCurator(getUrl2(), properties);
+ return HighAvailabilityGroup.getCurator(getZkUrl2(), properties);
}
/**
@@ -419,8 +517,8 @@ public class HighAvailabilityTestingUtility {
* @param tableName the table name
* @throws SQLException if error happens
*/
- public void createTableOnClusterPair(String tableName) throws SQLException {
- createTableOnClusterPair(tableName, true);
+ public void createTableOnClusterPair(HighAvailabilityGroup haGroup, String tableName) throws SQLException {
+ createTableOnClusterPair(haGroup, tableName, true);
}
/**
@@ -432,10 +530,11 @@ public class HighAvailabilityTestingUtility {
* @param replicationScope the table replication scope true=1 and false=0
* @throws SQLException if error happens
*/
- public void createTableOnClusterPair(String tableName, boolean replicationScope)
+ public void createTableOnClusterPair(HighAvailabilityGroup haGroup, String tableName, boolean replicationScope)
throws SQLException {
- for (String url : Arrays.asList(getUrl1(), getUrl2())) {
- String jdbcUrl = getJdbcUrl(url);
+ for (String url : Arrays.asList(getURL(1, haGroup.getRoleRecord().getRegistryType()),
+ getURL(2, haGroup.getRoleRecord().getRegistryType()))) {
+ String jdbcUrl = getJdbcUrl(haGroup, url);
try (Connection conn = DriverManager.getConnection(jdbcUrl, new Properties())) {
conn.createStatement().execute(String.format(
"CREATE TABLE IF NOT EXISTS %s (\n"
@@ -464,9 +563,10 @@ public class HighAvailabilityTestingUtility {
* @param tableName the table name
* @throws SQLException if error happens
*/
- public void createTenantSpecificTable(String tableName) throws SQLException {
- for (String url : Arrays.asList(getUrl1(), getUrl2())) {
- String jdbcUrl = getJdbcUrl(url);
+ public void createTenantSpecificTable(HighAvailabilityGroup haGroup, String tableName) throws SQLException {
+ for (String url : Arrays.asList(getURL(1, haGroup.getRoleRecord().getRegistryType()),
+ getURL(2, haGroup.getRoleRecord().getRegistryType()))) {
+ String jdbcUrl = getJdbcUrl(haGroup, url);
try (Connection conn = DriverManager.getConnection(jdbcUrl, new Properties())) {
conn.createStatement().execute(String.format(
"CREATE TABLE IF NOT EXISTS %s (\n"
@@ -488,6 +588,43 @@ public class HighAvailabilityTestingUtility {
LOG.info("Created multi-tenant table {} on cluster pair {}", tableName, this);
}
+ public void restartCluster1() throws Exception {
+ try {
+ hbaseCluster1.shutdownMiniHBaseCluster();
+ hbaseCluster1.shutdownMiniZKCluster();
+ } finally {
+ hbaseCluster1.startMiniZKCluster(1);
+ hbaseCluster1.startMiniHBaseCluster(StartMiniClusterOption.builder().numMasters(1).numRegionServers(1).build());
+
+ String confAddress = hbaseCluster1.getConfiguration().get(HConstants.ZOOKEEPER_QUORUM);
+
+ zkUrl1 = String.format("%s\\:%d::/hbase", confAddress, hbaseCluster1.getZkCluster().getClientPort());
+
+ haAdmin1 = new PhoenixHAAdmin(getZkUrl1(), hbaseCluster1.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
+
+ admin1 = hbaseCluster1.getConnection().getAdmin();
+ }
+
+ }
+
+ public void restartCluster2() throws Exception {
+ try {
+ hbaseCluster2.shutdownMiniHBaseCluster();
+ hbaseCluster2.shutdownMiniZKCluster();
+ } finally {
+ hbaseCluster2.startMiniZKCluster(1);
+ hbaseCluster2.startMiniHBaseCluster(StartMiniClusterOption.builder().numMasters(1).numRegionServers(1).build());
+
+ String confAddress = hbaseCluster2.getConfiguration().get(HConstants.ZOOKEEPER_QUORUM);
+
+ zkUrl2 = String.format("%s\\:%d::/hbase", confAddress, hbaseCluster2.getZkCluster().getClientPort());
+
+ haAdmin2 = new PhoenixHAAdmin(getZkUrl2(), hbaseCluster2.getConfiguration(), HighAvailibilityCuratorProvider.INSTANCE);
+
+ admin2 = hbaseCluster2.getConnection().getAdmin();
+ }
+ }
+
/**
* Shuts down the two hbase clusters.
*/
@@ -510,7 +647,7 @@ public class HighAvailabilityTestingUtility {
@Override
public String toString() {
- return "HBaseTestingUtilityPair{" + getUrl1() + ", " + getUrl2() + "}";
+ return "HBaseTestingUtilityPair{" + getZkUrl1() + ", " + getZkUrl2() + "}";
}
/** Sets up the default HBase configuration for Phoenix HA testing. */
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtilityIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtilityIT.java
index f7427050ea..06ac323dae 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtilityIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/HighAvailabilityTestingUtilityIT.java
@@ -22,6 +22,7 @@ import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestin
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneHBaseDown;
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.HBaseTestingUtilityPair.doTestWhenOneZKDown;
import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.doTestBasicOperationsWithConnection;
+import static org.apache.phoenix.jdbc.HighAvailabilityTestingUtility.getHighAvailibilityGroup;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -30,8 +31,11 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Properties;
+import org.apache.commons.lang3.RandomStringUtils;
import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.junit.AfterClass;
@@ -41,6 +45,8 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,6 +54,7 @@ import org.slf4j.LoggerFactory;
* Test failover basics for {@link HighAvailabilityTestingUtility}.
*/
@Category(NeedsOwnMiniClusterTest.class)
+@RunWith(Parameterized.class)
public class HighAvailabilityTestingUtilityIT {
private static final Logger LOG = LoggerFactory.getLogger(
HighAvailabilityTestingUtilityIT.class);
@@ -56,9 +63,22 @@ public class HighAvailabilityTestingUtilityIT {
@Rule
public TestName testName = new TestName();
+ /** Client properties to create a connection per test. */
+ private Properties clientProperties;
+ /** JDBC connection string for this test HA group. */
+ private String jdbcHAUrl;
+ /** Failover HA group for to test. */
+ private HighAvailabilityGroup haGroup;
+ private String haGroupName;
+ private final ClusterRoleRecord.RegistryType registryType;
+
/** Table name per test case. */
private String tableName;
+ public HighAvailabilityTestingUtilityIT(ClusterRoleRecord.RegistryType registryType) {
+ this.registryType = registryType;
+ }
+
@BeforeClass
public static void setUpBeforeClass() throws Exception {
CLUSTERS.start();
@@ -73,13 +93,31 @@ public class HighAvailabilityTestingUtilityIT {
@Before
public void setup() throws Exception {
- String haGroupName = testName.getMethodName();
+ haGroupName = testName.getMethodName();
+ clientProperties = HighAvailabilityTestingUtility.getHATestProperties();
+ clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName);
// Make first cluster ACTIVE
- CLUSTERS.initClusterRole(haGroupName,HighAvailabilityPolicy.FAILOVER);
+ if (registryType == null) {
+ CLUSTERS.initClusterRole(haGroupName, HighAvailabilityPolicy.FAILOVER);
+ } else {
+ CLUSTERS.initClusterRole(haGroupName, HighAvailabilityPolicy.FAILOVER, registryType);
+ }
- tableName = testName.getMethodName();
- CLUSTERS.createTableOnClusterPair(tableName);
+ tableName = RandomStringUtils.randomAlphabetic(10);
+ jdbcHAUrl = CLUSTERS.getJdbcHAUrl();
+ haGroup = getHighAvailibilityGroup(jdbcHAUrl,clientProperties);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
+ }
+
+ @Parameterized.Parameters(name="ClusterRoleRecord_registryType={0}")
+ public static Collection<Object> data() {
+ return Arrays.asList(new Object[] {
+ ClusterRoleRecord.RegistryType.ZK,
+ ClusterRoleRecord.RegistryType.MASTER,
+ ClusterRoleRecord.RegistryType.RPC,
+ null //For Backward Compatibility
+ });
}
/**
@@ -89,13 +127,13 @@ public class HighAvailabilityTestingUtilityIT {
public void testClusterUnavailableNormalConnection() throws Exception {
doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster2(), () -> {
CLUSTERS.logClustersStates();
- try (Connection conn = CLUSTERS.getCluster1Connection()) {
+ try (Connection conn = CLUSTERS.getCluster1Connection(haGroup)) {
doTestBasicOperationsWithConnection(conn, tableName, null);
}
});
doTestWhenOneHBaseDown(CLUSTERS.getHBaseCluster1(), () -> {
CLUSTERS.logClustersStates();
- try (Connection conn = CLUSTERS.getCluster2Connection()) {
+ try (Connection conn = CLUSTERS.getCluster2Connection(haGroup)) {
doTestBasicOperationsWithConnection(conn, tableName, null);
}
});
@@ -106,13 +144,13 @@ public class HighAvailabilityTestingUtilityIT {
*/
@Test
public void testClusterReplication() throws Exception {
- try (Connection conn = CLUSTERS.getClusterConnection(0)) {
+ try (Connection conn = CLUSTERS.getClusterConnection(0, haGroup)) {
doTestBasicOperationsWithConnection(conn, tableName, null);
}
CLUSTERS.checkReplicationComplete();
- try (Connection conn = CLUSTERS.getClusterConnection(1);
+ try (Connection conn = CLUSTERS.getClusterConnection(1, haGroup);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("SELECT * FROM %s",tableName))) {
@@ -131,7 +169,7 @@ public class HighAvailabilityTestingUtilityIT {
Properties properties = HighAvailabilityTestingUtility.getHATestProperties();
properties.setProperty(PHOENIX_HA_GROUP_ATTR, testName.getMethodName());
ConnectionQueryServices cqs = PhoenixDriver.INSTANCE.getConnectionQueryServices(
- CLUSTERS.getJdbcUrl1(), properties);
+ CLUSTERS.getJdbcUrl1(haGroup), properties);
fail("Should have failed since the target cluster is down, but got a CQS: " + cqs);
} catch (Exception e) {
LOG.info("Got expected exception since target cluster is down:", e);
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/LoggingHAConnectionLimiterIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/LoggingHAConnectionLimiterIT.java
index c4075ffdd5..30845397ca 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/LoggingHAConnectionLimiterIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/LoggingHAConnectionLimiterIT.java
@@ -56,7 +56,7 @@ public class LoggingHAConnectionLimiterIT extends LoggingConnectionLimiterIT {
/**
* JDBC connection string for this test HA group.
*/
- private String jdbcUrl;
+ private String jdbcHAUrl;
/**
* HA group for this test.
*/
@@ -86,7 +86,8 @@ public class LoggingHAConnectionLimiterIT extends LoggingConnectionLimiterIT {
GLOBAL_PROPERTIES.put(PHOENIX_HA_GROUP_ATTR, PARALLEL.name());
- CONNECTIONS = Lists.newArrayList(CLUSTERS.getCluster1Connection(), CLUSTERS.getCluster2Connection());
+ CONNECTIONS = Lists.newArrayList(getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl1())),
+ getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl2())));
LOG.info(String.format("************* Num connections : %d", CONNECTIONS.size()));
for (Connection conn : CONNECTIONS) {
@@ -97,7 +98,7 @@ public class LoggingHAConnectionLimiterIT extends LoggingConnectionLimiterIT {
}
//preload some data
- try (Connection connection = CLUSTERS.getCluster1Connection()) {
+ try (Connection connection = getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl1()))) {
loadData(connection, ORG_ID, GROUP_ID, 100, 20);
}
}
@@ -124,10 +125,10 @@ public class LoggingHAConnectionLimiterIT extends LoggingConnectionLimiterIT {
// Make first cluster ACTIVE
CLUSTERS.initClusterRole(haGroupName, PARALLEL);
- jdbcUrl = String.format("jdbc:phoenix:[%s|%s]",
- CLUSTERS.getUrl1(), CLUSTERS.getUrl2());
- haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcUrl, clientProperties);
- LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcUrl);
+ jdbcHAUrl = String.format("jdbc:phoenix:[%s|%s]",
+ CLUSTERS.getZkUrl1(), CLUSTERS.getZkUrl2());
+ haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcHAUrl, clientProperties);
+ LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcHAUrl);
}
@@ -147,9 +148,13 @@ public class LoggingHAConnectionLimiterIT extends LoggingConnectionLimiterIT {
@Override
protected Connection getConnection() throws SQLException {
- Connection connection = DriverManager.getConnection(jdbcUrl, clientProperties);
+ Connection connection = DriverManager.getConnection(jdbcHAUrl, clientProperties);
connection.setAutoCommit(true);
return connection;
}
+ private static Connection getConnection(String url) throws SQLException {
+ return DriverManager.getConnection(url, new Properties());
+ }
+
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionFallbackIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionFallbackIT.java
index e59fc18fd8..42513b1dce 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionFallbackIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionFallbackIT.java
@@ -72,7 +72,7 @@ public class ParallelPhoenixConnectionFallbackIT {
jdbcUrl = CLUSTERS.getJdbcHAUrl();
haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcUrl, PROPERTIES);
LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcUrl);
- CLUSTERS.createTableOnClusterPair(tableName);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
}
@AfterClass
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionIT.java
index 106ccfd9c0..d1f97356fe 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionIT.java
@@ -46,10 +46,11 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.Map;
-import java.util.Properties;
+import java.util.*;
import java.util.concurrent.CompletableFuture;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest;
import org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole;
@@ -60,6 +61,7 @@ import org.apache.phoenix.monitoring.GlobalMetric;
import org.apache.phoenix.monitoring.MetricType;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.util.JDBCUtil;
import org.apache.phoenix.util.PhoenixRuntime;
import org.junit.AfterClass;
import org.junit.Assert;
@@ -69,6 +71,8 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -119,8 +123,8 @@ public class ParallelPhoenixConnectionIT {
haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(CLUSTERS.getJdbcHAUrl(), clientProperties);
LOG.info("Initialized haGroup {} with URL {}", haGroup, CLUSTERS.getJdbcHAUrl());
- tableName = testName.getMethodName();
- CLUSTERS.createTableOnClusterPair(tableName);
+ tableName = testName.getMethodName().toUpperCase();
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName);
}
/**
@@ -137,31 +141,32 @@ public class ParallelPhoenixConnectionIT {
public void testUserPrincipal() throws Exception {
try (Connection conn = getParallelConnection()) {
ParallelPhoenixConnection pr = conn.unwrap(ParallelPhoenixConnection.class);
- ParallelPhoenixContext context = pr.getContext();
- HAURLInfo haurlInfo = context.getHaurlInfo();
- HighAvailabilityGroup.HAGroupInfo group = context.getHaGroup().getGroupInfo();
- if (CLUSTERS.getUrl1().compareTo(CLUSTERS.getUrl2()) <= 0) {
- Assert.assertEquals(CLUSTERS.getJdbcUrl1(), group.getJDBCUrl1(haurlInfo));
- Assert.assertEquals(CLUSTERS.getJdbcUrl2(), group.getJDBCUrl2(haurlInfo));
+ PhoenixConnection pConn;
+ PhoenixConnection pConn2;
+ if (CLUSTERS.getJdbcUrl1(haGroup).equals(pr.getFutureConnection1().get().getURL())) {
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), pr.getFutureConnection2().get().getURL());
+ pConn = pr.getFutureConnection1().get();
+ pConn2 = pr.getFutureConnection2().get();
} else {
- Assert.assertEquals(CLUSTERS.getJdbcUrl2(), group.getJDBCUrl1(haurlInfo));
- Assert.assertEquals(CLUSTERS.getJdbcUrl1(), group.getJDBCUrl2(haurlInfo));
+ assertEquals(CLUSTERS.getJdbcUrl1(haGroup), pr.getFutureConnection2().get().getURL());
+ assertEquals(CLUSTERS.getJdbcUrl2(haGroup), pr.getFutureConnection1().get().getURL());
+ pConn = pr.getFutureConnection2().get();
+ pConn2 = pr.getFutureConnection1().get();
}
+
ConnectionQueryServices cqsi;
// verify connection#1
- cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(group.getJDBCUrl1(haurlInfo), clientProperties);
+ cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl1(haGroup), clientProperties);
Assert.assertEquals(HBaseTestingUtilityPair.PRINCIPAL, cqsi.getUserName());
- PhoenixConnection pConn = pr.getFutureConnection1().get();
ConnectionQueryServices cqsiFromConn = pConn.getQueryServices();
Assert.assertEquals(HBaseTestingUtilityPair.PRINCIPAL, cqsiFromConn.getUserName());
- Assert.assertTrue(cqsi == cqsiFromConn);
+ Assert.assertSame(cqsi, cqsiFromConn);
// verify connection#2
- cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(group.getJDBCUrl2(haurlInfo), clientProperties);
+ cqsi = PhoenixDriver.INSTANCE.getConnectionQueryServices(CLUSTERS.getJdbcUrl2(haGroup), clientProperties);
Assert.assertEquals(HBaseTestingUtilityPair.PRINCIPAL, cqsi.getUserName());
- pConn = pr.getFutureConnection2().get();
- cqsiFromConn = pConn.getQueryServices();
+ cqsiFromConn = pConn2.getQueryServices();
Assert.assertEquals(HBaseTestingUtilityPair.PRINCIPAL, cqsiFromConn.getUserName());
- Assert.assertTrue(cqsi == cqsiFromConn);
+ Assert.assertSame(cqsi, cqsiFromConn);
}
}
@@ -208,7 +213,7 @@ public class ParallelPhoenixConnectionIT {
CLUSTERS.checkReplicationComplete();
//ensure values on both clusters
- try (Connection conn = CLUSTERS.getCluster1Connection();
+ try (Connection conn = CLUSTERS.getCluster1Connection(haGroup);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("SELECT COUNT(*) FROM %s", tableName))) {
assertTrue(rs.next());
@@ -216,7 +221,7 @@ public class ParallelPhoenixConnectionIT {
}
//ensure values on both clusters
- try (Connection conn = CLUSTERS.getCluster2Connection();
+ try (Connection conn = CLUSTERS.getCluster2Connection(haGroup);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("SELECT COUNT(*) FROM %s", tableName))) {
assertTrue(rs.next());
@@ -257,14 +262,14 @@ public class ParallelPhoenixConnectionIT {
CLUSTERS.checkReplicationComplete();
//ensure values on both clusters
- try (Connection conn = CLUSTERS.getCluster1Connection();
+ try (Connection conn = CLUSTERS.getCluster1Connection(haGroup);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("SELECT COUNT(*) FROM %s",tableName))) {
assertOperationTypeForStatement(statement, Operation.QUERY);
assertTrue(rs.next());
assertEquals(100, rs.getInt(1));
}
- try (Connection conn = CLUSTERS.getCluster2Connection();
+ try (Connection conn = CLUSTERS.getCluster2Connection(haGroup);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(String.format("SELECT COUNT(*) FROM %s",tableName))) {
assertTrue(rs.next());
@@ -333,7 +338,8 @@ public class ParallelPhoenixConnectionIT {
CompletableFuture<PhoenixConnection> pConn = null;
int downClientPort = CLUSTERS.getHBaseCluster1().getZkCluster().getClientPort();
- if(((ParallelPhoenixConnection) conn).getContext().getHaGroup().getRoleRecord().getZk1().contains(String.valueOf(downClientPort))) {
+ if(((ParallelPhoenixConnection) conn).getContext().getHaGroup().getRoleRecord().
+ getUrl1().contains(String.valueOf(downClientPort))) {
pConn = ((ParallelPhoenixConnection) conn).futureConnection2;
} else {
pConn = ((ParallelPhoenixConnection) conn).futureConnection1;
@@ -512,8 +518,8 @@ public class ParallelPhoenixConnectionIT {
@Test
public void testSeparateMetadata() throws Exception {
//make a table on the 2nd cluster
- String tableName = "TABLE_" + testName.getMethodName();
- try(Connection conn = CLUSTERS.getCluster2Connection()) {
+ String tableName = "TABLE_" + RandomStringUtils.randomAlphabetic(10);
+ try(Connection conn = CLUSTERS.getCluster2Connection(haGroup)) {
String ddl = "CREATE TABLE " + tableName + " ( MYKEY VARCHAR NOT NULL, MYVALUE VARCHAR CONSTRAINT PK_DATA PRIMARY KEY (MYKEY))";
try(Statement stmt = conn.createStatement()) {
@@ -533,6 +539,56 @@ public class ParallelPhoenixConnectionIT {
}
}
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR , ZK --> MASTER
+ *
+ * Test with many connections.
+ */
+ @Test
+ public void testAllWrappedConnectionsClosedAfterRegistryChangeToMaster() throws Exception {
+ short numberOfConnections = 10;
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getParallelConnection());
+ }
+ ClusterRoleRecord.RegistryType newRegistry = ClusterRoleRecord.RegistryType.MASTER;
+ CLUSTERS.transitClusterRoleRecordRegistry(haGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ ParallelPhoenixConnection conn = ((ParallelPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.futureConnection1.get().isClosed());
+ assertTrue(conn.futureConnection2.get().isClosed());
+ }
+ }
+
+ /**
+ * This is to make sure all Phoenix connections are closed when registryType changes
+ * of a CRR. ZK --> RPC
+ *
+ * Test with many connections.
+ */
+ @Test(timeout = 300000)
+ public void testAllWrappedConnectionsClosedAfterRegistryChangeToRpc() throws Exception {
+ short numberOfConnections = 10;
+ List<Connection> connectionList = new ArrayList<>(numberOfConnections);
+ for (short i = 0; i < numberOfConnections; i++) {
+ connectionList.add(getParallelConnection());
+ }
+ ClusterRoleRecord.RegistryType newRegistry = ClusterRoleRecord.RegistryType.RPC;
+ CLUSTERS.transitClusterRoleRecordRegistry(haGroup, newRegistry);
+
+ for (short i = 0; i < numberOfConnections; i++) {
+ LOG.info("Asserting connection number {}", i);
+ ParallelPhoenixConnection conn = ((ParallelPhoenixConnection) connectionList.get(i));
+ assertFalse(conn.isClosed());
+ assertTrue(conn.futureConnection1.get().isClosed());
+ assertTrue(conn.futureConnection2.get().isClosed());
+ }
+ }
+
/**
* Helper method to test Operation type of Phoenix Statement provided by
* PhoenixMonitoredStatement#getUpdateOperation method.
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionWorkflowIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionWorkflowIT.java
index 274aaf32ac..5950115d75 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionWorkflowIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixConnectionWorkflowIT.java
@@ -44,10 +44,7 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.Instant;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Properties;
+import java.util.*;
import static org.apache.phoenix.jdbc.HighAvailabilityGroup.PHOENIX_HA_GROUP_ATTR;
import static org.apache.phoenix.jdbc.HighAvailabilityPolicy.PARALLEL;
@@ -93,16 +90,38 @@ public class ParallelPhoenixConnectionWorkflowIT {
/**
* JDBC connection string for this test HA group.
*/
- private String jdbcUrl;
+ private String jdbcHAUrl;
/**
* HA group for this test.
*/
private HighAvailabilityGroup haGroup;
+ /**
+ * registry Type to use in CRR
+ */
+ private ClusterRoleRecord.RegistryType registryType;
+
+ @Parameters(name="ParallelPhoenixConnectionWorkflowIT_resultSetType={0}, registryType={1}") // name is used by failsafe as file name in reports
+ public static Collection<Object[]> data() {
+ return Arrays.asList( new Object[][]{
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.ZK},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_NULL_COMPARING_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.ZK},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.MASTER},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_NULL_COMPARING_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.MASTER},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.RPC},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_NULL_COMPARING_RESULT_SET.getName(),
+ ClusterRoleRecord.RegistryType.RPC},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_RESULT_SET.getName(),
+ null},
+ {ParallelPhoenixResultSetType.PARALLEL_PHOENIX_NULL_COMPARING_RESULT_SET.getName(),
+ null}
+
+ });
- @Parameters(name="ParallelPhoenixConnectionWorkflowIT_resultSetType={0}") // name is used by failsafe as file name in reports
- public static Collection<String> data() {
- return Arrays.asList(ParallelPhoenixResultSetType.PARALLEL_PHOENIX_RESULT_SET.getName(),
- ParallelPhoenixResultSetType.PARALLEL_PHOENIX_NULL_COMPARING_RESULT_SET.getName());
}
@BeforeClass
@@ -131,7 +150,8 @@ public class ParallelPhoenixConnectionWorkflowIT {
" ) \n" +
") IMMUTABLE_ROWS=true, VERSIONS=1, REPLICATION_SCOPE=1", tableName);
- CONNECTIONS = Lists.newArrayList(CLUSTERS.getCluster1Connection(), CLUSTERS.getCluster2Connection());
+ CONNECTIONS = Lists.newArrayList(getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl1())),
+ getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl2())));
for (Connection conn : CONNECTIONS) {
try (Statement statement = conn.createStatement()) {
@@ -143,7 +163,7 @@ public class ParallelPhoenixConnectionWorkflowIT {
CLUSTERS.checkReplicationComplete();
//preload some data
- try (Connection connection = CLUSTERS.getCluster1Connection()) {
+ try (Connection connection = getConnection(CLUSTERS.getJdbcUrl(CLUSTERS.getZkUrl1()))) {
loadData(connection, USER_ID, WORK_ID, 100, 20);
}
CLUSTERS.checkReplicationComplete();
@@ -187,8 +207,10 @@ public class ParallelPhoenixConnectionWorkflowIT {
}
}
- public ParallelPhoenixConnectionWorkflowIT(String resultSetType) {
+ public ParallelPhoenixConnectionWorkflowIT(String resultSetType,
+ ClusterRoleRecord.RegistryType registryType) {
GLOBAL_PROPERTIES.setProperty(ParallelPhoenixResultSetFactory.PHOENIX_PARALLEL_RESULTSET_TYPE, resultSetType);
+ this.registryType = registryType;
}
@Before
@@ -198,11 +220,15 @@ public class ParallelPhoenixConnectionWorkflowIT {
clientProperties.setProperty(PHOENIX_HA_GROUP_ATTR, haGroupName);
// Make first cluster ACTIVE
- CLUSTERS.initClusterRole(haGroupName, PARALLEL);
+ if (registryType == null) {
+ CLUSTERS.initClusterRole(haGroupName, PARALLEL);
+ } else {
+ CLUSTERS.initClusterRole(haGroupName, PARALLEL, registryType);
+ }
- jdbcUrl = CLUSTERS.getJdbcHAUrl();
- haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcUrl, clientProperties);
- LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcUrl);
+ jdbcHAUrl = CLUSTERS.getJdbcHAUrl();
+ haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcHAUrl, clientProperties);
+ LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcHAUrl);
}
@Test
@@ -268,7 +294,7 @@ public class ParallelPhoenixConnectionWorkflowIT {
public void testSingleDelete() throws SQLException {
String userId = StringUtils.rightPad(BaseTest.generateUniqueName(), 15).substring(0, 15);
String workId = testName.getMethodName();
- loadData(CLUSTERS.getCluster1Connection(), userId, workId, 10, 10);
+ loadData(CLUSTERS.getCluster1Connection(haGroup), userId, workId, 10, 10);
CLUSTERS.checkReplicationComplete();
for (Connection conn : CONNECTIONS) {
@@ -306,7 +332,7 @@ public class ParallelPhoenixConnectionWorkflowIT {
public void testBatchDelete() throws SQLException {
String userId = StringUtils.rightPad(BaseTest.generateUniqueName(), 15).substring(0, 15);
String workId = testName.getMethodName();
- loadData(CLUSTERS.getCluster1Connection(), userId, workId, 10, 10);
+ loadData(CLUSTERS.getCluster1Connection(haGroup), userId, workId, 10, 10);
CLUSTERS.checkReplicationComplete();
//delete batch
@@ -340,9 +366,9 @@ public class ParallelPhoenixConnectionWorkflowIT {
public void testGroupDelete() throws SQLException {
String userId = StringUtils.rightPad(BaseTest.generateUniqueName(), 15).substring(0, 15);
String workId1 = testName.getMethodName();
- loadData(CLUSTERS.getCluster1Connection(), userId, workId1, 10, 10);
+ loadData(CLUSTERS.getCluster1Connection(haGroup), userId, workId1, 10, 10);
String workId2 = testName.getMethodName() + "2";
- loadData(CLUSTERS.getCluster1Connection(), userId, workId2, 10, 10);
+ loadData(CLUSTERS.getCluster1Connection(haGroup), userId, workId2, 10, 10);
CLUSTERS.checkReplicationComplete();
//delete group
@@ -460,9 +486,13 @@ public class ParallelPhoenixConnectionWorkflowIT {
* @throws SQLException
*/
private Connection getParallelConnection() throws SQLException {
- Connection connection = DriverManager.getConnection(jdbcUrl, clientProperties);
+ Connection connection = DriverManager.getConnection(jdbcHAUrl, clientProperties);
connection.setAutoCommit(true);
return connection;
}
+ private static Connection getConnection(String url) throws SQLException {
+ return DriverManager.getConnection(url, new Properties());
+ }
+
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixNullComparingResultSetIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixNullComparingResultSetIT.java
index 271db0232f..4a516563ab 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixNullComparingResultSetIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/ParallelPhoenixNullComparingResultSetIT.java
@@ -84,7 +84,7 @@ public class ParallelPhoenixNullComparingResultSetIT {
jdbcUrl = CLUSTERS.getJdbcHAUrl();
haGroup = HighAvailabilityTestingUtility.getHighAvailibilityGroup(jdbcUrl, PROPERTIES);
LOG.info("Initialized haGroup {} with URL {}", haGroup.getGroupInfo().getName(), jdbcUrl);
- CLUSTERS.createTableOnClusterPair(tableName, false);
+ CLUSTERS.createTableOnClusterPair(haGroup, tableName, false);
// Disable replication from cluster 1 to cluster 2
ReplicationAdmin admin =
new ReplicationAdmin(CLUSTERS.getHBaseCluster1().getConfiguration());
@@ -108,12 +108,12 @@ public class ParallelPhoenixNullComparingResultSetIT {
@Test
public void testRowOnCluster1() throws SQLException {
- testRowOnCluster(CLUSTERS.getUrl1());
+ testRowOnCluster(CLUSTERS.getURL(1, haGroup.getRoleRecord().getRegistryType()));
}
@Test
public void testRowOnCluster2() throws SQLException {
- testRowOnCluster(CLUSTERS.getUrl2());
+ testRowOnCluster(CLUSTERS.getURL(2, haGroup.getRoleRecord().getRegistryType()));
}
private void testRowOnCluster(String clusterUrl) throws SQLException {
@@ -156,15 +156,15 @@ public class ParallelPhoenixNullComparingResultSetIT {
}
private void addRowToCluster1(String tableName, int id, int v) throws SQLException {
- addRowToCluster(CLUSTERS.getUrl1(), tableName, id, v);
+ addRowToCluster(CLUSTERS.getURL(1, haGroup.getRoleRecord().getRegistryType()), tableName, id, v);
}
private void addRowToCluster2(String tableName, int id, int v) throws SQLException {
- addRowToCluster(CLUSTERS.getUrl2(), tableName, id, v);
+ addRowToCluster(CLUSTERS.getURL(2, haGroup.getRoleRecord().getRegistryType()), tableName, id, v);
}
private void addRowToCluster(String url, String tableName, int id, int v) throws SQLException {
- String jdbcUrl = CLUSTERS.getJdbcUrl(url);
+ String jdbcUrl = CLUSTERS.getJdbcUrl(haGroup, url);
try (Connection conn = DriverManager.getConnection(jdbcUrl, PROPERTIES)) {
Statement stmt = conn.createStatement();
stmt.executeUpdate(String.format("UPSERT INTO %s VALUES(%d, %d)", tableName, id, v));
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolIT.java b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolIT.java
index 2edbbf8023..736f627de4 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolIT.java
@@ -17,7 +17,6 @@
*/
package org.apache.phoenix.jdbc;
-import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.hadoop.hbase.GenericTestUtils.waitFor;
import static org.apache.phoenix.jdbc.PhoenixHAAdminTool.RET_REPAIR_FOUND_INCONSISTENCIES;
import static org.apache.phoenix.jdbc.PhoenixHAAdminTool.RET_SUCCESS;
@@ -86,8 +85,8 @@ public class PhoenixHAAdminToolIT {
haGroupName = testName.getMethodName();
recordV1 = new ClusterRoleRecord(
haGroupName, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.ACTIVE,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl1(), ClusterRole.ACTIVE,
+ CLUSTERS.getZkUrl2(), ClusterRole.STANDBY,
1);
String jsonFileName = ClusterRoleRecordTest.createJsonFileWithRecords(recordV1);
int ret = admin.run(new String[]{"-m", jsonFileName});
@@ -97,8 +96,8 @@ public class PhoenixHAAdminToolIT {
// the V2 record is for the same HA group; it is created but not populated yet
recordV2 = new ClusterRoleRecord(
haGroupName, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.STANDBY,
- CLUSTERS.getUrl2(), ClusterRole.ACTIVE,
+ CLUSTERS.getZkUrl1(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl2(), ClusterRole.ACTIVE,
2);
}
@@ -148,8 +147,8 @@ public class PhoenixHAAdminToolIT {
String haGroupName2 = haGroupName + 2;
ClusterRoleRecord record2 = new ClusterRoleRecord(
haGroupName2, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.ACTIVE,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl1(), ClusterRole.ACTIVE,
+ CLUSTERS.getZkUrl2(), ClusterRole.STANDBY,
1);
// For haGroupName it's update and for haGroupName2 it's create.
String jsonFileName = ClusterRoleRecordTest.createJsonFileWithRecords(recordV2, record2);
@@ -193,8 +192,8 @@ public class PhoenixHAAdminToolIT {
ClusterRoleRecord recordV3 = new ClusterRoleRecord(
haGroupName, HighAvailabilityPolicy.FAILOVER,
- CLUSTERS.getUrl1(), ClusterRole.ACTIVE,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl1(), ClusterRole.ACTIVE,
+ CLUSTERS.getZkUrl2(), ClusterRole.STANDBY,
3);
getCurator2().setData().forPath(zpath, ClusterRoleRecord.toJson(recordV3));
doVerifyClusterRole(getCurator1(), recordV2);
@@ -215,8 +214,8 @@ public class PhoenixHAAdminToolIT {
try {
ClusterRoleRecord recordDifferent = new ClusterRoleRecord(
haGroupName, HighAvailabilityPolicy.PARALLEL,
- CLUSTERS.getUrl1(), ClusterRole.STANDBY,
- CLUSTERS.getUrl2(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl1(), ClusterRole.STANDBY,
+ CLUSTERS.getZkUrl2(), ClusterRole.STANDBY,
1);
getCurator1().setData().forPath(zpath, ClusterRoleRecord.toJson(recordDifferent));
doVerifyClusterRole(getCurator1(), recordDifferent);
@@ -315,10 +314,10 @@ public class PhoenixHAAdminToolIT {
}
private static CuratorFramework getCurator1() throws IOException {
- return HighAvailabilityGroup.getCurator(CLUSTERS.getUrl1(), new Properties());
+ return HighAvailabilityGroup.getCurator(CLUSTERS.getZkUrl1(), new Properties());
}
private static CuratorFramework getCurator2() throws IOException {
- return HighAvailabilityGroup.getCurator(CLUSTERS.getUrl2(), new Properties());
+ return HighAvailabilityGroup.getCurator(CLUSTERS.getZkUrl2(), new Properties());
}
}
diff --git a/phoenix-core/src/test/java/org/apache/phoenix/jdbc/ClusterRoleRecordTest.java b/phoenix-core/src/test/java/org/apache/phoenix/jdbc/ClusterRoleRecordTest.java
index 3c2001205d..ca1b6c559b 100644
--- a/phoenix-core/src/test/java/org/apache/phoenix/jdbc/ClusterRoleRecordTest.java
+++ b/phoenix-core/src/test/java/org/apache/phoenix/jdbc/ClusterRoleRecordTest.java
@@ -24,30 +24,54 @@ import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.phoenix.jdbc.ClusterRoleRecord.ClusterRole;
-import org.apache.phoenix.util.JDBCUtil;
import org.apache.phoenix.util.JacksonUtil;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Unit test for {@link ClusterRoleRecord}.
*/
+@RunWith(Parameterized.class)
public class ClusterRoleRecordTest {
private static final Logger LOG = LoggerFactory.getLogger(ClusterRoleRecordTest.class);
- private static final String ZK1 = "zk1-1\\:2181,zk1-2\\:2181::/hbase";
- private static final String ZK2 = "zk2-1\\:2181,zk2-2\\:2181::/hbase";
+ private static final String URL1 = "zk1-1\\:2181,zk1-2\\:2181";
+ private static final String URL2 = "zk2-1\\:2181,zk2-2\\:2181";
+ private final ClusterRoleRecord.RegistryType registryType;
@Rule
public final TestName testName = new TestName();
+ public ClusterRoleRecordTest(ClusterRoleRecord.RegistryType registryType) {
+ this.registryType = registryType;
+ }
+
+ @Parameterized.Parameters(name="ClusterRoleRecord_registryType={0}")
+ public static Collection<Object> data() {
+ return Arrays.asList(new Object[] {
+ ClusterRoleRecord.RegistryType.ZK,
+ ClusterRoleRecord.RegistryType.MASTER,
+ ClusterRoleRecord.RegistryType.RPC,
+ null //For Backward Compatibility
+ });
+ }
+
/**
* Helper method to create a temp JSON file with the given array of cluster role records.
*/
@@ -63,23 +87,50 @@ public class ClusterRoleRecordTest {
@Test
public void testReadWriteJsonToFile() throws IOException {
- ClusterRoleRecord record = new ClusterRoleRecord(
- testName.getMethodName(), HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2, ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY, 1);
String fileName = createJsonFileWithRecords(record);
String fileContent = FileUtils.readFileToString(new File(fileName), "UTF-8");
assertTrue(fileContent.contains(record.getHaGroupName()));
}
+ @Test
+ public void testOldFormatCompatibility() throws IOException {
+ String oldFormatPath = "json/test_role_record_old_format.json";
+ String newFormatPath = "json/test_role_record.json";
+ byte[] oldFormat = readFile(oldFormatPath);
+ byte[] newFormat = readFile(newFormatPath);
+ assertFalse(Arrays.equals(oldFormat, newFormat));
+
+ ClusterRoleRecord oldFormatCRR = ClusterRoleRecord.fromJson(oldFormat).get();
+ ClusterRoleRecord newFormatCRR = ClusterRoleRecord.fromJson(newFormat).get();
+ assertEquals(oldFormatCRR, newFormatCRR);
+
+ }
+
+ @Test
+ public void testUrlNullInRoleRecord() throws IOException {
+ String wrongFormatPath = "json/test_role_record_wrong_format.json";
+ String wrongFormatForRolePath = "json/test_role_record_wrong_role_format.json";
+ byte[] roleRecord = readFile(wrongFormatPath);
+ byte[] roleRecordWithWrongRole = readFile(wrongFormatForRolePath);
+
+ Optional<ClusterRoleRecord> record = ClusterRoleRecord.fromJson(roleRecord);
+ //We should get empty object as url is missing in ClusterRoleRecord
+ assertEquals(record, Optional.empty());
+
+
+ Optional<ClusterRoleRecord> recordWithNullRole = ClusterRoleRecord.fromJson(roleRecordWithWrongRole);
+ //We should get empty object as role is missing in ClusterRoleRecord
+ assertEquals(record, Optional.empty());
+ }
+
@Test
public void testToAndFromJson() throws IOException {
- ClusterRoleRecord record = new ClusterRoleRecord(
- testName.getMethodName(), HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2, ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,1);
byte[] bytes = ClusterRoleRecord.toJson(record);
Optional<ClusterRoleRecord> record2 = ClusterRoleRecord.fromJson(bytes);
assertTrue(record2.isPresent());
@@ -88,39 +139,28 @@ public class ClusterRoleRecordTest {
@Test
public void testGetActiveUrl() {
- String haGroupName = testName.getMethodName();
- {
- ClusterRoleRecord record = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2, ClusterRole.STANDBY,
- 0);
- assertTrue(record.getActiveUrl().isPresent());
- assertEquals(ZK1, record.getActiveUrl().get());
- }
- {
- ClusterRoleRecord record = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.STANDBY,
- ZK2, ClusterRole.STANDBY,
- 0);
- assertFalse(record.getActiveUrl().isPresent());
- }
+ ClusterRoleRecord record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,0);
+ assertTrue(record.getActiveUrl().isPresent());
+ assertEquals(getUrlWithSuffix(URL1), record.getActiveUrl().get());
+
+ record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.STANDBY,
+ URL2, ClusterRole.STANDBY, 0);
+ assertFalse(record.getActiveUrl().isPresent());
+
}
@Test
public void testIsNewerThan() {
String haGroupName = testName.getMethodName();
- ClusterRoleRecord recordV0 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.STANDBY,
- ZK2 , ClusterRole.STANDBY,
- 0);
- ClusterRoleRecord recordV1 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.STANDBY,
- ZK2 , ClusterRole.STANDBY,
- 2);
+ ClusterRoleRecord recordV0 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.STANDBY,
+ URL2, ClusterRole.STANDBY,0);
+ ClusterRoleRecord recordV1 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.STANDBY,
+ URL2, ClusterRole.STANDBY,2);
assertTrue(recordV1.isNewerThan(recordV0)); // v1 is indeed newer
assertFalse(recordV1.isNewerThan(recordV1)); // irreflexive
assertFalse(recordV0.isNewerThan(recordV1)); // antisymmetry
@@ -129,11 +169,9 @@ public class ClusterRoleRecordTest {
// Cluster role records for different HA groups can not compare in reality,
// so they are not newer than each other.
String haGroupName2 = haGroupName + RandomStringUtils.randomAlphabetic(2);
- ClusterRoleRecord record2 = new ClusterRoleRecord(
- haGroupName2, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.STANDBY,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record2 = getClusterRoleRecord(haGroupName2,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.STANDBY,
+ URL2, ClusterRole.STANDBY, 1);
assertFalse(recordV0.isNewerThan(record2));
assertFalse(recordV1.isNewerThan(record2));
assertFalse(record2.isNewerThan(recordV0));
@@ -143,16 +181,12 @@ public class ClusterRoleRecordTest {
@Test
public void testHasSameInfo() {
String haGroupName = testName.getMethodName();
- ClusterRoleRecord recordV0 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 0);
- ClusterRoleRecord recordV1 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord recordV0 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,0);
+ ClusterRoleRecord recordV1 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY, 1);
assertTrue(recordV1.hasSameInfo(recordV0));
assertTrue(recordV1.hasSameInfo(recordV1));
assertTrue(recordV0.hasSameInfo(recordV1));
@@ -161,16 +195,12 @@ public class ClusterRoleRecordTest {
@Test
public void testHasSameInfoDifferentZKOrder() {
String haGroupName = testName.getMethodName();
- ClusterRoleRecord recordV0 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK2, ClusterRole.ACTIVE,
- ZK1 , ClusterRole.STANDBY,
- 0);
- ClusterRoleRecord recordV1 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord recordV0 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL2, ClusterRole.ACTIVE,
+ URL1, ClusterRole.STANDBY, 0);
+ ClusterRoleRecord recordV1 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY, 1);
assertTrue(recordV1.hasSameInfo(recordV0));
assertTrue(recordV1.hasSameInfo(recordV1));
assertTrue(recordV0.hasSameInfo(recordV1));
@@ -178,19 +208,15 @@ public class ClusterRoleRecordTest {
@Test
public void testHasSameInfoDifferentHostOrder() {
- String hostzk1ordered = "zk1-1,zk1-2:2181:/hbase";
- String hostzk1unordered = "zk1-2,zk1-1:2181:/hbase";
+ String hostzk1ordered = "zk1-1,zk1-2:2181";
+ String hostzk1unordered = "zk1-2,zk1-1:2181";
String haGroupName = testName.getMethodName();
- ClusterRoleRecord recordV0 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK2, ClusterRole.ACTIVE,
- hostzk1ordered , ClusterRole.STANDBY,
- 0);
- ClusterRoleRecord recordV1 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- hostzk1unordered, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord recordV0 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL2, ClusterRole.ACTIVE,
+ hostzk1ordered, ClusterRole.STANDBY, 0);
+ ClusterRoleRecord recordV1 = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, hostzk1unordered, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,1);
assertTrue(recordV1.hasSameInfo(recordV0));
assertTrue(recordV1.hasSameInfo(recordV1));
assertTrue(recordV0.hasSameInfo(recordV1));
@@ -199,53 +225,91 @@ public class ClusterRoleRecordTest {
@Test
public void testHasSameInfoNegative() {
String haGroupName = testName.getMethodName();
- ClusterRoleRecord record = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.PARALLEL,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 0);
-
- ClusterRoleRecord recordFailover = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.PARALLEL, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,0);
+
+ ClusterRoleRecord recordFailover = getClusterRoleRecord(haGroupName,
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,1);
assertFalse(record.hasSameInfo(recordFailover));
assertFalse(recordFailover.hasSameInfo(record));
String haGroupName2 = haGroupName + RandomStringUtils.randomAlphabetic(2);
- ClusterRoleRecord record2 = new ClusterRoleRecord(
- haGroupName2, HighAvailabilityPolicy.PARALLEL,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record2 = getClusterRoleRecord(haGroupName2,
+ HighAvailabilityPolicy.PARALLEL, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,1);
assertFalse(record.hasSameInfo(record2));
assertFalse(record2.hasSameInfo(record));
}
@Test
public void testGetRole() {
- ClusterRoleRecord record = new ClusterRoleRecord(
- testName.getMethodName(), HighAvailabilityPolicy.FAILOVER,
- ZK1, ClusterRole.ACTIVE,
- ZK2 , ClusterRole.STANDBY,
- 0);
- assertEquals(ClusterRole.ACTIVE, record.getRole(ZK1));
- assertEquals(ClusterRole.ACTIVE, record.getRole(record.getZk1()));
- assertEquals(ClusterRole.STANDBY, record.getRole(record.getZk2()));
+ ClusterRoleRecord record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.FAILOVER, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,0);
+ assertEquals(ClusterRole.ACTIVE, record.getRole(getUrlWithSuffix(URL1)));
+ assertEquals(ClusterRole.ACTIVE, record.getRole(record.getUrl1()));
+ assertEquals(ClusterRole.STANDBY, record.getRole(record.getUrl2()));
assertEquals(ClusterRole.UNKNOWN, record.getRole(null));
assertEquals(ClusterRole.UNKNOWN, record.getRole("foo"));
}
@Test
public void testToPrettyString() {
- ClusterRoleRecord record = new ClusterRoleRecord(
- testName.getMethodName(), HighAvailabilityPolicy.PARALLEL,
- ZK1, ClusterRole.ACTIVE,
- ZK2, ClusterRole.STANDBY,
- 1);
+ ClusterRoleRecord record = getClusterRoleRecord(testName.getMethodName(),
+ HighAvailabilityPolicy.PARALLEL, URL1, ClusterRole.ACTIVE,
+ URL2, ClusterRole.STANDBY,1);
LOG.info("toString(): {}", record.toString());
LOG.info("toPrettyString:\n{}", record.toPrettyString());
assertNotEquals(record.toString(), record.toPrettyString());
}
+
+ //Private Helper Methods
+
+ private ClusterRoleRecord getClusterRoleRecord(String name, HighAvailabilityPolicy policy,
+ String url1, ClusterRole role1, String url2, ClusterRole role2, int version) {
+ url1 = getUrlWithSuffix(url1);
+ url2 = getUrlWithSuffix(url2);
+ if (registryType == null) {
+ return new ClusterRoleRecord(
+ name, policy,
+ url1, role1,
+ url2, role2,
+ version);
+ } else {
+ return new ClusterRoleRecord(
+ name, policy,
+ registryType,
+ url1, role1,
+ url2, role2,
+ version);
+ }
+ }
+
+ private String getUrlWithSuffix(String url) {
+ if (registryType == null) {
+ return url + "::/hbase";
+ }
+ switch (registryType){
+ case MASTER:
+ case RPC:
+ return url;
+ case ZK:
+ default:
+ return url + "::/hbase";
+ }
+ }
+
+ private byte[] readFile(String fileName) throws IOException {
+ InputStream inputStream = ClusterRoleRecordTest.class.getClassLoader().getResourceAsStream(fileName);
+ assert inputStream != null;
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ byte[] temp = new byte[1024];
+ int bytesRead;
+ while ((bytesRead = inputStream.read(temp)) != -1) {
+ buffer.write(temp, 0, bytesRead);
+ }
+ return buffer.toByteArray();
+ }
}
diff --git a/phoenix-core/src/test/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolTest.java b/phoenix-core/src/test/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolTest.java
index e00d15c515..fa88b5909a 100644
--- a/phoenix-core/src/test/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolTest.java
+++ b/phoenix-core/src/test/java/org/apache/phoenix/jdbc/PhoenixHAAdminToolTest.java
@@ -205,25 +205,6 @@ public class PhoenixHAAdminToolTest {
verify(curator, atLeastOnce()).newNamespaceAwareEnsurePath(contains(haGroupName));
}
- /**
- * Test that agent rejects to deal with the record if it is not associated to this ZK.
- */
- @Test
- public void testFailWithUnrelatedRecord() {
- ClusterRoleRecord record2 = new ClusterRoleRecord(
- haGroupName, HighAvailabilityPolicy.FAILOVER,
- ZK1 + RandomStringUtils.random(3), ClusterRole.ACTIVE, // unrelated ZK
- ZK2 + RandomStringUtils.random(3), ClusterRole.STANDBY, // unrelated ZK
- 1);
- try {
- admin.createOrUpdateDataOnZookeeper(record2);
- } catch (IOException e) {
- LOG.info("Got expected exception since the record is not totally related to this ZK");
- assertTrue(e.getMessage().contains("INTERNAL ERROR"));
- }
- verify(curator, never()).getData(); // not even try to read the znode
- }
-
/**
* Test that agent rejects to update the record if its version is lower.
*/
diff --git a/phoenix-core/src/test/java/org/apache/phoenix/util/JDBCUtilTest.java b/phoenix-core/src/test/java/org/apache/phoenix/util/JDBCUtilTest.java
index 11add1ffcb..31e30fe856 100644
--- a/phoenix-core/src/test/java/org/apache/phoenix/util/JDBCUtilTest.java
+++ b/phoenix-core/src/test/java/org/apache/phoenix/util/JDBCUtilTest.java
@@ -145,7 +145,7 @@ public class JDBCUtilTest {
@Test
public void formatZookeeperUrlSameOrderTest() {
String zk1 = "zk1.net\\:2181,zk2.net\\:2181,zk3.net\\:2181::/hbase";
- String result = JDBCUtil.formatZookeeperUrl(zk1);
+ String result = JDBCUtil.formatUrl(zk1);
assertEquals(zk1,result);
}
@@ -153,21 +153,21 @@ public class JDBCUtilTest {
@Test
public void formatZookeeperUrlDifferentOrderTest() {
String zk1 = "zk3.net,zk2.net,zk1.net:2181:/hbase";
- String result = JDBCUtil.formatZookeeperUrl(zk1);
+ String result = JDBCUtil.formatUrl(zk1);
assertEquals("zk1.net\\:2181,zk2.net\\:2181,zk3.net\\:2181::/hbase",result);
}
@Test
public void formatZookeeperUrlNoTrailersTest() {
String zk1 = "zk1.net,zk2.net,zk3.net";
- String result = JDBCUtil.formatZookeeperUrl(zk1);
+ String result = JDBCUtil.formatUrl(zk1);
assertEquals("zk1.net\\:2181,zk2.net\\:2181,zk3.net\\:2181::/hbase",result);
}
@Test
public void formatZookeeperUrlToLowercaseTest() {
String zk1 = "MYHOST1.NET,MYHOST2.NET";
- String result = JDBCUtil.formatZookeeperUrl(zk1);
+ String result = JDBCUtil.formatUrl(zk1);
assertEquals("myhost1.net\\:2181,myhost2.net\\:2181::/hbase",result);
}
diff --git a/phoenix-core/src/test/resources/json/test_role_record.json b/phoenix-core/src/test/resources/json/test_role_record.json
new file mode 100644
index 0000000000..b7c9ac4e7f
--- /dev/null
+++ b/phoenix-core/src/test/resources/json/test_role_record.json
@@ -0,0 +1,10 @@
+{
+ "haGroupName" : "testReadRecordsFromFileJson",
+ "policy" : "FAILOVER",
+ "registryType" : "ZK",
+ "url1" : "zk1\\:2181::/hbase",
+ "role1" : "ACTIVE",
+ "url2" : "zk2\\:2181::/hbase",
+ "role2" : "STANDBY",
+ "version" : 1
+}
\ No newline at end of file
diff --git a/phoenix-core/src/test/resources/json/test_role_record_old_format.json b/phoenix-core/src/test/resources/json/test_role_record_old_format.json
new file mode 100644
index 0000000000..320d30acd3
--- /dev/null
+++ b/phoenix-core/src/test/resources/json/test_role_record_old_format.json
@@ -0,0 +1,9 @@
+{
+ "haGroupName" : "testReadRecordsFromFileJson",
+ "policy" : "FAILOVER",
+ "zk1" : "zk1\\:2181::/hbase",
+ "role1" : "ACTIVE",
+ "zk2" : "zk2\\:2181::/hbase",
+ "role2" : "STANDBY",
+ "version" : 1
+}
\ No newline at end of file
diff --git a/phoenix-core/src/test/resources/json/test_role_record_wrong_format.json b/phoenix-core/src/test/resources/json/test_role_record_wrong_format.json
new file mode 100644
index 0000000000..dc566c33da
--- /dev/null
+++ b/phoenix-core/src/test/resources/json/test_role_record_wrong_format.json
@@ -0,0 +1,9 @@
+{
+ "haGroupName" : "testReadRecordsFromFileJson",
+ "policy" : "FAILOVER",
+ "registryType" : "ZK",
+ "url1" : "zk1\\:2181::/hbase",
+ "role1" : "ACTIVE",
+ "role2" : "STANDBY",
+ "version" : 1
+}
\ No newline at end of file
diff --git a/phoenix-core/src/test/resources/json/test_role_record_wrong_role_format.json b/phoenix-core/src/test/resources/json/test_role_record_wrong_role_format.json
new file mode 100644
index 0000000000..a5768d1a4a
--- /dev/null
+++ b/phoenix-core/src/test/resources/json/test_role_record_wrong_role_format.json
@@ -0,0 +1,9 @@
+{
+ "haGroupName" : "testReadRecordsFromFileJson",
+ "policy" : "FAILOVER",
+ "registryType" : "ZK",
+ "url1" : "zk1\\:2181::/hbase",
+ "url2" : "zk2\\:2181::/hbase",
+ "role2" : "STANDBY",
+ "version" : 1
+}
\ No newline at end of file