You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zookeeper.apache.org by an...@apache.org on 2018/10/05 12:26:13 UTC
[20/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN
MIGRATION - move java server, client
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/StateSummary.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/StateSummary.java b/src/java/main/org/apache/zookeeper/server/quorum/StateSummary.java
deleted file mode 100644
index aaaa4f8..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/StateSummary.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * 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.zookeeper.server.quorum;
-
-/**
- * This class encapsulates the state comparison logic. Specifically,
- * how two different states are compared.
- */
-public class StateSummary {
- private long currentEpoch;
- private long lastZxid;
- public StateSummary(long currentEpoch, long lastZxid) {
- this.currentEpoch = currentEpoch;
- this.lastZxid = lastZxid;
- }
-
- public long getCurrentEpoch() {
- return currentEpoch;
- }
-
- public long getLastZxid() {
- return lastZxid;
- }
-
- public boolean isMoreRecentThan(StateSummary ss) {
- return (currentEpoch > ss.currentEpoch) || (currentEpoch == ss.currentEpoch && lastZxid > ss.lastZxid);
- }
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof StateSummary)) {
- return false;
- }
- StateSummary ss = (StateSummary)obj;
- return currentEpoch == ss.currentEpoch && lastZxid == ss.lastZxid;
- }
-
- @Override
- public int hashCode() {
- return (int)(currentEpoch ^ lastZxid);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/SyncedLearnerTracker.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/SyncedLearnerTracker.java b/src/java/main/org/apache/zookeeper/server/quorum/SyncedLearnerTracker.java
deleted file mode 100644
index d773119..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/SyncedLearnerTracker.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * 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.zookeeper.server.quorum;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
-
-public class SyncedLearnerTracker {
-
- protected ArrayList<QuorumVerifierAcksetPair> qvAcksetPairs =
- new ArrayList<QuorumVerifierAcksetPair>();
-
- public void addQuorumVerifier(QuorumVerifier qv) {
- qvAcksetPairs.add(new QuorumVerifierAcksetPair(qv,
- new HashSet<Long>(qv.getVotingMembers().size())));
- }
-
- public boolean addAck(Long sid) {
- boolean change = false;
- for (QuorumVerifierAcksetPair qvAckset : qvAcksetPairs) {
- if (qvAckset.getQuorumVerifier().getVotingMembers().containsKey(sid)) {
- qvAckset.getAckset().add(sid);
- change = true;
- }
- }
- return change;
- }
-
- public boolean hasSid(long sid) {
- for (QuorumVerifierAcksetPair qvAckset : qvAcksetPairs) {
- if (!qvAckset.getQuorumVerifier().getVotingMembers().containsKey(sid)) {
- return false;
- }
- }
- return true;
- }
-
- public boolean hasAllQuorums() {
- for (QuorumVerifierAcksetPair qvAckset : qvAcksetPairs) {
- if (!qvAckset.getQuorumVerifier().containsQuorum(qvAckset.getAckset()))
- return false;
- }
- return true;
- }
-
- public String ackSetsToString(){
- StringBuilder sb = new StringBuilder();
-
- for (QuorumVerifierAcksetPair qvAckset : qvAcksetPairs) {
- sb.append(qvAckset.getAckset().toString()).append(",");
- }
-
- return sb.substring(0, sb.length()-1);
- }
-
- public static class QuorumVerifierAcksetPair {
- private final QuorumVerifier qv;
- private final HashSet<Long> ackset;
-
- public QuorumVerifierAcksetPair(QuorumVerifier qv, HashSet<Long> ackset) {
- this.qv = qv;
- this.ackset = ackset;
- }
-
- public QuorumVerifier getQuorumVerifier() {
- return this.qv;
- }
-
- public HashSet<Long> getAckset() {
- return this.ackset;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/UpgradeableSessionTracker.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/UpgradeableSessionTracker.java b/src/java/main/org/apache/zookeeper/server/quorum/UpgradeableSessionTracker.java
deleted file mode 100644
index 157b06e..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/UpgradeableSessionTracker.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * 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.zookeeper.server.quorum;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.server.SessionTracker;
-import org.apache.zookeeper.server.ZooKeeperServerListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A session tracker that supports upgradeable local sessions.
- */
-public abstract class UpgradeableSessionTracker implements SessionTracker {
- private static final Logger LOG = LoggerFactory.getLogger(UpgradeableSessionTracker.class);
-
- private ConcurrentMap<Long, Integer> localSessionsWithTimeouts;
- private ConcurrentMap<Long, Integer> upgradingSessions;
- protected LocalSessionTracker localSessionTracker;
- protected boolean localSessionsEnabled;
-
- public void start() {}
-
- public void createLocalSessionTracker(SessionExpirer expirer,
- int tickTime, long id, ZooKeeperServerListener listener) {
- this.localSessionsWithTimeouts =
- new ConcurrentHashMap<Long, Integer>();
- this.localSessionTracker = new LocalSessionTracker(
- expirer, this.localSessionsWithTimeouts, tickTime, id, listener);
- this.upgradingSessions = new ConcurrentHashMap<Long, Integer>();
- }
-
- public boolean isTrackingSession(long sessionId) {
- return isLocalSession(sessionId) || isGlobalSession(sessionId);
- }
-
- public boolean isLocalSession(long sessionId) {
- return localSessionTracker != null &&
- localSessionTracker.isTrackingSession(sessionId);
- }
-
- public boolean isUpgradingSession(long sessionId) {
- return upgradingSessions != null &&
- upgradingSessions.containsKey(sessionId);
- }
-
- public void finishedUpgrading(long sessionId) {
- if (upgradingSessions != null) {
- upgradingSessions.remove(sessionId);
- }
- }
-
- abstract public boolean isGlobalSession(long sessionId);
-
- /**
- * Upgrades the session to a global session.
- * This simply removes the session from the local tracker and marks
- * it as global. It is up to the caller to actually
- * queue up a transaction for the session.
- *
- * @param sessionId
- * @return session timeout (-1 if not a local session)
- */
- public int upgradeSession(long sessionId) {
- if (localSessionsWithTimeouts == null) {
- return -1;
- }
- // We won't race another upgrade attempt because only one thread
- // will get the timeout from the map
- Integer timeout = localSessionsWithTimeouts.remove(sessionId);
- if (timeout != null) {
- LOG.info("Upgrading session 0x" + Long.toHexString(sessionId));
- // Track global session, which will add to global session tracker
- // on leader and do nothing on learner. Need to start track global
- // session in leader now to update the session expire between
- // LeaderRequestProcessor and PrepRequestProcessor.
- trackSession(sessionId, timeout);
- // Track ongoing upgrading sessions, learner will use it to find
- // other sessions it has which are not in local and global sessions
- upgradingSessions.put(sessionId, timeout);
- localSessionTracker.removeSession(sessionId);
- return timeout;
- }
- return -1;
- }
-
- protected void removeLocalSession(long sessionId) {
- if (localSessionTracker == null) {
- return;
- }
- localSessionTracker.removeSession(sessionId);
- }
-
- public void checkGlobalSession(long sessionId, Object owner)
- throws KeeperException.SessionExpiredException,
- KeeperException.SessionMovedException {
- throw new UnsupportedOperationException();
- }
-
- public long getLocalSessionCount() {
- if (localSessionsWithTimeouts == null) {
- return 0;
- }
- return localSessionsWithTimeouts.size();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/Vote.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/Vote.java b/src/java/main/org/apache/zookeeper/server/quorum/Vote.java
deleted file mode 100644
index 8152c66..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/Vote.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * 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.zookeeper.server.quorum;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
-
-
-public class Vote {
-
- public Vote(long id,
- long zxid) {
- this.version = 0x0;
- this.id = id;
- this.zxid = zxid;
- this.electionEpoch = -1;
- this.peerEpoch = -1;
- this.state = ServerState.LOOKING;
- }
-
- public Vote(long id,
- long zxid,
- long peerEpoch) {
- this.version = 0x0;
- this.id = id;
- this.zxid = zxid;
- this.electionEpoch = -1;
- this.peerEpoch = peerEpoch;
- this.state = ServerState.LOOKING;
- }
-
- public Vote(long id,
- long zxid,
- long electionEpoch,
- long peerEpoch) {
- this.version = 0x0;
- this.id = id;
- this.zxid = zxid;
- this.electionEpoch = electionEpoch;
- this.peerEpoch = peerEpoch;
- this.state = ServerState.LOOKING;
- }
-
- public Vote(int version,
- long id,
- long zxid,
- long electionEpoch,
- long peerEpoch,
- ServerState state) {
- this.version = version;
- this.id = id;
- this.zxid = zxid;
- this.electionEpoch = electionEpoch;
- this.state = state;
- this.peerEpoch = peerEpoch;
- }
-
- public Vote(long id,
- long zxid,
- long electionEpoch,
- long peerEpoch,
- ServerState state) {
- this.id = id;
- this.zxid = zxid;
- this.electionEpoch = electionEpoch;
- this.state = state;
- this.peerEpoch = peerEpoch;
- this.version = 0x0;
- }
-
- final private int version;
-
- final private long id;
-
- final private long zxid;
-
- final private long electionEpoch;
-
- final private long peerEpoch;
-
- public int getVersion() {
- return version;
- }
-
- public long getId() {
- return id;
- }
-
- public long getZxid() {
- return zxid;
- }
-
- public long getElectionEpoch() {
- return electionEpoch;
- }
-
- public long getPeerEpoch() {
- return peerEpoch;
- }
-
- public ServerState getState() {
- return state;
- }
-
- final private ServerState state;
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof Vote)) {
- return false;
- }
- Vote other = (Vote) o;
- return (id == other.id
- && zxid == other.zxid
- && electionEpoch == other.electionEpoch
- && peerEpoch == other.peerEpoch);
-
- }
-
- @Override
- public int hashCode() {
- return (int) (id & zxid);
- }
-
- public String toString() {
- return "(" + id + ", " + Long.toHexString(zxid) + ", " + Long.toHexString(peerEpoch) + ")";
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthLearner.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthLearner.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthLearner.java
deleted file mode 100644
index 0af891c..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthLearner.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.net.Socket;
-
-/**
- * This class represents no authentication learner, it just return
- * without performing any authentication.
- */
-public class NullQuorumAuthLearner implements QuorumAuthLearner {
-
- @Override
- public void authenticate(Socket sock, String hostname) {
- return; // simply return don't require auth
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthServer.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthServer.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthServer.java
deleted file mode 100644
index b26a54a..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/NullQuorumAuthServer.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.DataInputStream;
-import java.net.Socket;
-
-/**
- * This class represents no authentication server, it just return
- * without performing any authentication.
- */
-public class NullQuorumAuthServer implements QuorumAuthServer {
-
- @Override
- public void authenticate(final Socket sock, final DataInputStream din) {
- return; // simply return don't require auth
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuth.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuth.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuth.java
deleted file mode 100644
index 8bfa394..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuth.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.DataInputStream;
-import java.io.IOException;
-import org.apache.jute.BinaryInputArchive;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.zookeeper.server.quorum.QuorumAuthPacket;
-
-public class QuorumAuth {
- private static final Logger LOG = LoggerFactory.getLogger(QuorumAuth.class);
-
- public static final String QUORUM_SASL_AUTH_ENABLED = "quorum.auth.enableSasl";
- public static final String QUORUM_SERVER_SASL_AUTH_REQUIRED = "quorum.auth.serverRequireSasl";
- public static final String QUORUM_LEARNER_SASL_AUTH_REQUIRED = "quorum.auth.learnerRequireSasl";
-
- public static final String QUORUM_KERBEROS_SERVICE_PRINCIPAL = "quorum.auth.kerberos.servicePrincipal";
- public static final String QUORUM_KERBEROS_SERVICE_PRINCIPAL_DEFAULT_VALUE = "zkquorum/localhost";
-
- public static final String QUORUM_LEARNER_SASL_LOGIN_CONTEXT = "quorum.auth.learner.saslLoginContext";
- public static final String QUORUM_LEARNER_SASL_LOGIN_CONTEXT_DFAULT_VALUE = "QuorumLearner";
-
- public static final String QUORUM_SERVER_SASL_LOGIN_CONTEXT = "quorum.auth.server.saslLoginContext";
- public static final String QUORUM_SERVER_SASL_LOGIN_CONTEXT_DFAULT_VALUE = "QuorumServer";
-
- static final String QUORUM_SERVER_PROTOCOL_NAME = "zookeeper-quorum";
- static final String QUORUM_SERVER_SASL_DIGEST = "zk-quorum-sasl-md5";
- static final String QUORUM_AUTH_MESSAGE_TAG = "qpconnect";
-
- // this is negative, so that if a learner that does auth, connects to a
- // server, it'll think the received packet is an authentication packet
- public static final long QUORUM_AUTH_MAGIC_NUMBER = -0xa0dbcafecafe1234L;
-
- public enum Status {
- IN_PROGRESS(0), SUCCESS(1), ERROR(-1);
- private int status;
-
- Status(int status) {
- this.status = status;
- }
-
- static Status getStatus(int status) {
- switch (status) {
- case 0:
- return IN_PROGRESS;
- case 1:
- return SUCCESS;
- case -1:
- return ERROR;
- default:
- LOG.error("Unknown status:{}!", status);
- assert false : "Unknown status!";
- return ERROR;
- }
- }
-
- int status() {
- return status;
- }
- }
-
- public static QuorumAuthPacket createPacket(Status status, byte[] response) {
- return new QuorumAuthPacket(QUORUM_AUTH_MAGIC_NUMBER,
- status.status(), response);
- }
-
- public static boolean nextPacketIsAuth(DataInputStream din)
- throws IOException {
- din.mark(32);
- BinaryInputArchive bia = new BinaryInputArchive(din);
- boolean firstIsAuth = (bia.readLong("NO_TAG")
- == QuorumAuth.QUORUM_AUTH_MAGIC_NUMBER);
- din.reset();
- return firstIsAuth;
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthLearner.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthLearner.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthLearner.java
deleted file mode 100644
index af71257..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthLearner.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.IOException;
-import java.net.Socket;
-
-/**
- * Interface for quorum learner authentication mechanisms.
- */
-public interface QuorumAuthLearner {
-
- /**
- * Performs an authentication step for the given socket connection.
- *
- * @param sock
- * socket connection to other quorum peer server
- * @param hostname
- * host name of other quorum peer server
- * @throws IOException
- * if there is an authentication failure
- */
- public void authenticate(Socket sock, String hostname) throws IOException;
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthServer.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthServer.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthServer.java
deleted file mode 100644
index e9de8f0..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/QuorumAuthServer.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.net.Socket;
-
-/**
- * Interface for quorum server authentication mechanisms.
- */
-public interface QuorumAuthServer {
-
- /**
- * Performs an authentication step for the given socket connection.
- *
- * @param sock
- * socket connection to other quorum peer
- * @param din
- * stream used to read auth data send by the quorum learner
- * @throws IOException if the server fails to authenticate connecting quorum learner
- */
- public void authenticate(Socket sock, DataInputStream din)
- throws IOException;
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthLearner.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthLearner.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthLearner.java
deleted file mode 100644
index 31f4f55..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthLearner.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.net.Socket;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
-import javax.security.auth.login.LoginException;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.zookeeper.Login;
-import org.apache.zookeeper.SaslClientCallbackHandler;
-import org.apache.zookeeper.common.ZKConfig;
-import org.apache.zookeeper.server.quorum.QuorumAuthPacket;
-import org.apache.zookeeper.util.SecurityUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SaslQuorumAuthLearner implements QuorumAuthLearner {
- private static final Logger LOG = LoggerFactory
- .getLogger(SaslQuorumAuthLearner.class);
-
- private final Login learnerLogin;
- private final boolean quorumRequireSasl;
- private final String quorumServicePrincipal;
-
- public SaslQuorumAuthLearner(boolean quorumRequireSasl,
- String quorumServicePrincipal, String loginContext)
- throws SaslException {
- this.quorumRequireSasl = quorumRequireSasl;
- this.quorumServicePrincipal = quorumServicePrincipal;
- try {
- AppConfigurationEntry entries[] = Configuration
- .getConfiguration()
- .getAppConfigurationEntry(loginContext);
- if (entries == null || entries.length == 0) {
- throw new LoginException("SASL-authentication failed because"
- + " the specified JAAS configuration "
- + "section '" + loginContext
- + "' could not be found.");
- }
- this.learnerLogin = new Login(loginContext,
- new SaslClientCallbackHandler(null, "QuorumLearner"), new ZKConfig());
- this.learnerLogin.startThreadIfNeeded();
- } catch (LoginException e) {
- throw new SaslException("Failed to initialize authentication mechanism using SASL", e);
- }
- }
-
- @Override
- public void authenticate(Socket sock, String hostName) throws IOException {
- if (!quorumRequireSasl) { // let it through, we don't require auth
- LOG.info("Skipping SASL authentication as {}={}",
- QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED,
- quorumRequireSasl);
- return;
- }
- SaslClient sc = null;
- String principalConfig = SecurityUtils
- .getServerPrincipal(quorumServicePrincipal, hostName);
- try {
- DataOutputStream dout = new DataOutputStream(
- sock.getOutputStream());
- DataInputStream din = new DataInputStream(sock.getInputStream());
- byte[] responseToken = new byte[0];
- sc = SecurityUtils.createSaslClient(learnerLogin.getSubject(),
- principalConfig,
- QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME,
- QuorumAuth.QUORUM_SERVER_SASL_DIGEST, LOG, "QuorumLearner");
-
- if (sc.hasInitialResponse()) {
- responseToken = createSaslToken(new byte[0], sc, learnerLogin);
- }
- send(dout, responseToken);
- QuorumAuthPacket authPacket = receive(din);
- QuorumAuth.Status qpStatus = QuorumAuth.Status
- .getStatus(authPacket.getStatus());
- while (!sc.isComplete()) {
- switch (qpStatus) {
- case SUCCESS:
- responseToken = createSaslToken(authPacket.getToken(), sc,
- learnerLogin);
- // we're done; don't expect to send another BIND
- if (responseToken != null) {
- throw new SaslException("Protocol error: attempting to send response after completion");
- }
- break;
- case IN_PROGRESS:
- responseToken = createSaslToken(authPacket.getToken(), sc,
- learnerLogin);
- send(dout, responseToken);
- authPacket = receive(din);
- qpStatus = QuorumAuth.Status
- .getStatus(authPacket.getStatus());
- break;
- case ERROR:
- throw new SaslException(
- "Authentication failed against server addr: "
- + sock.getRemoteSocketAddress());
- default:
- LOG.warn("Unknown status:{}!", qpStatus);
- throw new SaslException(
- "Authentication failed against server addr: "
- + sock.getRemoteSocketAddress());
- }
- }
-
- // Validate status code at the end of authentication exchange.
- checkAuthStatus(sock, qpStatus);
- } finally {
- if (sc != null) {
- try {
- sc.dispose();
- } catch (SaslException e) {
- LOG.error("SaslClient dispose() failed", e);
- }
- }
- }
- return;
- }
-
- private void checkAuthStatus(Socket sock, QuorumAuth.Status qpStatus)
- throws SaslException {
- if (qpStatus == QuorumAuth.Status.SUCCESS) {
- LOG.info("Successfully completed the authentication using SASL. server addr: {}, status: {}",
- sock.getRemoteSocketAddress(), qpStatus);
- } else {
- throw new SaslException("Authentication failed against server addr: "
- + sock.getRemoteSocketAddress() + ", qpStatus: "
- + qpStatus);
- }
- }
-
- private QuorumAuthPacket receive(DataInputStream din) throws IOException {
- QuorumAuthPacket authPacket = new QuorumAuthPacket();
- BinaryInputArchive bia = BinaryInputArchive.getArchive(din);
- authPacket.deserialize(bia, QuorumAuth.QUORUM_AUTH_MESSAGE_TAG);
- return authPacket;
- }
-
- private void send(DataOutputStream dout, byte[] response)
- throws IOException {
- QuorumAuthPacket authPacket;
- BufferedOutputStream bufferedOutput = new BufferedOutputStream(dout);
- BinaryOutputArchive boa = BinaryOutputArchive
- .getArchive(bufferedOutput);
- authPacket = QuorumAuth.createPacket(
- QuorumAuth.Status.IN_PROGRESS, response);
- boa.writeRecord(authPacket, QuorumAuth.QUORUM_AUTH_MESSAGE_TAG);
- bufferedOutput.flush();
- }
-
- // TODO: need to consolidate the #createSaslToken() implementation between ZooKeeperSaslClient#createSaslToken().
- private byte[] createSaslToken(final byte[] saslToken,
- final SaslClient saslClient, final Login login)
- throws SaslException {
- if (saslToken == null) {
- throw new SaslException(
- "Error in authenticating with a Zookeeper Quorum member: the quorum member's saslToken is null.");
- }
- if (login.getSubject() != null) {
- synchronized (login) {
- try {
- final byte[] retval = Subject.doAs(login.getSubject(),
- new PrivilegedExceptionAction<byte[]>() {
- public byte[] run() throws SaslException {
- LOG.debug("saslClient.evaluateChallenge(len="
- + saslToken.length + ")");
- return saslClient.evaluateChallenge(saslToken);
- }
- });
- return retval;
- } catch (PrivilegedActionException e) {
- String error = "An error: (" + e
- + ") occurred when evaluating Zookeeper Quorum Member's "
- + " received SASL token.";
- // Try to provide hints to use about what went wrong so they
- // can fix their configuration.
- // TODO: introspect about e: look for GSS information.
- final String UNKNOWN_SERVER_ERROR_TEXT = "(Mechanism level: Server not found in Kerberos database (7) - UNKNOWN_SERVER)";
- if (e.toString().indexOf(UNKNOWN_SERVER_ERROR_TEXT) > -1) {
- error += " This may be caused by Java's being unable to resolve the Zookeeper Quorum Member's"
- + " hostname correctly. You may want to try to adding"
- + " '-Dsun.net.spi.nameservice.provider.1=dns,sun' to your server's JVMFLAGS environment.";
- }
- LOG.error(error);
- throw new SaslException(error);
- }
- }
- } else {
- throw new SaslException(
- "Cannot make SASL token without subject defined. "
- + "For diagnosis, please look for WARNs and ERRORs in your log related to the Login class.");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthServer.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthServer.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthServer.java
deleted file mode 100644
index fc5e3b6..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumAuthServer.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.net.Socket;
-import java.util.Set;
-
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
-import javax.security.auth.login.LoginException;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.zookeeper.Login;
-import org.apache.zookeeper.common.ZKConfig;
-import org.apache.zookeeper.server.quorum.QuorumAuthPacket;
-import org.apache.zookeeper.util.SecurityUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class SaslQuorumAuthServer implements QuorumAuthServer {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(SaslQuorumAuthServer.class);
-
- private final static int MAX_RETRIES = 5;
- private final Login serverLogin;
- private final boolean quorumRequireSasl;
-
- public SaslQuorumAuthServer(boolean quorumRequireSasl, String loginContext, Set<String> authzHosts)
- throws SaslException {
- this.quorumRequireSasl = quorumRequireSasl;
- try {
- AppConfigurationEntry entries[] = Configuration.getConfiguration()
- .getAppConfigurationEntry(loginContext);
- if (entries == null || entries.length == 0) {
- throw new LoginException("SASL-authentication failed"
- + " because the specified JAAS configuration "
- + "section '" + loginContext + "' could not be found.");
- }
- SaslQuorumServerCallbackHandler saslServerCallbackHandler = new SaslQuorumServerCallbackHandler(
- Configuration.getConfiguration(), loginContext, authzHosts);
- serverLogin = new Login(loginContext, saslServerCallbackHandler, new ZKConfig());
- serverLogin.startThreadIfNeeded();
- } catch (Throwable e) {
- throw new SaslException(
- "Failed to initialize authentication mechanism using SASL",
- e);
- }
- }
-
- @Override
- public void authenticate(Socket sock, DataInputStream din)
- throws SaslException {
- DataOutputStream dout = null;
- SaslServer ss = null;
- try {
- if (!QuorumAuth.nextPacketIsAuth(din)) {
- if (quorumRequireSasl) {
- throw new SaslException("Learner not trying to authenticate"
- + " and authentication is required");
- } else {
- // let it through, we don't require auth
- return;
- }
- }
-
- byte[] token = receive(din);
- int tries = 0;
- dout = new DataOutputStream(sock.getOutputStream());
- byte[] challenge = null;
- ss = SecurityUtils.createSaslServer(serverLogin.getSubject(),
- QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME,
- QuorumAuth.QUORUM_SERVER_SASL_DIGEST, serverLogin.callbackHandler,
- LOG);
- while (!ss.isComplete()) {
- challenge = ss.evaluateResponse(token);
- if (!ss.isComplete()) {
- // limited number of retries.
- if (++tries > MAX_RETRIES) {
- send(dout, challenge, QuorumAuth.Status.ERROR);
- LOG.warn("Failed to authenticate using SASL, server addr: {}, retries={} exceeded.",
- sock.getRemoteSocketAddress(), tries);
- break;
- }
- send(dout, challenge, QuorumAuth.Status.IN_PROGRESS);
- token = receive(din);
- }
- }
- // Authentication exchange has completed
- if (ss.isComplete()) {
- send(dout, challenge, QuorumAuth.Status.SUCCESS);
- LOG.info("Successfully completed the authentication using SASL. learner addr: {}",
- sock.getRemoteSocketAddress());
- }
- } catch (Exception e) {
- try {
- if (dout != null) {
- // send error message to the learner
- send(dout, new byte[0], QuorumAuth.Status.ERROR);
- }
- } catch (IOException ioe) {
- LOG.warn("Exception while sending failed status", ioe);
- }
- // If sasl is not required, when a server initializes a
- // connection it will try to log in, but it will also
- // accept connections that do not start with a sasl
- // handshake.
- if (quorumRequireSasl) {
- LOG.error("Failed to authenticate using SASL", e);
- throw new SaslException(
- "Failed to authenticate using SASL: " + e.getMessage());
- } else {
- LOG.warn("Failed to authenticate using SASL", e);
- LOG.warn("Maintaining learner connection despite SASL authentication failure."
- + " server addr: {}, {}: {}",
- new Object[] { sock.getRemoteSocketAddress(),
- QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED,
- quorumRequireSasl });
- return; // let it through, we don't require auth
- }
- } finally {
- if (ss != null) {
- try {
- ss.dispose();
- } catch (SaslException e) {
- LOG.error("SaslServer dispose() failed", e);
- }
- }
- }
- return;
- }
-
- private byte[] receive(DataInputStream din) throws IOException {
- QuorumAuthPacket authPacket = new QuorumAuthPacket();
- BinaryInputArchive bia = BinaryInputArchive.getArchive(din);
- authPacket.deserialize(bia, QuorumAuth.QUORUM_AUTH_MESSAGE_TAG);
- return authPacket.getToken();
- }
-
- private void send(DataOutputStream dout, byte[] challenge,
- QuorumAuth.Status s) throws IOException {
- BufferedOutputStream bufferedOutput = new BufferedOutputStream(dout);
- BinaryOutputArchive boa = BinaryOutputArchive
- .getArchive(bufferedOutput);
- QuorumAuthPacket authPacket;
- if (challenge == null && s != QuorumAuth.Status.SUCCESS) {
- authPacket = QuorumAuth.createPacket(
- QuorumAuth.Status.IN_PROGRESS, null);
- } else {
- authPacket = QuorumAuth.createPacket(s, challenge);
- }
-
- boa.writeRecord(authPacket, QuorumAuth.QUORUM_AUTH_MESSAGE_TAG);
- bufferedOutput.flush();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumServerCallbackHandler.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumServerCallbackHandler.java b/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumServerCallbackHandler.java
deleted file mode 100644
index 3e71bb1..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/auth/SaslQuorumServerCallbackHandler.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.auth;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
-import javax.security.sasl.AuthorizeCallback;
-import javax.security.sasl.RealmCallback;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This is used by the SASL mechanisms to get further information to complete
- * the authentication. For example, a SASL mechanism might use this callback
- * handler to do verification operation. This is used by the QuorumServer to
- * perform the mutual quorum peer authentication.
- */
-public class SaslQuorumServerCallbackHandler implements CallbackHandler {
- private static final String USER_PREFIX = "user_";
- private static final Logger LOG = LoggerFactory.getLogger(SaslQuorumServerCallbackHandler.class);
-
- private String userName;
- private final Map<String,String> credentials = new HashMap<String,String>();
- private final Set<String> authzHosts;
-
- public SaslQuorumServerCallbackHandler(Configuration configuration,
- String serverSection, Set<String> authzHosts) throws IOException {
- AppConfigurationEntry configurationEntries[] = configuration.getAppConfigurationEntry(serverSection);
-
- if (configurationEntries == null) {
- String errorMessage = "Could not find a '" + serverSection + "' entry in this configuration: Server cannot start.";
- LOG.error(errorMessage);
- throw new IOException(errorMessage);
- }
- credentials.clear();
- for(AppConfigurationEntry entry: configurationEntries) {
- Map<String,?> options = entry.getOptions();
- // Populate DIGEST-MD5 user -> password map with JAAS configuration entries from the "QuorumServer" section.
- // Usernames are distinguished from other options by prefixing the username with a "user_" prefix.
- for(Map.Entry<String, ?> pair : options.entrySet()) {
- String key = pair.getKey();
- if (key.startsWith(USER_PREFIX)) {
- String userName = key.substring(USER_PREFIX.length());
- credentials.put(userName,(String)pair.getValue());
- }
- }
- }
-
- // authorized host lists
- this.authzHosts = authzHosts;
- }
-
- public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
- for (Callback callback : callbacks) {
- if (callback instanceof NameCallback) {
- handleNameCallback((NameCallback) callback);
- } else if (callback instanceof PasswordCallback) {
- handlePasswordCallback((PasswordCallback) callback);
- } else if (callback instanceof RealmCallback) {
- handleRealmCallback((RealmCallback) callback);
- } else if (callback instanceof AuthorizeCallback) {
- handleAuthorizeCallback((AuthorizeCallback) callback);
- }
- }
- }
-
- private void handleNameCallback(NameCallback nc) {
- // check to see if this user is in the user password database.
- if (credentials.get(nc.getDefaultName()) == null) {
- LOG.warn("User '{}' not found in list of DIGEST-MD5 authenticateable users.",
- nc.getDefaultName());
- return;
- }
- nc.setName(nc.getDefaultName());
- userName = nc.getDefaultName();
- }
-
- private void handlePasswordCallback(PasswordCallback pc) {
- if (credentials.containsKey(userName) ) {
- pc.setPassword(credentials.get(userName).toCharArray());
- } else {
- LOG.warn("No password found for user: {}", userName);
- }
- }
-
- private void handleRealmCallback(RealmCallback rc) {
- LOG.debug("QuorumLearner supplied realm: {}", rc.getDefaultText());
- rc.setText(rc.getDefaultText());
- }
-
- private void handleAuthorizeCallback(AuthorizeCallback ac) {
- String authenticationID = ac.getAuthenticationID();
- String authorizationID = ac.getAuthorizationID();
-
- boolean authzFlag = false;
- // 1. Matches authenticationID and authorizationID
- authzFlag = authenticationID.equals(authorizationID);
-
- // 2. Verify whether the connecting host is present in authorized hosts.
- // If not exists, then connecting peer is not authorized to join the
- // ensemble and will reject it.
- if (authzFlag) {
- String[] components = authorizationID.split("[/@]");
- if (components.length == 3) {
- authzFlag = authzHosts.contains(components[1]);
- }
- if (!authzFlag) {
- LOG.error("SASL authorization completed, {} is not authorized to connect",
- components[1]);
- }
- }
-
- // Sets authorization flag
- ac.setAuthorized(authzFlag);
- if (ac.isAuthorized()) {
- ac.setAuthorizedID(authorizationID);
- LOG.info("Successfully authenticated learner: authenticationID={}; authorizationID={}.",
- authenticationID, authorizationID);
- }
- LOG.debug("SASL authorization completed, authorized flag set to {}", ac.isAuthorized());
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumHierarchical.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumHierarchical.java b/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumHierarchical.java
deleted file mode 100644
index 404aa8c..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumHierarchical.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.flexible;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.Set;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Map.Entry;
-
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
-import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-
-
-/**
- * This class implements a validator for hierarchical quorums. With this
- * construction, zookeeper servers are split into disjoint groups, and
- * each server has a weight. We obtain a quorum if we get more than half
- * of the total weight of a group for a majority of groups.
- *
- * The configuration of quorums uses two parameters: group and weight.
- * Groups are sets of ZooKeeper servers, and we set a group by passing
- * a colon-separated list of server ids. It is also necessary to assign
- * weights to server. Here is an example of a configuration that creates
- * three groups and assigns a weight of 1 to each server:
- *
- * group.1=1:2:3
- * group.2=4:5:6
- * group.3=7:8:9
- *
- * weight.1=1
- * weight.2=1
- * weight.3=1
- * weight.4=1
- * weight.5=1
- * weight.6=1
- * weight.7=1
- * weight.8=1
- * weight.9=1
- *
- * Note that it is still necessary to define peers using the server keyword.
- */
-
-public class QuorumHierarchical implements QuorumVerifier {
- private static final Logger LOG = LoggerFactory.getLogger(QuorumHierarchical.class);
-
- private HashMap<Long, Long> serverWeight = new HashMap<Long, Long>();
- private HashMap<Long, Long> serverGroup = new HashMap<Long, Long>();
- private HashMap<Long, Long> groupWeight = new HashMap<Long, Long>();
-
- private int numGroups = 0;
-
- private Map<Long, QuorumServer> allMembers = new HashMap<Long, QuorumServer>();
- private Map<Long, QuorumServer> participatingMembers = new HashMap<Long, QuorumServer>();
- private Map<Long, QuorumServer> observingMembers = new HashMap<Long, QuorumServer>();
-
- private long version = 0;
-
- public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
- public boolean equals(Object o){
- if (!(o instanceof QuorumHierarchical)) {
- return false;
- }
- QuorumHierarchical qm = (QuorumHierarchical)o;
- if (qm.getVersion() == version) return true;
- if ((allMembers.size()!=qm.getAllMembers().size()) ||
- (serverWeight.size() != qm.serverWeight.size()) ||
- (groupWeight.size() != qm.groupWeight.size()) ||
- (serverGroup.size() != qm.serverGroup.size())) {
- return false;
- }
- for (QuorumServer qs: allMembers.values()){
- QuorumServer qso = qm.getAllMembers().get(qs.id);
- if (qso == null || !qs.equals(qso)) return false;
- }
- for (Entry<Long, Long> entry : serverWeight.entrySet()) {
- if (!entry.getValue().equals(qm.serverWeight.get(entry.getKey())))
- return false;
- }
- for (Entry<Long, Long> entry : groupWeight.entrySet()) {
- if (!entry.getValue().equals(qm.groupWeight.get(entry.getKey())))
- return false;
- }
- for (Entry<Long, Long> entry : serverGroup.entrySet()) {
- if (!entry.getValue().equals(qm.serverGroup.get(entry.getKey())))
- return false;
- }
- return true;
- }
- /**
- * This contructor requires the quorum configuration
- * to be declared in a separate file, and it takes the
- * file as an input parameter.
- */
- public QuorumHierarchical(String filename)
- throws ConfigException {
- readConfigFile(filename);
- }
-
- /**
- * This constructor takes a set of properties. We use
- * it in the unit test for this feature.
- */
-
- public QuorumHierarchical(Properties qp) throws ConfigException {
- parse(qp);
- LOG.info(serverWeight.size() + ", " + serverGroup.size() + ", " + groupWeight.size());
- }
-
- /**
- * Returns the weight of a server.
- *
- * @param id
- */
- public long getWeight(long id){
- return serverWeight.get(id);
- }
-
- /**
- * Reads a configration file. Called from the constructor
- * that takes a file as an input.
- */
- private void readConfigFile(String filename)
- throws ConfigException{
- File configFile = new File(filename);
-
- LOG.info("Reading configuration from: " + configFile);
-
- try {
- if (!configFile.exists()) {
- throw new IllegalArgumentException(configFile.toString()
- + " file is missing");
- }
-
- Properties cfg = new Properties();
- FileInputStream in = new FileInputStream(configFile);
- try {
- cfg.load(in);
- } finally {
- in.close();
- }
-
- parse(cfg);
- } catch (IOException e) {
- throw new ConfigException("Error processing " + filename, e);
- } catch (IllegalArgumentException e) {
- throw new ConfigException("Error processing " + filename, e);
- }
-
- }
-
-
- /**
- * Parse properties if configuration given in a separate file.
- * Assumes that allMembers has been already assigned
- * @throws ConfigException
- */
- private void parse(Properties quorumProp) throws ConfigException{
- for (Entry<Object, Object> entry : quorumProp.entrySet()) {
- String key = entry.getKey().toString();
- String value = entry.getValue().toString();
-
- if (key.startsWith("server.")) {
- int dot = key.indexOf('.');
- long sid = Long.parseLong(key.substring(dot + 1));
- QuorumServer qs = new QuorumServer(sid, value);
- allMembers.put(Long.valueOf(sid), qs);
- if (qs.type == LearnerType.PARTICIPANT)
- participatingMembers.put(Long.valueOf(sid), qs);
- else {
- observingMembers.put(Long.valueOf(sid), qs);
- }
- } else if (key.startsWith("group")) {
- int dot = key.indexOf('.');
- long gid = Long.parseLong(key.substring(dot + 1));
-
- numGroups++;
-
- String parts[] = value.split(":");
- for(String s : parts){
- long sid = Long.parseLong(s);
- if(serverGroup.containsKey(sid))
- throw new ConfigException("Server " + sid + "is in multiple groups");
- else
- serverGroup.put(sid, gid);
- }
-
-
- } else if(key.startsWith("weight")) {
- int dot = key.indexOf('.');
- long sid = Long.parseLong(key.substring(dot + 1));
- serverWeight.put(sid, Long.parseLong(value));
- } else if (key.equals("version")){
- version = Long.parseLong(value, 16);
- }
- }
-
- for (QuorumServer qs: allMembers.values()){
- Long id = qs.id;
- if (qs.type == LearnerType.PARTICIPANT){
- if (!serverGroup.containsKey(id))
- throw new ConfigException("Server " + id + "is not in a group");
- if (!serverWeight.containsKey(id))
- serverWeight.put(id, (long) 1);
- }
- }
-
-
- computeGroupWeight();
- }
-
- public Map<Long, QuorumServer> getAllMembers() {
- return allMembers;
- }
- public String toString(){
- StringWriter sw = new StringWriter();
-
- for (QuorumServer member: getAllMembers().values()){
- String key = "server." + member.id;
- String value = member.toString();
- sw.append(key);
- sw.append('=');
- sw.append(value);
- sw.append('\n');
- }
-
- Map<Long, String> groups = new HashMap<Long, String>();
- for (Entry<Long, Long> pair: serverGroup.entrySet()) {
- Long sid = pair.getKey();
- Long gid = pair.getValue();
- String str = groups.get(gid);
- if (str == null) str = sid.toString();
- else str = str.concat(":").concat(sid.toString());
- groups.put(gid, str);
- }
-
- for (Entry<Long, String> pair: groups.entrySet()) {
- Long gid = pair.getKey();
- String key = "group." + gid.toString();
- String value = pair.getValue();
- sw.append(key);
- sw.append('=');
- sw.append(value);
- sw.append('\n');
- }
-
-
- for (Entry<Long, Long> pair: serverWeight.entrySet()) {
- Long sid = pair.getKey();
- String key = "weight." + sid.toString();
- String value = pair.getValue().toString();
- sw.append(key);
- sw.append('=');
- sw.append(value);
- sw.append('\n');
- }
-
- sw.append("version=" + Long.toHexString(version));
-
- return sw.toString();
- }
-
- /**
- * This method pre-computes the weights of groups to speed up processing
- * when validating a given set. We compute the weights of groups in
- * different places, so we have a separate method.
- */
- private void computeGroupWeight(){
- for (Entry<Long, Long> entry : serverGroup.entrySet()) {
- Long sid = entry.getKey();
- Long gid = entry.getValue();
- if(!groupWeight.containsKey(gid))
- groupWeight.put(gid, serverWeight.get(sid));
- else {
- long totalWeight = serverWeight.get(sid) + groupWeight.get(gid);
- groupWeight.put(gid, totalWeight);
- }
- }
-
- /*
- * Do not consider groups with weight zero
- */
- for(long weight: groupWeight.values()){
- LOG.debug("Group weight: " + weight);
- if(weight == ((long) 0)){
- numGroups--;
- LOG.debug("One zero-weight group: " + 1 + ", " + numGroups);
- }
- }
- }
-
- /**
- * Verifies if a given set is a quorum.
- */
- public boolean containsQuorum(Set<Long> set){
- HashMap<Long, Long> expansion = new HashMap<Long, Long>();
-
- /*
- * Adds up weights per group
- */
- if(set.size() == 0) return false;
- else LOG.debug("Set size: " + set.size());
-
- for(long sid : set){
- Long gid = serverGroup.get(sid);
- if (gid == null) continue;
- if(!expansion.containsKey(gid))
- expansion.put(gid, serverWeight.get(sid));
- else {
- long totalWeight = serverWeight.get(sid) + expansion.get(gid);
- expansion.put(gid, totalWeight);
- }
- }
-
- /*
- * Check if all groups have majority
- */
- int majGroupCounter = 0;
- for (Entry<Long, Long> entry : expansion.entrySet()) {
- Long gid = entry.getKey();
- LOG.debug("Group info: {}, {}, {}", entry.getValue(), gid, groupWeight.get(gid));
- if (entry.getValue() > (groupWeight.get(gid) / 2))
- majGroupCounter++;
- }
-
- LOG.debug("Majority group counter: {}, {}", majGroupCounter, numGroups);
- if ((majGroupCounter > (numGroups / 2))){
- LOG.debug("Positive set size: {}", set.size());
- return true;
- } else {
- LOG.debug("Negative set size: {}", set.size());
- return false;
- }
- }
- public Map<Long, QuorumServer> getVotingMembers() {
- return participatingMembers;
- }
-
- public Map<Long, QuorumServer> getObservingMembers() {
- return observingMembers;
- }
-
- public long getVersion() {
- return version;
- }
-
- public void setVersion(long ver) {
- version = ver;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumMaj.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumMaj.java b/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumMaj.java
deleted file mode 100644
index 0003c2a..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumMaj.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.flexible;
-
-import java.util.HashMap;
-import java.util.Set;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Map.Entry;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
-import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-
-/**
- * This class implements a validator for majority quorums. The implementation is
- * straightforward.
- *
- */
-public class QuorumMaj implements QuorumVerifier {
- private Map<Long, QuorumServer> allMembers = new HashMap<Long, QuorumServer>();
- private Map<Long, QuorumServer> votingMembers = new HashMap<Long, QuorumServer>();
- private Map<Long, QuorumServer> observingMembers = new HashMap<Long, QuorumServer>();
- private long version = 0;
- private int half;
-
- public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof QuorumMaj)) {
- return false;
- }
- QuorumMaj qm = (QuorumMaj) o;
- if (qm.getVersion() == version)
- return true;
- if (allMembers.size() != qm.getAllMembers().size())
- return false;
- for (QuorumServer qs : allMembers.values()) {
- QuorumServer qso = qm.getAllMembers().get(qs.id);
- if (qso == null || !qs.equals(qso))
- return false;
- }
- return true;
- }
-
- /**
- * Defines a majority to avoid computing it every time.
- *
- */
- public QuorumMaj(Map<Long, QuorumServer> allMembers) {
- this.allMembers = allMembers;
- for (QuorumServer qs : allMembers.values()) {
- if (qs.type == LearnerType.PARTICIPANT) {
- votingMembers.put(Long.valueOf(qs.id), qs);
- } else {
- observingMembers.put(Long.valueOf(qs.id), qs);
- }
- }
- half = votingMembers.size() / 2;
- }
-
- public QuorumMaj(Properties props) throws ConfigException {
- for (Entry<Object, Object> entry : props.entrySet()) {
- String key = entry.getKey().toString();
- String value = entry.getValue().toString();
-
- if (key.startsWith("server.")) {
- int dot = key.indexOf('.');
- long sid = Long.parseLong(key.substring(dot + 1));
- QuorumServer qs = new QuorumServer(sid, value);
- allMembers.put(Long.valueOf(sid), qs);
- if (qs.type == LearnerType.PARTICIPANT)
- votingMembers.put(Long.valueOf(sid), qs);
- else {
- observingMembers.put(Long.valueOf(sid), qs);
- }
- } else if (key.equals("version")) {
- version = Long.parseLong(value, 16);
- }
- }
- half = votingMembers.size() / 2;
- }
-
- /**
- * Returns weight of 1 by default.
- *
- * @param id
- */
- public long getWeight(long id) {
- return (long) 1;
- }
-
- public String toString() {
- StringBuilder sw = new StringBuilder();
-
- for (QuorumServer member : getAllMembers().values()) {
- String key = "server." + member.id;
- String value = member.toString();
- sw.append(key);
- sw.append('=');
- sw.append(value);
- sw.append('\n');
- }
- String hexVersion = Long.toHexString(version);
- sw.append("version=");
- sw.append(hexVersion);
- return sw.toString();
- }
-
- /**
- * Verifies if a set is a majority. Assumes that ackSet contains acks only
- * from votingMembers
- */
- public boolean containsQuorum(Set<Long> ackSet) {
- return (ackSet.size() > half);
- }
-
- public Map<Long, QuorumServer> getAllMembers() {
- return allMembers;
- }
-
- public Map<Long, QuorumServer> getVotingMembers() {
- return votingMembers;
- }
-
- public Map<Long, QuorumServer> getObservingMembers() {
- return observingMembers;
- }
-
- public long getVersion() {
- return version;
- }
-
- public void setVersion(long ver) {
- version = ver;
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumVerifier.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumVerifier.java b/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumVerifier.java
deleted file mode 100644
index c70eac6..0000000
--- a/src/java/main/org/apache/zookeeper/server/quorum/flexible/QuorumVerifier.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 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.zookeeper.server.quorum.flexible;
-
-import java.util.Set;
-import java.util.Map;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-
-/**
- * All quorum validators have to implement a method called
- * containsQuorum, which verifies if a HashSet of server
- * identifiers constitutes a quorum.
- *
- */
-
-public interface QuorumVerifier {
- long getWeight(long id);
- boolean containsQuorum(Set<Long> set);
- long getVersion();
- void setVersion(long ver);
- Map<Long, QuorumServer> getAllMembers();
- Map<Long, QuorumServer> getVotingMembers();
- Map<Long, QuorumServer> getObservingMembers();
- boolean equals(Object o);
- String toString();
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/util/BitHashSet.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/util/BitHashSet.java b/src/java/main/org/apache/zookeeper/server/util/BitHashSet.java
deleted file mode 100644
index b60f1d4..0000000
--- a/src/java/main/org/apache/zookeeper/server/util/BitHashSet.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * 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.zookeeper.server.util;
-
-import java.util.BitSet;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.lang.Iterable;
-
-/**
- * Using BitSet to store all the elements, and use HashSet to cache limited
- * number of elements to find a balance between memory and time complexity.
- *
- * Without HashSet, we need to use O(N) time to get the elements, N is
- * the bit numbers in elementBits. But we need to keep the size small to make
- * sure it doesn't cost too much in memory, there is a trade off between
- * memory and time complexity.
- *
- * Previously, was deciding to dynamically switch between SparseBitSet and
- * HashSet based on the memory consumption, but it will take time to copy
- * data over and may have some herd effect of keep copying data from one
- * data structure to anther. The current solution can do a very good job
- * given most of the paths have limited number of elements.
- */
-public class BitHashSet implements Iterable<Integer> {
-
- /**
- * Change to SparseBitSet if we we want to optimize more, the number of
- * elements on a single server is usually limited, so BitSet should be
- * fine.
- */
- private final BitSet elementBits = new BitSet();
-
- /**
- * HashSet is used to optimize the iterating, if there is a single
- * element in this BitHashSet, but the bit is very large, without
- * HashSet we need to go through all the words before return that
- * element, which is not efficient.
- */
- private final Set<Integer> cache = new HashSet<Integer>();
-
- private final int cacheSize;
-
- // To record how many elements in this set.
- private int elementCount = 0;
-
- public BitHashSet() {
- this(Integer.getInteger("zookeeper.bitHashCacheSize", 10));
- }
-
- public BitHashSet(int cacheSize) {
- this.cacheSize = cacheSize;
- }
-
- public synchronized boolean add(Integer elementBit) {
- if (elementBit == null || elementBits.get(elementBit)) {
- return false;
- }
- if (cache.size() < cacheSize) {
- cache.add(elementBit);
- }
- elementBits.set(elementBit);
- elementCount++;
- return true;
- }
-
- /**
- * Remove the watches, and return the number of watches being removed.
- */
- public synchronized int remove(Set<Integer> bitSet, BitSet bits) {
- cache.removeAll(bitSet);
- elementBits.andNot(bits);
- int elementCountBefore = elementCount;
- elementCount = elementBits.cardinality();
- return elementCountBefore - elementCount;
- }
-
- public synchronized boolean remove(Integer elementBit) {
- if (elementBit == null || !elementBits.get(elementBit)) {
- return false;
- }
-
- cache.remove(elementBit);
- elementBits.clear(elementBit);
- elementCount--;
- return true;
- }
-
- public synchronized boolean contains(Integer elementBit) {
- if (elementBit == null) {
- return false;
- }
- return elementBits.get(elementBit);
- }
-
- public synchronized int size() {
- return elementCount;
- }
-
- /**
- * This function is not thread-safe, need to synchronized when
- * iterate through this set.
- */
- @Override
- public Iterator<Integer> iterator() {
- if (cache.size() == elementCount) {
- return cache.iterator();
- }
-
- return new Iterator<Integer>() {
- int returnedCount = 0;
- int bitIndex = 0;
-
- @Override
- public boolean hasNext() {
- return returnedCount < elementCount;
- }
-
- @Override
- public Integer next() {
- int bit = elementBits.nextSetBit(bitIndex);
- bitIndex = bit + 1;
- returnedCount++;
- return bit;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
- // visible for test
- public synchronized int cachedSize() {
- return cache.size();
- }
-
- public synchronized boolean isEmpty() {
- return elementCount == 0;
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/main/org/apache/zookeeper/server/util/BitMap.java
----------------------------------------------------------------------
diff --git a/src/java/main/org/apache/zookeeper/server/util/BitMap.java b/src/java/main/org/apache/zookeeper/server/util/BitMap.java
deleted file mode 100644
index 1a0fb3b..0000000
--- a/src/java/main/org/apache/zookeeper/server/util/BitMap.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * 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.zookeeper.server.util;
-
-import java.util.Map;
-import java.util.HashMap;
-import java.util.BitSet;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * This is a helper class to maintain the bit to specific value and the
- * reversed value to bit mapping.
- */
-public class BitMap<T> {
-
- private final Map<T, Integer> value2Bit = new HashMap<T, Integer>();
- private final Map<Integer, T> bit2Value = new HashMap<Integer, T>();
-
- private final BitSet freedBitSet = new BitSet();
- private Integer nextBit = Integer.valueOf(0);
-
- private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
-
- public Integer add(T value) {
- /*
- * Optimized for code which will add the same value again and again,
- * more specifically this is used to add new bit for watcher, and
- * the same watcher may watching thousands or even millions of nodes,
- * which will call add the same value of this function, check exist
- * using read lock will optimize the performance here.
- */
- Integer bit = getBit(value);
- if (bit != null) {
- return bit;
- }
-
- rwLock.writeLock().lock();
- try {
- bit = value2Bit.get(value);
- if (bit != null) {
- return bit;
- }
- bit = freedBitSet.nextSetBit(0);
- if (bit > -1) {
- freedBitSet.clear(bit);
- } else {
- bit = nextBit++;
- }
-
- value2Bit.put(value, bit);
- bit2Value.put(bit, value);
- return bit;
- } finally {
- rwLock.writeLock().unlock();
- }
- }
-
- public T get(int bit) {
- rwLock.readLock().lock();
- try {
- return bit2Value.get(bit);
- } finally {
- rwLock.readLock().unlock();
- }
- }
-
- public Integer getBit(T value) {
- rwLock.readLock().lock();
- try {
- return value2Bit.get(value);
- } finally {
- rwLock.readLock().unlock();
- }
- }
-
- public int remove(T value) {
- /*
- * remove only called once when the session is closed, so use write
- * lock directly without checking read lock.
- */
- rwLock.writeLock().lock();
- try {
- Integer bit = value2Bit.get(value);
- if (bit == null) {
- return -1;
- }
- value2Bit.remove(value);
- bit2Value.remove(bit);
- freedBitSet.set(bit);
- return bit;
- } finally {
- rwLock.writeLock().unlock();
- }
- }
-
- public T remove(int bit) {
- rwLock.writeLock().lock();
- try {
- T value = bit2Value.get(bit);
- if (value == null) {
- return null;
- }
- value2Bit.remove(value);
- bit2Value.remove(bit);
- freedBitSet.set(bit);
- return value;
- } finally {
- rwLock.writeLock().unlock();
- }
- }
-
- public int size() {
- rwLock.readLock().lock();
- try {
- return value2Bit.size();
- } finally {
- rwLock.readLock().unlock();
- }
- }
-}