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.InterruptedIOException;
22  import java.util.Arrays;
23  import java.util.HashMap;
24  import java.util.HashSet;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.Set;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.CoordinatedStateException;
32  import org.apache.hadoop.hbase.TableName;
33  import org.apache.hadoop.hbase.TableStateManager;
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  import org.apache.hadoop.hbase.exceptions.DeserializationException;
36  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
37  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
38  import org.apache.zookeeper.KeeperException;
39  
40  import com.google.protobuf.InvalidProtocolBufferException;
41  
42  /**
43   * Implementation of TableStateManager which reads, caches and sets state
44   * up in ZooKeeper.  If multiple read/write clients, will make for confusion.
45   * Code running on client side without consensus context should use
46   * {@link ZKTableStateClientSideReader} instead.
47   *
48   * <p>To save on trips to the zookeeper ensemble, internally we cache table
49   * state.
50   */
51  @InterfaceAudience.Private
52  public class ZKTableStateManager implements TableStateManager {
53    // A znode will exist under the table directory if it is in any of the
54    // following states: {@link TableState#ENABLING} , {@link TableState#DISABLING},
55    // or {@link TableState#DISABLED}.  If {@link TableState#ENABLED}, there will
56    // be no entry for a table in zk.  Thats how it currently works.
57  
58    private static final Log LOG = LogFactory.getLog(ZKTableStateManager.class);
59    private final ZooKeeperWatcher watcher;
60  
61    /**
62     * Cache of what we found in zookeeper so we don't have to go to zk ensemble
63     * for every query.  Synchronize access rather than use concurrent Map because
64     * synchronization needs to span query of zk.
65     */
66    private final Map<TableName, ZooKeeperProtos.Table.State> cache =
67      new HashMap<TableName, ZooKeeperProtos.Table.State>();
68  
69    public ZKTableStateManager(final ZooKeeperWatcher zkw) throws KeeperException,
70        InterruptedException {
71      super();
72      this.watcher = zkw;
73      populateTableStates();
74    }
75  
76    /**
77     * Gets a list of all the tables set as disabled in zookeeper.
78     * @throws KeeperException, InterruptedException
79     */
80    private void populateTableStates() throws KeeperException, InterruptedException {
81      synchronized (this.cache) {
82        List<String> children = ZKUtil.listChildrenNoWatch(this.watcher, this.watcher.tableZNode);
83        if (children == null) return;
84        for (String child: children) {
85          TableName tableName = TableName.valueOf(child);
86          ZooKeeperProtos.Table.State state = getTableState(this.watcher, tableName);
87          if (state != null) this.cache.put(tableName, state);
88        }
89      }
90    }
91  
92    /**
93     * Sets table state in ZK. Sets no watches.
94     *
95     * {@inheritDoc}
96     */
97    @Override
98    public void setTableState(TableName tableName, ZooKeeperProtos.Table.State state)
99    throws CoordinatedStateException {
100     synchronized (this.cache) {
101       LOG.warn("Moving table " + tableName + " state from " + this.cache.get(tableName)
102         + " to " + state);
103       try {
104         setTableStateInZK(tableName, state);
105       } catch (KeeperException e) {
106         throw new CoordinatedStateException(e);
107       }
108     }
109   }
110 
111   /**
112    * Checks and sets table state in ZK. Sets no watches.
113    * {@inheritDoc}
114    */
115   @Override
116   public boolean setTableStateIfInStates(TableName tableName,
117                                          ZooKeeperProtos.Table.State newState,
118                                          ZooKeeperProtos.Table.State... states)
119       throws CoordinatedStateException {
120     synchronized (this.cache) {
121       // Transition ENABLED->DISABLING has to be performed with a hack, because
122       // we treat empty state as enabled in this case because 0.92- clusters.
123       if (
124           (newState == ZooKeeperProtos.Table.State.DISABLING) &&
125                this.cache.get(tableName) != null && !isTableState(tableName, states) ||
126           (newState != ZooKeeperProtos.Table.State.DISABLING &&
127                !isTableState(tableName, states) )) {
128         return false;
129       }
130       try {
131         setTableStateInZK(tableName, newState);
132       } catch (KeeperException e) {
133         throw new CoordinatedStateException(e);
134       }
135       return true;
136     }
137   }
138 
139   /**
140    * Checks and sets table state in ZK. Sets no watches.
141    * {@inheritDoc}
142    */
143   @Override
144   public boolean setTableStateIfNotInStates(TableName tableName,
145                                             ZooKeeperProtos.Table.State newState,
146                                             ZooKeeperProtos.Table.State... states)
147     throws CoordinatedStateException {
148     synchronized (this.cache) {
149       if (isTableState(tableName, states)) {
150         // If the table is in the one of the states from the states list, the cache
151         // might be out-of-date, try to find it out from the master source (zookeeper server).
152         //
153         // Note: this adds extra zookeeper server calls and might have performance impact.
154         // However, this is not the happy path so we should not reach here often. Therefore,
155         // the performance impact should be minimal to none.
156         try {
157           ZooKeeperProtos.Table.State curstate = getTableState(watcher, tableName);
158 
159           if (isTableInState(Arrays.asList(states), curstate)) {
160             return false;
161           }
162         } catch (KeeperException e) {
163           throw new CoordinatedStateException(e);
164         } catch (InterruptedException e) {
165           throw new CoordinatedStateException(e);
166         }
167       }
168       try {
169         setTableStateInZK(tableName, newState);
170       } catch (KeeperException e) {
171         throw new CoordinatedStateException(e);
172       }
173       return true;
174     }
175   }
176 
177   private void setTableStateInZK(final TableName tableName,
178                                  final ZooKeeperProtos.Table.State state)
179       throws KeeperException {
180     String znode = ZKUtil.joinZNode(this.watcher.tableZNode, tableName.getNameAsString());
181     if (ZKUtil.checkExists(this.watcher, znode) == -1) {
182       ZKUtil.createAndFailSilent(this.watcher, znode);
183     }
184     synchronized (this.cache) {
185       ZooKeeperProtos.Table.Builder builder = ZooKeeperProtos.Table.newBuilder();
186       builder.setState(state);
187       byte [] data = ProtobufUtil.prependPBMagic(builder.build().toByteArray());
188       ZKUtil.setData(this.watcher, znode, data);
189       this.cache.put(tableName, state);
190     }
191   }
192 
193   /**
194    * Checks if table is marked in specified state in ZK (using cache only). {@inheritDoc}
195    */
196   @Override
197   public boolean isTableState(final TableName tableName,
198       final ZooKeeperProtos.Table.State... states) {
199     return isTableState(tableName, false, states); // only check cache
200   }
201 
202   /**
203    * Checks if table is marked in specified state in ZK. {@inheritDoc}
204    */
205   @Override
206   public boolean isTableState(final TableName tableName, final boolean checkSource,
207       final ZooKeeperProtos.Table.State... states) {
208     boolean isTableInSpecifiedState;
209     synchronized (this.cache) {
210       ZooKeeperProtos.Table.State currentState = this.cache.get(tableName);
211       if (checkSource) {
212         // The cache might be out-of-date, try to find it out from the master source (zookeeper
213         // server) and update the cache.
214         try {
215           ZooKeeperProtos.Table.State stateInZK = getTableState(watcher, tableName);
216 
217           if (currentState != stateInZK) {
218             if (stateInZK != null) {
219               this.cache.put(tableName, stateInZK);
220             } else {
221               this.cache.remove(tableName);
222             }
223             currentState = stateInZK;
224           }
225         } catch (KeeperException | InterruptedException e) {
226           // Contacting zookeeper failed.  Let us just trust the value in cache.
227         }
228       }
229       return isTableInState(Arrays.asList(states), currentState);
230     }
231   }
232 
233   /**
234    * Deletes the table in zookeeper. Fails silently if the table is not currently disabled in
235    * zookeeper. Sets no watches. {@inheritDoc}
236    */
237   @Override
238   public void setDeletedTable(final TableName tableName)
239   throws CoordinatedStateException {
240     synchronized (this.cache) {
241       if (this.cache.remove(tableName) == null) {
242         LOG.warn("Moving table " + tableName + " state to deleted but was " +
243           "already deleted");
244       }
245       try {
246         ZKUtil.deleteNodeFailSilent(this.watcher,
247           ZKUtil.joinZNode(this.watcher.tableZNode, tableName.getNameAsString()));
248       } catch (KeeperException e) {
249         throw new CoordinatedStateException(e);
250       }
251     }
252   }
253 
254   /**
255    * check if table is present.
256    *
257    * @param tableName table we're working on
258    * @return true if the table is present
259    */
260   @Override
261   public boolean isTablePresent(final TableName tableName) {
262     synchronized (this.cache) {
263       ZooKeeperProtos.Table.State state = this.cache.get(tableName);
264       return !(state == null);
265     }
266   }
267 
268   /**
269    * Gets a list of all the tables set as disabling in zookeeper.
270    * @return Set of disabling tables, empty Set if none
271    * @throws CoordinatedStateException if error happened in underlying coordination engine
272    */
273   @Override
274   public Set<TableName> getTablesInStates(ZooKeeperProtos.Table.State... states)
275     throws InterruptedIOException, CoordinatedStateException {
276     try {
277       return getAllTables(states);
278     } catch (KeeperException e) {
279       throw new CoordinatedStateException(e);
280     }
281   }
282 
283   /**
284    * {@inheritDoc}
285    */
286   @Override
287   public void checkAndRemoveTableState(TableName tableName, ZooKeeperProtos.Table.State states,
288                                        boolean deletePermanentState)
289       throws CoordinatedStateException {
290     synchronized (this.cache) {
291       if (isTableState(tableName, states)) {
292         this.cache.remove(tableName);
293         if (deletePermanentState) {
294           try {
295             ZKUtil.deleteNodeFailSilent(this.watcher,
296                 ZKUtil.joinZNode(this.watcher.tableZNode, tableName.getNameAsString()));
297           } catch (KeeperException e) {
298             throw new CoordinatedStateException(e);
299           }
300         }
301       }
302     }
303   }
304 
305   /**
306    * Gets a list of all the tables of specified states in zookeeper.
307    * @return Set of tables of specified states, empty Set if none
308    * @throws KeeperException
309    */
310   Set<TableName> getAllTables(final ZooKeeperProtos.Table.State... states)
311       throws KeeperException, InterruptedIOException {
312 
313     Set<TableName> allTables = new HashSet<TableName>();
314     List<String> children =
315       ZKUtil.listChildrenNoWatch(watcher, watcher.tableZNode);
316     if(children == null) return allTables;
317     for (String child: children) {
318       TableName tableName = TableName.valueOf(child);
319       ZooKeeperProtos.Table.State state;
320       try {
321         state = getTableState(watcher, tableName);
322       } catch (InterruptedException e) {
323         throw new InterruptedIOException();
324       }
325       for (ZooKeeperProtos.Table.State expectedState: states) {
326         if (state == expectedState) {
327           allTables.add(tableName);
328           break;
329         }
330       }
331     }
332     return allTables;
333   }
334 
335   /**
336    * Gets table state from ZK.
337    * @param zkw ZooKeeperWatcher instance to use
338    * @param tableName table we're checking
339    * @return Null or {@link ZooKeeperProtos.Table.State} found in znode.
340    * @throws KeeperException
341    */
342   private ZooKeeperProtos.Table.State getTableState(final ZooKeeperWatcher zkw,
343                                                    final TableName tableName)
344     throws KeeperException, InterruptedException {
345     String znode = ZKUtil.joinZNode(zkw.tableZNode, tableName.getNameAsString());
346     byte [] data = ZKUtil.getData(zkw, znode);
347     if (data == null || data.length <= 0) return null;
348     try {
349       ProtobufUtil.expectPBMagicPrefix(data);
350       ZooKeeperProtos.Table.Builder builder = ZooKeeperProtos.Table.newBuilder();
351       int magicLen = ProtobufUtil.lengthOfPBMagic();
352       ZooKeeperProtos.Table t = builder.mergeFrom(data, magicLen, data.length - magicLen).build();
353       return t.getState();
354     } catch (InvalidProtocolBufferException e) {
355       KeeperException ke = new KeeperException.DataInconsistencyException();
356       ke.initCause(e);
357       throw ke;
358     } catch (DeserializationException e) {
359       throw ZKUtil.convert(e);
360     }
361   }
362 
363   /**
364    * @return true if current state isn't null and is contained
365    * in the list of expected states.
366    */
367   private boolean isTableInState(final List<ZooKeeperProtos.Table.State> expectedStates,
368                        final ZooKeeperProtos.Table.State currentState) {
369     return currentState != null && expectedStates.contains(currentState);
370   }
371 }