View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.zookeeper;
20  
21  import java.io.BufferedReader;
22  import java.io.File;
23  import java.io.InterruptedIOException;
24  import java.io.IOException;
25  import java.io.InputStreamReader;
26  import java.io.OutputStream;
27  import java.io.Reader;
28  import java.net.BindException;
29  import java.net.InetSocketAddress;
30  import java.net.Socket;
31  import java.util.ArrayList;
32  import java.util.List;
33  import java.util.Random;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.classification.InterfaceAudience;
38  import org.apache.hadoop.classification.InterfaceStability;
39  import org.apache.hadoop.conf.Configuration;
40  import org.apache.hadoop.fs.FileUtil;
41  import org.apache.hadoop.hbase.HConstants;
42  import org.apache.zookeeper.server.NIOServerCnxnFactory;
43  import org.apache.zookeeper.server.ZooKeeperServer;
44  import org.apache.zookeeper.server.persistence.FileTxnLog;
45  
46  /**
47   * TODO: Most of the code in this class is ripped from ZooKeeper tests. Instead
48   * of redoing it, we should contribute updates to their code which let us more
49   * easily access testing helper objects.
50   */
51  @InterfaceAudience.Public
52  @InterfaceStability.Evolving
53  public class MiniZooKeeperCluster {
54    private static final Log LOG = LogFactory.getLog(MiniZooKeeperCluster.class);
55  
56    private static final int TICK_TIME = 2000;
57    private static final int CONNECTION_TIMEOUT = 30000;
58  
59    private boolean started;
60  
61    /** The default port. If zero, we use a random port. */
62    private int defaultClientPort = 0;
63  
64    private List<NIOServerCnxnFactory> standaloneServerFactoryList;
65    private List<ZooKeeperServer> zooKeeperServers;
66    private List<Integer> clientPortList;
67  
68    private int activeZKServerIndex;
69    private int tickTime = 0;
70  
71    private Configuration configuration;
72  
73    public MiniZooKeeperCluster() {
74      this(new Configuration());
75    }
76  
77    public MiniZooKeeperCluster(Configuration configuration) {
78      this.started = false;
79      this.configuration = configuration;
80      activeZKServerIndex = -1;
81      zooKeeperServers = new ArrayList<ZooKeeperServer>();
82      clientPortList = new ArrayList<Integer>();
83      standaloneServerFactoryList = new ArrayList<NIOServerCnxnFactory>();
84    }
85  
86    public void setDefaultClientPort(int clientPort) {
87      if (clientPort <= 0) {
88        throw new IllegalArgumentException("Invalid default ZK client port: "
89            + clientPort);
90      }
91      this.defaultClientPort = clientPort;
92    }
93  
94    /**
95     * Selects a ZK client port. Returns the default port if specified.
96     * Otherwise, returns a random port. The random port is selected from the
97     * range between 49152 to 65535. These ports cannot be registered with IANA
98     * and are intended for dynamic allocation (see http://bit.ly/dynports).
99     */
100   private int selectClientPort() {
101     if (defaultClientPort > 0) {
102       return defaultClientPort;
103     }
104     return 0xc000 + new Random().nextInt(0x3f00);
105   }
106 
107   public void setTickTime(int tickTime) {
108     this.tickTime = tickTime;
109   }
110 
111   public int getBackupZooKeeperServerNum() {
112     return zooKeeperServers.size()-1;
113   }
114 
115   public int getZooKeeperServerNum() {
116     return zooKeeperServers.size();
117   }
118 
119   // / XXX: From o.a.zk.t.ClientBase
120   private static void setupTestEnv() {
121     // during the tests we run with 100K prealloc in the logs.
122     // on windows systems prealloc of 64M was seen to take ~15seconds
123     // resulting in test failure (client timeout on first session).
124     // set env and directly in order to handle static init/gc issues
125     System.setProperty("zookeeper.preAllocSize", "100");
126     FileTxnLog.setPreallocSize(100 * 1024);
127   }
128 
129   public int startup(File baseDir) throws IOException, InterruptedException {
130     return startup(baseDir,1);
131   }
132 
133   /**
134    * @param baseDir
135    * @param numZooKeeperServers
136    * @return ClientPort server bound to, -1 if there was a
137    *         binding problem and we couldn't pick another port.
138    * @throws IOException
139    * @throws InterruptedException
140    */
141   public int startup(File baseDir, int numZooKeeperServers) throws IOException,
142       InterruptedException {
143     if (numZooKeeperServers <= 0)
144       return -1;
145 
146     setupTestEnv();
147     shutdown();
148 
149     int tentativePort = selectClientPort();
150 
151     // running all the ZK servers
152     for (int i = 0; i < numZooKeeperServers; i++) {
153       File dir = new File(baseDir, "zookeeper_"+i).getAbsoluteFile();
154       createDir(dir);
155       int tickTimeToUse;
156       if (this.tickTime > 0) {
157         tickTimeToUse = this.tickTime;
158       } else {
159         tickTimeToUse = TICK_TIME;
160       }
161       ZooKeeperServer server = new ZooKeeperServer(dir, dir, tickTimeToUse);
162       NIOServerCnxnFactory standaloneServerFactory;
163       while (true) {
164         try {
165           standaloneServerFactory = new NIOServerCnxnFactory();
166           standaloneServerFactory.configure(
167             new InetSocketAddress(tentativePort),
168             configuration.getInt(HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS,
169               1000));
170         } catch (BindException e) {
171           LOG.debug("Failed binding ZK Server to client port: " +
172               tentativePort, e);
173           // We're told to use some port but it's occupied, fail
174           if (defaultClientPort > 0) return -1;
175           // This port is already in use, try to use another.
176           tentativePort = selectClientPort();
177           continue;
178         }
179         break;
180       }
181 
182       // Start up this ZK server
183       standaloneServerFactory.startup(server);
184       if (!waitForServerUp(tentativePort, CONNECTION_TIMEOUT)) {
185         throw new IOException("Waiting for startup of standalone server");
186       }
187 
188       // We have selected this port as a client port.
189       clientPortList.add(tentativePort);
190       standaloneServerFactoryList.add(standaloneServerFactory);
191       zooKeeperServers.add(server);
192       tentativePort++; //for the next server
193     }
194 
195     // set the first one to be active ZK; Others are backups
196     activeZKServerIndex = 0;
197     started = true;
198     int clientPort = clientPortList.get(activeZKServerIndex);
199     LOG.info("Started MiniZK Cluster and connect 1 ZK server " +
200         "on client port: " + clientPort);
201     return clientPort;
202   }
203 
204   private void createDir(File dir) throws IOException {
205     try {
206       if (!dir.exists()) {
207         dir.mkdirs();
208       }
209     } catch (SecurityException e) {
210       throw new IOException("creating dir: " + dir, e);
211     }
212   }
213 
214   /**
215    * @throws IOException
216    */
217   public void shutdown() throws IOException {
218     if (!started) {
219       return;
220     }
221 
222     // shut down all the zk servers
223     for (int i = 0; i < standaloneServerFactoryList.size(); i++) {
224       NIOServerCnxnFactory standaloneServerFactory =
225         standaloneServerFactoryList.get(i);
226       int clientPort = clientPortList.get(i);
227 
228       standaloneServerFactory.shutdown();
229       if (!waitForServerDown(clientPort, CONNECTION_TIMEOUT)) {
230         throw new IOException("Waiting for shutdown of standalone server");
231       }
232     }
233     for (ZooKeeperServer zkServer: zooKeeperServers) {
234       //explicitly close ZKDatabase since ZookeeperServer does not close them
235       zkServer.getZKDatabase().close();
236     }
237 
238     // clear everything
239     started = false;
240     activeZKServerIndex = 0;
241     standaloneServerFactoryList.clear();
242     clientPortList.clear();
243     zooKeeperServers.clear();
244 
245     LOG.info("Shutdown MiniZK cluster with all ZK servers");
246   }
247 
248   /**@return clientPort return clientPort if there is another ZK backup can run
249    *         when killing the current active; return -1, if there is no backups.
250    * @throws IOException
251    * @throws InterruptedException
252    */
253   public int killCurrentActiveZooKeeperServer() throws IOException,
254                                         InterruptedException {
255     if (!started || activeZKServerIndex < 0 ) {
256       return -1;
257     }
258 
259     // Shutdown the current active one
260     NIOServerCnxnFactory standaloneServerFactory =
261       standaloneServerFactoryList.get(activeZKServerIndex);
262     int clientPort = clientPortList.get(activeZKServerIndex);
263 
264     standaloneServerFactory.shutdown();
265     if (!waitForServerDown(clientPort, CONNECTION_TIMEOUT)) {
266       throw new IOException("Waiting for shutdown of standalone server");
267     }
268 
269     zooKeeperServers.get(activeZKServerIndex).getZKDatabase().close();
270 
271     // remove the current active zk server
272     standaloneServerFactoryList.remove(activeZKServerIndex);
273     clientPortList.remove(activeZKServerIndex);
274     zooKeeperServers.remove(activeZKServerIndex);
275     LOG.info("Kill the current active ZK servers in the cluster " +
276         "on client port: " + clientPort);
277 
278     if (standaloneServerFactoryList.size() == 0) {
279       // there is no backup servers;
280       return -1;
281     }
282     clientPort = clientPortList.get(activeZKServerIndex);
283     LOG.info("Activate a backup zk server in the cluster " +
284         "on client port: " + clientPort);
285     // return the next back zk server's port
286     return clientPort;
287   }
288 
289   /**
290    * Kill one back up ZK servers
291    * @throws IOException
292    * @throws InterruptedException
293    */
294   public void killOneBackupZooKeeperServer() throws IOException,
295                                         InterruptedException {
296     if (!started || activeZKServerIndex < 0 ||
297         standaloneServerFactoryList.size() <= 1) {
298       return ;
299     }
300 
301     int backupZKServerIndex = activeZKServerIndex+1;
302     // Shutdown the current active one
303     NIOServerCnxnFactory standaloneServerFactory =
304       standaloneServerFactoryList.get(backupZKServerIndex);
305     int clientPort = clientPortList.get(backupZKServerIndex);
306 
307     standaloneServerFactory.shutdown();
308     if (!waitForServerDown(clientPort, CONNECTION_TIMEOUT)) {
309       throw new IOException("Waiting for shutdown of standalone server");
310     }
311 
312     zooKeeperServers.get(backupZKServerIndex).getZKDatabase().close();
313 
314     // remove this backup zk server
315     standaloneServerFactoryList.remove(backupZKServerIndex);
316     clientPortList.remove(backupZKServerIndex);
317     zooKeeperServers.remove(backupZKServerIndex);
318     LOG.info("Kill one backup ZK servers in the cluster " +
319         "on client port: " + clientPort);
320   }
321 
322   // XXX: From o.a.zk.t.ClientBase
323   private static boolean waitForServerDown(int port, long timeout) throws IOException {
324     long start = System.currentTimeMillis();
325     while (true) {
326       try {
327         Socket sock = new Socket("localhost", port);
328         try {
329           OutputStream outstream = sock.getOutputStream();
330           outstream.write("stat".getBytes());
331           outstream.flush();
332         } finally {
333           sock.close();
334         }
335       } catch (IOException e) {
336         return true;
337       }
338 
339       if (System.currentTimeMillis() > start + timeout) {
340         break;
341       }
342       try {
343         Thread.sleep(250);
344       } catch (InterruptedException e) {
345         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
346       }
347     }
348     return false;
349   }
350 
351   // XXX: From o.a.zk.t.ClientBase
352   private static boolean waitForServerUp(int port, long timeout) throws IOException {
353     long start = System.currentTimeMillis();
354     while (true) {
355       try {
356         Socket sock = new Socket("localhost", port);
357         BufferedReader reader = null;
358         try {
359           OutputStream outstream = sock.getOutputStream();
360           outstream.write("stat".getBytes());
361           outstream.flush();
362 
363           Reader isr = new InputStreamReader(sock.getInputStream());
364           reader = new BufferedReader(isr);
365           String line = reader.readLine();
366           if (line != null && line.startsWith("Zookeeper version:")) {
367             return true;
368           }
369         } finally {
370           sock.close();
371           if (reader != null) {
372             reader.close();
373           }
374         }
375       } catch (IOException e) {
376         // ignore as this is expected
377         LOG.info("server localhost:" + port + " not up " + e);
378       }
379 
380       if (System.currentTimeMillis() > start + timeout) {
381         break;
382       }
383       try {
384         Thread.sleep(250);
385       } catch (InterruptedException e) {
386         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
387       }
388     }
389     return false;
390   }
391 
392   public int getClientPort() {
393     return activeZKServerIndex < 0 || activeZKServerIndex >= clientPortList.size() ? -1
394         : clientPortList.get(activeZKServerIndex);
395   }
396 }