View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional information regarding
4    * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
7    * law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
8    * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
9    * for the specific language governing permissions and limitations under the License.
10   */
11  package org.apache.hadoop.hbase.namespace;
12  
13  import java.io.IOException;
14  import java.util.List;
15  import java.util.Map;
16  import java.util.concurrent.ConcurrentHashMap;
17  import java.util.concurrent.ConcurrentMap;
18  
19  import org.apache.commons.logging.Log;
20  import org.apache.commons.logging.LogFactory;
21  import org.apache.hadoop.hbase.HRegionInfo;
22  import org.apache.hadoop.hbase.NamespaceDescriptor;
23  import org.apache.hadoop.hbase.RegionTransition;
24  import org.apache.hadoop.hbase.ServerName;
25  import org.apache.hadoop.hbase.TableName;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.client.MetaScanner;
28  import org.apache.hadoop.hbase.exceptions.DeserializationException;
29  import org.apache.hadoop.hbase.executor.EventType;
30  import org.apache.hadoop.hbase.master.MasterServices;
31  import org.apache.hadoop.hbase.master.TableNamespaceManager;
32  import org.apache.hadoop.hbase.quotas.QuotaExceededException;
33  import org.apache.hadoop.hbase.util.Bytes;
34  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
35  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
36  import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener;
37  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
38  import org.apache.zookeeper.KeeperException;
39  import org.apache.zookeeper.data.Stat;
40  
41  /**
42   * NamespaceStateManager manages state (in terms of quota) of all the namespaces. It contains a
43   * cache which is updated based on the hooks in the NamespaceAuditor class.
44   */
45  @InterfaceAudience.Private
46  class NamespaceStateManager extends ZooKeeperListener {
47  
48    private static Log LOG = LogFactory.getLog(NamespaceStateManager.class);
49    private ConcurrentMap<String, NamespaceTableAndRegionInfo> nsStateCache;
50    private MasterServices master;
51    private volatile boolean initialized = false;
52  
53    public NamespaceStateManager(MasterServices masterServices, ZooKeeperWatcher zkw) {
54      super(zkw);
55      nsStateCache = new ConcurrentHashMap<String, NamespaceTableAndRegionInfo>();
56      master = masterServices;
57    }
58  
59    /**
60     * Starts the NamespaceStateManager. The boot strap of cache is done in the post master start hook
61     * of the NamespaceAuditor class.
62     * @throws IOException Signals that an I/O exception has occurred.
63     */
64    public void start() throws IOException {
65      LOG.info("Namespace State Manager started.");
66      initialize();
67      watcher.registerListenerFirst(this);
68    }
69  
70    /**
71     * Gets an instance of NamespaceTableAndRegionInfo associated with namespace.
72     * @param The name of the namespace
73     * @return An instance of NamespaceTableAndRegionInfo.
74     */
75    public NamespaceTableAndRegionInfo getState(String name) {
76      return nsStateCache.get(name);
77    }
78  
79    /**
80     * Check if adding a region violates namespace quota, if not update namespace cache.
81     * @param TableName
82     * @param regionName
83     * @param incr
84     * @return true, if region can be added to table.
85     * @throws IOException Signals that an I/O exception has occurred.
86     */
87    synchronized boolean checkAndUpdateNamespaceRegionCount(TableName name, byte[] regionName,
88        int incr) throws IOException {
89      String namespace = name.getNamespaceAsString();
90      NamespaceDescriptor nspdesc = getNamespaceDescriptor(namespace);
91      if (nspdesc != null) {
92        NamespaceTableAndRegionInfo currentStatus;
93        currentStatus = getState(namespace);
94        if (incr > 0
95            && currentStatus.getRegionCount() >= TableNamespaceManager.getMaxRegions(nspdesc)) {
96          LOG.warn("The region " + Bytes.toStringBinary(regionName)
97              + " cannot be created. The region count  will exceed quota on the namespace. "
98              + "This may be transient, please retry later if there are any ongoing split"
99              + " operations in the namespace.");
100         return false;
101       }
102       NamespaceTableAndRegionInfo nsInfo = nsStateCache.get(namespace);
103       if (nsInfo != null) {
104         nsInfo.incRegionCountForTable(name, incr);
105       } else {
106         LOG.warn("Namespace state found null for namespace : " + namespace);
107       }
108     }
109     return true;
110   }
111 
112   private NamespaceDescriptor getNamespaceDescriptor(String namespaceAsString) {
113     try {
114       return this.master.getNamespaceDescriptor(namespaceAsString);
115     } catch (IOException e) {
116       LOG.error("Error while fetching namespace descriptor for namespace : " + namespaceAsString);
117       return null;
118     }
119   }
120 
121   synchronized void checkAndUpdateNamespaceTableCount(TableName table, int numRegions)
122       throws IOException {
123     String namespace = table.getNamespaceAsString();
124     NamespaceDescriptor nspdesc = getNamespaceDescriptor(namespace);
125     if (nspdesc != null) {
126       NamespaceTableAndRegionInfo currentStatus;
127       currentStatus = getState(nspdesc.getName());
128       if ((currentStatus.getTables().size()) >= TableNamespaceManager.getMaxTables(nspdesc)) {
129         throw new QuotaExceededException("The table " + table.getNameAsString()
130             + "cannot be created as it would exceed maximum number of tables allowed "
131             + " in the namespace.  The total number of tables permitted is "
132             + TableNamespaceManager.getMaxTables(nspdesc));
133       }
134       if ((currentStatus.getRegionCount() + numRegions) > TableNamespaceManager
135           .getMaxRegions(nspdesc)) {
136         throw new QuotaExceededException("The table " + table.getNameAsString()
137             + " is not allowed to have " + numRegions
138             + " regions. The total number of regions permitted is only "
139             + TableNamespaceManager.getMaxRegions(nspdesc) + ", while current region count is "
140             + currentStatus.getRegionCount()
141             + ". This may be transient, please retry later if there are any"
142             + " ongoing split operations in the namespace.");
143       }
144     } else {
145       throw new IOException("Namespace Descriptor found null for " + namespace
146           + " This is unexpected.");
147     }
148     addTable(table, numRegions);
149   }
150 
151   NamespaceTableAndRegionInfo addNamespace(String namespace) {
152     if (!nsStateCache.containsKey(namespace)) {
153       NamespaceTableAndRegionInfo a1 = new NamespaceTableAndRegionInfo(namespace);
154       nsStateCache.put(namespace, a1);
155     }
156     return nsStateCache.get(namespace);
157   }
158 
159   /**
160    * Delete the namespace state.
161    * @param An instance of NamespaceTableAndRegionInfo
162    */
163   void deleteNamespace(String namespace) {
164     this.nsStateCache.remove(namespace);
165   }
166 
167   private void addTable(TableName tableName, int regionCount) throws IOException {
168     NamespaceTableAndRegionInfo info = nsStateCache.get(tableName.getNamespaceAsString());
169     if (info != null) {
170       info.addTable(tableName, regionCount);
171     } else {
172       throw new IOException("Bad state : Namespace quota information not found for namespace : "
173           + tableName.getNamespaceAsString());
174     }
175   }
176 
177   synchronized void removeTable(TableName tableName) {
178     NamespaceTableAndRegionInfo info = nsStateCache.get(tableName.getNamespaceAsString());
179     if (info != null) {
180       info.removeTable(tableName);
181     }
182   }
183 
184   /**
185    * Initialize namespace state cache by scanning meta table.
186    */
187   private void initialize() throws IOException {
188     List<NamespaceDescriptor> namespaces = this.master.listNamespaceDescriptors();
189     for (NamespaceDescriptor namespace : namespaces) {
190       addNamespace(namespace.getName());
191       List<TableName> tables = this.master.listTableNamesByNamespace(namespace.getName());
192       for (TableName table : tables) {
193         if (table.isSystemTable()) {
194           continue;
195         }
196         int regionCount = 0;
197         Map<HRegionInfo, ServerName> regions =
198             MetaScanner.allTableRegions(this.master.getConnection(), table);
199         for (HRegionInfo info : regions.keySet()) {
200           if (!info.isSplit()) {
201             regionCount++;
202           }
203         }
204         addTable(table, regionCount);
205       }
206     }
207     LOG.info("Finished updating state of " + nsStateCache.size() + " namespaces. ");
208     initialized = true;
209   }
210 
211   boolean isInitialized() {
212     return initialized;
213   }
214 
215   public synchronized void removeRegionFromTable(HRegionInfo hri) throws IOException {
216     String namespace = hri.getTable().getNamespaceAsString();
217     NamespaceTableAndRegionInfo nsInfo = nsStateCache.get(namespace);
218     if (nsInfo != null) {
219       nsInfo.decrementRegionCountForTable(hri.getTable(), 1);
220     } else {
221       throw new IOException("Namespace state found null for namespace : " + namespace);
222     }
223   }
224 
225   @Override
226   public void nodeCreated(String path) {
227     checkSplittingOrMergingNode(path);
228   }
229 
230   @Override
231   public void nodeChildrenChanged(String path) {
232     checkSplittingOrMergingNode(path);
233   }
234 
235   private void checkSplittingOrMergingNode(String path) {
236     String msg = "Error reading data from zookeeper, ";
237     try {
238       if (path.startsWith(watcher.assignmentZNode)) {
239         List<String> children =
240             ZKUtil.listChildrenAndWatchForNewChildren(watcher, watcher.assignmentZNode);
241         if (children != null) {
242           for (String child : children) {
243             Stat stat = new Stat();
244             byte[] data =
245                 ZKAssign.getDataAndWatch(watcher, ZKUtil.joinZNode(watcher.assignmentZNode, child),
246                   stat);
247             if (data != null) {
248               RegionTransition rt = RegionTransition.parseFrom(data);
249               if (rt.getEventType().equals(EventType.RS_ZK_REQUEST_REGION_SPLIT)) {
250                 TableName table = HRegionInfo.getTable(rt.getRegionName());
251                 if (!checkAndUpdateNamespaceRegionCount(table, rt.getRegionName(), 1)) {
252                   ZKUtil.deleteNode(watcher, ZKUtil.joinZNode(watcher.assignmentZNode, child));
253                 }
254               } else if (rt.getEventType().equals(EventType.RS_ZK_REQUEST_REGION_MERGE)) {
255                 TableName table = HRegionInfo.getTable(rt.getRegionName());
256                 checkAndUpdateNamespaceRegionCount(table, rt.getRegionName(), -1);
257               }
258             }
259           }
260         }
261       }
262     } catch (KeeperException ke) {
263       LOG.error(msg, ke);
264       watcher.abort(msg, ke);
265     } catch (DeserializationException e) {
266       LOG.error(msg, e);
267       watcher.abort(msg, e);
268     } catch (IOException e) {
269       LOG.error(msg, e);
270       watcher.abort(msg, e);
271     }
272   }
273 }