001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.zookeeper;
020
021import java.io.BufferedReader;
022import java.io.File;
023import java.io.IOException;
024import java.io.InputStreamReader;
025import java.io.InterruptedIOException;
026import java.io.OutputStream;
027import java.io.Reader;
028import java.net.BindException;
029import java.net.InetSocketAddress;
030import java.net.Socket;
031import java.util.ArrayList;
032import java.util.List;
033import java.util.Random;
034
035import org.apache.hadoop.conf.Configuration;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.yetus.audience.InterfaceAudience;
038import org.apache.zookeeper.server.NIOServerCnxnFactory;
039import org.apache.zookeeper.server.ZooKeeperServer;
040import org.apache.zookeeper.server.persistence.FileTxnLog;
041import org.slf4j.Logger;
042import org.slf4j.LoggerFactory;
043
044import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
045
046/**
047 * TODO: Most of the code in this class is ripped from ZooKeeper tests. Instead
048 * of redoing it, we should contribute updates to their code which let us more
049 * easily access testing helper objects.
050 */
051@InterfaceAudience.Public
052public class MiniZooKeeperCluster {
053  private static final Logger LOG = LoggerFactory.getLogger(MiniZooKeeperCluster.class);
054
055  private static final int TICK_TIME = 2000;
056  private static final int DEFAULT_CONNECTION_TIMEOUT = 30000;
057  private int connectionTimeout;
058
059  private boolean started;
060
061  /** The default port. If zero, we use a random port. */
062  private int defaultClientPort = 0;
063
064  private List<NIOServerCnxnFactory> standaloneServerFactoryList;
065  private List<ZooKeeperServer> zooKeeperServers;
066  private List<Integer> clientPortList;
067
068  private int activeZKServerIndex;
069  private int tickTime = 0;
070
071  private Configuration configuration;
072
073  public MiniZooKeeperCluster() {
074    this(new Configuration());
075  }
076
077  public MiniZooKeeperCluster(Configuration configuration) {
078    this.started = false;
079    this.configuration = configuration;
080    activeZKServerIndex = -1;
081    zooKeeperServers = new ArrayList<>();
082    clientPortList = new ArrayList<>();
083    standaloneServerFactoryList = new ArrayList<>();
084    connectionTimeout = configuration.getInt(HConstants.ZK_SESSION_TIMEOUT + ".localHBaseCluster",
085      DEFAULT_CONNECTION_TIMEOUT);
086  }
087
088  /**
089   * Add a client port to the list.
090   *
091   * @param clientPort the specified port
092   */
093  public void addClientPort(int clientPort) {
094    clientPortList.add(clientPort);
095  }
096
097  /**
098   * Get the list of client ports.
099   * @return clientPortList the client port list
100   */
101  @VisibleForTesting
102  public List<Integer> getClientPortList() {
103    return clientPortList;
104  }
105
106  /**
107   * Check whether the client port in a specific position of the client port list is valid.
108   *
109   * @param index the specified position
110   */
111  private boolean hasValidClientPortInList(int index) {
112    return (clientPortList.size() > index && clientPortList.get(index) > 0);
113  }
114
115  public void setDefaultClientPort(int clientPort) {
116    if (clientPort <= 0) {
117      throw new IllegalArgumentException("Invalid default ZK client port: "
118          + clientPort);
119    }
120    this.defaultClientPort = clientPort;
121  }
122
123  /**
124   * Selects a ZK client port.
125   *
126   * @param seedPort the seed port to start with; -1 means first time.
127   * @Returns a valid and unused client port
128   */
129  private int selectClientPort(int seedPort) {
130    int i;
131    int returnClientPort = seedPort + 1;
132    if (returnClientPort == 0) {
133      // If the new port is invalid, find one - starting with the default client port.
134      // If the default client port is not specified, starting with a random port.
135      // The random port is selected from the range between 49152 to 65535. These ports cannot be
136      // registered with IANA and are intended for dynamic allocation (see http://bit.ly/dynports).
137      if (defaultClientPort > 0) {
138        returnClientPort = defaultClientPort;
139      } else {
140        returnClientPort = 0xc000 + new Random().nextInt(0x3f00);
141      }
142    }
143    // Make sure that the port is unused.
144    while (true) {
145      for (i = 0; i < clientPortList.size(); i++) {
146        if (returnClientPort == clientPortList.get(i)) {
147          // Already used. Update the port and retry.
148          returnClientPort++;
149          break;
150        }
151      }
152      if (i == clientPortList.size()) {
153        break; // found a unused port, exit
154      }
155    }
156    return returnClientPort;
157  }
158
159  public void setTickTime(int tickTime) {
160    this.tickTime = tickTime;
161  }
162
163  public int getBackupZooKeeperServerNum() {
164    return zooKeeperServers.size()-1;
165  }
166
167  public int getZooKeeperServerNum() {
168    return zooKeeperServers.size();
169  }
170
171  // / XXX: From o.a.zk.t.ClientBase
172  private static void setupTestEnv() {
173    // during the tests we run with 100K prealloc in the logs.
174    // on windows systems prealloc of 64M was seen to take ~15seconds
175    // resulting in test failure (client timeout on first session).
176    // set env and directly in order to handle static init/gc issues
177    System.setProperty("zookeeper.preAllocSize", "100");
178    FileTxnLog.setPreallocSize(100 * 1024);
179  }
180
181  public int startup(File baseDir) throws IOException, InterruptedException {
182    int numZooKeeperServers = clientPortList.size();
183    if (numZooKeeperServers == 0) {
184      numZooKeeperServers = 1; // need at least 1 ZK server for testing
185    }
186    return startup(baseDir, numZooKeeperServers);
187  }
188
189  /**
190   * @param baseDir the base directory to use
191   * @param numZooKeeperServers the number of ZooKeeper servers
192   * @return ClientPort server bound to, -1 if there was a binding problem and we couldn't pick
193   *         another port.
194   * @throws IOException if an operation fails during the startup
195   * @throws InterruptedException if the startup fails
196   */
197  public int startup(File baseDir, int numZooKeeperServers) throws IOException,
198          InterruptedException {
199    if (numZooKeeperServers <= 0) {
200      return -1;
201    }
202
203    setupTestEnv();
204    shutdown();
205
206    int tentativePort = -1; // the seed port
207    int currentClientPort;
208
209    // running all the ZK servers
210    for (int i = 0; i < numZooKeeperServers; i++) {
211      File dir = new File(baseDir, "zookeeper_"+i).getAbsoluteFile();
212      createDir(dir);
213      int tickTimeToUse;
214      if (this.tickTime > 0) {
215        tickTimeToUse = this.tickTime;
216      } else {
217        tickTimeToUse = TICK_TIME;
218      }
219
220      // Set up client port - if we have already had a list of valid ports, use it.
221      if (hasValidClientPortInList(i)) {
222        currentClientPort = clientPortList.get(i);
223      } else {
224        tentativePort = selectClientPort(tentativePort); // update the seed
225        currentClientPort = tentativePort;
226      }
227
228      ZooKeeperServer server = new ZooKeeperServer(dir, dir, tickTimeToUse);
229      // Setting {min,max}SessionTimeout defaults to be the same as in Zookeeper
230      server.setMinSessionTimeout(configuration.getInt(
231              "hbase.zookeeper.property.minSessionTimeout", -1));
232      server.setMaxSessionTimeout(configuration.getInt(
233              "hbase.zookeeper.property.maxSessionTimeout", -1));
234      NIOServerCnxnFactory standaloneServerFactory;
235      while (true) {
236        try {
237          standaloneServerFactory = new NIOServerCnxnFactory();
238          standaloneServerFactory.configure(
239            new InetSocketAddress(currentClientPort),
240            configuration.getInt(HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS,
241                    HConstants.DEFAULT_ZOOKEPER_MAX_CLIENT_CNXNS));
242        } catch (BindException e) {
243          LOG.debug("Failed binding ZK Server to client port: " +
244              currentClientPort, e);
245          // We're told to use some port but it's occupied, fail
246          if (hasValidClientPortInList(i)) {
247            return -1;
248          }
249          // This port is already in use, try to use another.
250          tentativePort = selectClientPort(tentativePort);
251          currentClientPort = tentativePort;
252          continue;
253        }
254        break;
255      }
256
257      // Start up this ZK server
258      standaloneServerFactory.startup(server);
259      // Runs a 'stat' against the servers.
260      if (!waitForServerUp(currentClientPort, connectionTimeout)) {
261        throw new IOException("Waiting for startup of standalone server");
262      }
263
264      // We have selected a port as a client port.  Update clientPortList if necessary.
265      if (clientPortList.size() <= i) { // it is not in the list, add the port
266        clientPortList.add(currentClientPort);
267      }
268      else if (clientPortList.get(i) <= 0) { // the list has invalid port, update with valid port
269        clientPortList.remove(i);
270        clientPortList.add(i, currentClientPort);
271      }
272
273      standaloneServerFactoryList.add(standaloneServerFactory);
274      zooKeeperServers.add(server);
275    }
276
277    // set the first one to be active ZK; Others are backups
278    activeZKServerIndex = 0;
279    started = true;
280    int clientPort = clientPortList.get(activeZKServerIndex);
281    LOG.info("Started MiniZooKeeperCluster and ran successful 'stat' " +
282        "on client port=" + clientPort);
283    return clientPort;
284  }
285
286  private void createDir(File dir) throws IOException {
287    try {
288      if (!dir.exists()) {
289        dir.mkdirs();
290      }
291    } catch (SecurityException e) {
292      throw new IOException("creating dir: " + dir, e);
293    }
294  }
295
296  /**
297   * @throws IOException if waiting for the shutdown of a server fails
298   */
299  public void shutdown() throws IOException {
300    // shut down all the zk servers
301    for (int i = 0; i < standaloneServerFactoryList.size(); i++) {
302      NIOServerCnxnFactory standaloneServerFactory =
303        standaloneServerFactoryList.get(i);
304      int clientPort = clientPortList.get(i);
305
306      standaloneServerFactory.shutdown();
307      if (!waitForServerDown(clientPort, connectionTimeout)) {
308        throw new IOException("Waiting for shutdown of standalone server");
309      }
310    }
311    standaloneServerFactoryList.clear();
312
313    for (ZooKeeperServer zkServer: zooKeeperServers) {
314      //explicitly close ZKDatabase since ZookeeperServer does not close them
315      zkServer.getZKDatabase().close();
316    }
317    zooKeeperServers.clear();
318
319    // clear everything
320    if (started) {
321      started = false;
322      activeZKServerIndex = 0;
323      clientPortList.clear();
324      LOG.info("Shutdown MiniZK cluster with all ZK servers");
325    }
326  }
327
328  /**
329   * @return clientPort return clientPort if there is another ZK backup can run
330   *         when killing the current active; return -1, if there is no backups.
331   * @throws IOException if waiting for the shutdown of a server fails
332   */
333  public int killCurrentActiveZooKeeperServer() throws IOException, InterruptedException {
334    if (!started || activeZKServerIndex < 0) {
335      return -1;
336    }
337
338    // Shutdown the current active one
339    NIOServerCnxnFactory standaloneServerFactory =
340      standaloneServerFactoryList.get(activeZKServerIndex);
341    int clientPort = clientPortList.get(activeZKServerIndex);
342
343    standaloneServerFactory.shutdown();
344    if (!waitForServerDown(clientPort, connectionTimeout)) {
345      throw new IOException("Waiting for shutdown of standalone server");
346    }
347
348    zooKeeperServers.get(activeZKServerIndex).getZKDatabase().close();
349
350    // remove the current active zk server
351    standaloneServerFactoryList.remove(activeZKServerIndex);
352    clientPortList.remove(activeZKServerIndex);
353    zooKeeperServers.remove(activeZKServerIndex);
354    LOG.info("Kill the current active ZK servers in the cluster " +
355        "on client port: " + clientPort);
356
357    if (standaloneServerFactoryList.isEmpty()) {
358      // there is no backup servers;
359      return -1;
360    }
361    clientPort = clientPortList.get(activeZKServerIndex);
362    LOG.info("Activate a backup zk server in the cluster " +
363        "on client port: " + clientPort);
364    // return the next back zk server's port
365    return clientPort;
366  }
367
368  /**
369   * Kill one back up ZK servers.
370   *
371   * @throws IOException if waiting for the shutdown of a server fails
372   */
373  public void killOneBackupZooKeeperServer() throws IOException, InterruptedException {
374    if (!started || activeZKServerIndex < 0 || standaloneServerFactoryList.size() <= 1) {
375      return ;
376    }
377
378    int backupZKServerIndex = activeZKServerIndex+1;
379    // Shutdown the current active one
380    NIOServerCnxnFactory standaloneServerFactory =
381      standaloneServerFactoryList.get(backupZKServerIndex);
382    int clientPort = clientPortList.get(backupZKServerIndex);
383
384    standaloneServerFactory.shutdown();
385    if (!waitForServerDown(clientPort, connectionTimeout)) {
386      throw new IOException("Waiting for shutdown of standalone server");
387    }
388
389    zooKeeperServers.get(backupZKServerIndex).getZKDatabase().close();
390
391    // remove this backup zk server
392    standaloneServerFactoryList.remove(backupZKServerIndex);
393    clientPortList.remove(backupZKServerIndex);
394    zooKeeperServers.remove(backupZKServerIndex);
395    LOG.info("Kill one backup ZK servers in the cluster " +
396        "on client port: " + clientPort);
397  }
398
399  // XXX: From o.a.zk.t.ClientBase
400  private static boolean waitForServerDown(int port, long timeout) throws IOException {
401    long start = System.currentTimeMillis();
402    while (true) {
403      try {
404        Socket sock = new Socket("localhost", port);
405        try {
406          OutputStream outstream = sock.getOutputStream();
407          outstream.write("stat".getBytes());
408          outstream.flush();
409        } finally {
410          sock.close();
411        }
412      } catch (IOException e) {
413        return true;
414      }
415
416      if (System.currentTimeMillis() > start + timeout) {
417        break;
418      }
419      try {
420        Thread.sleep(250);
421      } catch (InterruptedException e) {
422        throw (InterruptedIOException)new InterruptedIOException().initCause(e);
423      }
424    }
425    return false;
426  }
427
428  // XXX: From o.a.zk.t.ClientBase
429  private static boolean waitForServerUp(int port, long timeout) throws IOException {
430    long start = System.currentTimeMillis();
431    while (true) {
432      try {
433        Socket sock = new Socket("localhost", port);
434        BufferedReader reader = null;
435        try {
436          OutputStream outstream = sock.getOutputStream();
437          outstream.write("stat".getBytes());
438          outstream.flush();
439
440          Reader isr = new InputStreamReader(sock.getInputStream());
441          reader = new BufferedReader(isr);
442          String line = reader.readLine();
443          if (line != null && line.startsWith("Zookeeper version:")) {
444            return true;
445          }
446        } finally {
447          sock.close();
448          if (reader != null) {
449            reader.close();
450          }
451        }
452      } catch (IOException e) {
453        // ignore as this is expected
454        LOG.info("server localhost:" + port + " not up " + e);
455      }
456
457      if (System.currentTimeMillis() > start + timeout) {
458        break;
459      }
460      try {
461        Thread.sleep(250);
462      } catch (InterruptedException e) {
463        throw (InterruptedIOException)new InterruptedIOException().initCause(e);
464      }
465    }
466    return false;
467  }
468
469  public int getClientPort() {
470    return activeZKServerIndex < 0 || activeZKServerIndex >= clientPortList.size() ? -1
471        : clientPortList.get(activeZKServerIndex);
472  }
473
474  List<ZooKeeperServer> getZooKeeperServers() {
475    return zooKeeperServers;
476  }
477}