001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.zookeeper;
019
020import static org.hamcrest.CoreMatchers.instanceOf;
021import static org.hamcrest.MatcherAssert.assertThat;
022import static org.junit.Assert.assertArrayEquals;
023import static org.junit.Assert.assertEquals;
024import static org.junit.Assert.assertNotEquals;
025import static org.junit.Assert.assertNotNull;
026import static org.junit.Assert.assertNotSame;
027import static org.junit.Assert.assertNull;
028import static org.junit.Assert.assertSame;
029import static org.junit.Assert.fail;
030import static org.mockito.ArgumentMatchers.any;
031import static org.mockito.ArgumentMatchers.anyBoolean;
032import static org.mockito.ArgumentMatchers.anyString;
033import static org.mockito.Mockito.doAnswer;
034import static org.mockito.Mockito.mock;
035import static org.mockito.Mockito.never;
036import static org.mockito.Mockito.times;
037import static org.mockito.Mockito.verify;
038import static org.mockito.Mockito.when;
039
040import java.io.IOException;
041import java.util.Collections;
042import java.util.List;
043import java.util.concurrent.CompletableFuture;
044import java.util.concurrent.Exchanger;
045import java.util.concurrent.ExecutionException;
046import java.util.concurrent.TimeUnit;
047import org.apache.hadoop.conf.Configuration;
048import org.apache.hadoop.hbase.HBaseClassTestRule;
049import org.apache.hadoop.hbase.HBaseZKTestingUtil;
050import org.apache.hadoop.hbase.HConstants;
051import org.apache.hadoop.hbase.Waiter.ExplainingPredicate;
052import org.apache.hadoop.hbase.testclassification.MediumTests;
053import org.apache.hadoop.hbase.testclassification.ZKTests;
054import org.apache.hadoop.hbase.util.Bytes;
055import org.apache.hadoop.hbase.util.Threads;
056import org.apache.zookeeper.AsyncCallback;
057import org.apache.zookeeper.CreateMode;
058import org.apache.zookeeper.KeeperException;
059import org.apache.zookeeper.KeeperException.Code;
060import org.apache.zookeeper.ZooDefs;
061import org.apache.zookeeper.ZooKeeper;
062import org.junit.AfterClass;
063import org.junit.BeforeClass;
064import org.junit.ClassRule;
065import org.junit.Test;
066import org.junit.experimental.categories.Category;
067
068import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
069import org.apache.hbase.thirdparty.io.netty.util.HashedWheelTimer;
070
071@Category({ ZKTests.class, MediumTests.class })
072public class TestReadOnlyZKClient {
073
074  @ClassRule
075  public static final HBaseClassTestRule CLASS_RULE =
076    HBaseClassTestRule.forClass(TestReadOnlyZKClient.class);
077
078  private static HBaseZKTestingUtil UTIL = new HBaseZKTestingUtil();
079
080  private static String PATH = "/test";
081
082  private static byte[] DATA;
083
084  private static int CHILDREN = 5;
085
086  private static ReadOnlyZKClient RO_ZK;
087  private static final HashedWheelTimer RETRY_TIMER = new HashedWheelTimer(
088    new ThreadFactoryBuilder().setNameFormat("Async-Client-Retry-Timer-pool-%d").setDaemon(true)
089      .setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build(),
090    10, TimeUnit.MILLISECONDS);
091
092  @BeforeClass
093  public static void setUp() throws Exception {
094    final int port = UTIL.startMiniZKCluster().getClientPort();
095    String hostPort = UTIL.getZkCluster().getAddress().toString();
096
097    ZooKeeper zk = ZooKeeperHelper.getConnectedZooKeeper(hostPort, 10000);
098    DATA = new byte[10];
099    Bytes.random(DATA);
100    zk.create(PATH, DATA, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
101    for (int i = 0; i < CHILDREN; i++) {
102      zk.create(PATH + "/c" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
103    }
104    zk.close();
105    Configuration conf = UTIL.getConfiguration();
106    conf.set(HConstants.ZOOKEEPER_QUORUM, hostPort);
107    conf.setInt(ReadOnlyZKClient.RECOVERY_RETRY, 3);
108    conf.setInt(ReadOnlyZKClient.RECOVERY_RETRY_INTERVAL_MILLIS, 100);
109    conf.setInt(ReadOnlyZKClient.KEEPALIVE_MILLIS, 3000);
110    RO_ZK = new ReadOnlyZKClient(conf, RETRY_TIMER);
111    // only connect when necessary
112    assertNull(RO_ZK.zookeeper);
113  }
114
115  @AfterClass
116  public static void tearDown() throws IOException {
117    RETRY_TIMER.stop();
118    RO_ZK.close();
119    UTIL.shutdownMiniZKCluster();
120    UTIL.cleanupTestDir();
121  }
122
123  private void waitForIdleConnectionClosed() throws Exception {
124    // The zookeeper client should be closed finally after the keep alive time elapsed
125    UTIL.waitFor(10000, new ExplainingPredicate<Exception>() {
126
127      @Override
128      public boolean evaluate() {
129        return RO_ZK.zookeeper == null;
130      }
131
132      @Override
133      public String explainFailure() {
134        return "Connection to zookeeper is still alive";
135      }
136    });
137  }
138
139  @Test
140  public void testRead() throws Exception {
141    assertArrayEquals(DATA, RO_ZK.get(PATH).get());
142    assertEquals(CHILDREN, RO_ZK.exists(PATH).get().getNumChildren());
143    List<String> children = RO_ZK.list(PATH).get();
144    assertEquals(CHILDREN, children.size());
145    Collections.sort(children);
146    for (int i = 0; i < CHILDREN; i++) {
147      assertEquals("c" + i, children.get(i));
148    }
149    assertNotNull(RO_ZK.zookeeper);
150    waitForIdleConnectionClosed();
151  }
152
153  @Test
154  public void testNoNode() throws InterruptedException, ExecutionException {
155    String pathNotExists = PATH + "_whatever";
156    try {
157      RO_ZK.get(pathNotExists).get();
158      fail("should fail because of " + pathNotExists + " does not exist");
159    } catch (ExecutionException e) {
160      assertThat(e.getCause(), instanceOf(KeeperException.class));
161      KeeperException ke = (KeeperException) e.getCause();
162      assertEquals(Code.NONODE, ke.code());
163      assertEquals(pathNotExists, ke.getPath());
164    }
165    try {
166      RO_ZK.list(pathNotExists).get();
167      fail("should fail because of " + pathNotExists + " does not exist");
168    } catch (ExecutionException e) {
169      assertThat(e.getCause(), instanceOf(KeeperException.class));
170      KeeperException ke = (KeeperException) e.getCause();
171      assertEquals(Code.NONODE, ke.code());
172      assertEquals(pathNotExists, ke.getPath());
173    }
174    // exists will not throw exception.
175    assertNull(RO_ZK.exists(pathNotExists).get());
176  }
177
178  @Test
179  public void testSessionExpire() throws Exception {
180    assertArrayEquals(DATA, RO_ZK.get(PATH).get());
181    ZooKeeper zk = RO_ZK.zookeeper;
182    long sessionId = zk.getSessionId();
183    UTIL.getZkCluster().getZooKeeperServers().get(0).closeSession(sessionId);
184    // should not reach keep alive so still the same instance
185    assertSame(zk, RO_ZK.zookeeper);
186    byte[] got = RO_ZK.get(PATH).get();
187    assertArrayEquals(DATA, got);
188    assertNotNull(RO_ZK.zookeeper);
189    assertNotSame(zk, RO_ZK.zookeeper);
190    assertNotEquals(sessionId, RO_ZK.zookeeper.getSessionId());
191  }
192
193  @Test
194  public void testNotCloseZkWhenPending() throws Exception {
195    ZooKeeper mockedZK = mock(ZooKeeper.class);
196    Exchanger<AsyncCallback.DataCallback> exchanger = new Exchanger<>();
197    doAnswer(i -> {
198      exchanger.exchange(i.getArgument(2));
199      return null;
200    }).when(mockedZK).getData(anyString(), anyBoolean(), any(AsyncCallback.DataCallback.class),
201      any());
202    doAnswer(i -> null).when(mockedZK).close();
203    when(mockedZK.getState()).thenReturn(ZooKeeper.States.CONNECTED);
204    RO_ZK.zookeeper = mockedZK;
205    CompletableFuture<byte[]> future = RO_ZK.get(PATH);
206    AsyncCallback.DataCallback callback = exchanger.exchange(null);
207    // 2 * keep alive time to ensure that we will not close the zk when there are pending requests
208    Thread.sleep(6000);
209    assertNotNull(RO_ZK.zookeeper);
210    verify(mockedZK, never()).close();
211    callback.processResult(Code.OK.intValue(), PATH, null, DATA, null);
212    assertArrayEquals(DATA, future.get());
213    // now we will close the idle connection.
214    waitForIdleConnectionClosed();
215    verify(mockedZK, times(1)).close();
216  }
217
218  @Test
219  public void testReadWithTimeout() throws Exception {
220    assertArrayEquals(DATA, RO_ZK.get(PATH, 10000).get());
221    assertEquals(CHILDREN, RO_ZK.exists(PATH, 10000).get().getNumChildren());
222    List<String> children = RO_ZK.list(PATH, 10000).get();
223    assertEquals(CHILDREN, children.size());
224    Collections.sort(children);
225    for (int i = 0; i < CHILDREN; i++) {
226      assertEquals("c" + i, children.get(i));
227    }
228    assertNotNull(RO_ZK.zookeeper);
229    waitForIdleConnectionClosed();
230  }
231}