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.master.handler;
20  
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.util.List;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.fs.FileSystem;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.CoordinatedStateException;
32  import org.apache.hadoop.hbase.TableName;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.HTableDescriptor;
35  import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
36  import org.apache.hadoop.hbase.Server;
37  import org.apache.hadoop.hbase.TableExistsException;
38  import org.apache.hadoop.hbase.catalog.CatalogTracker;
39  import org.apache.hadoop.hbase.catalog.MetaEditor;
40  import org.apache.hadoop.hbase.catalog.MetaReader;
41  import org.apache.hadoop.hbase.executor.EventHandler;
42  import org.apache.hadoop.hbase.executor.EventType;
43  import org.apache.hadoop.hbase.master.AssignmentManager;
44  import org.apache.hadoop.hbase.master.HMaster;
45  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
46  import org.apache.hadoop.hbase.master.MasterFileSystem;
47  import org.apache.hadoop.hbase.master.MasterServices;
48  import org.apache.hadoop.hbase.master.TableLockManager;
49  import org.apache.hadoop.hbase.master.TableLockManager.TableLock;
50  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
51  import org.apache.hadoop.hbase.util.FSTableDescriptors;
52  import org.apache.hadoop.hbase.util.FSUtils;
53  import org.apache.hadoop.hbase.util.ModifyRegionUtils;
54  
55  /**
56   * Handler to create a table.
57   */
58  @InterfaceAudience.Private
59  public class CreateTableHandler extends EventHandler {
60    private static final Log LOG = LogFactory.getLog(CreateTableHandler.class);
61    protected final MasterFileSystem fileSystemManager;
62    protected final HTableDescriptor hTableDescriptor;
63    protected final Configuration conf;
64    private final AssignmentManager assignmentManager;
65    private final CatalogTracker catalogTracker;
66    private final TableLockManager tableLockManager;
67    private final HRegionInfo [] newRegions;
68    private final TableLock tableLock;
69  
70    public CreateTableHandler(Server server, MasterFileSystem fileSystemManager,
71        HTableDescriptor hTableDescriptor, Configuration conf, HRegionInfo [] newRegions,
72        MasterServices masterServices) {
73      super(server, EventType.C_M_CREATE_TABLE);
74  
75      this.fileSystemManager = fileSystemManager;
76      this.hTableDescriptor = hTableDescriptor;
77      this.conf = conf;
78      this.newRegions = newRegions;
79      this.catalogTracker = masterServices.getCatalogTracker();
80      this.assignmentManager = masterServices.getAssignmentManager();
81      this.tableLockManager = masterServices.getTableLockManager();
82  
83      this.tableLock = this.tableLockManager.writeLock(this.hTableDescriptor.getTableName()
84          , EventType.C_M_CREATE_TABLE.toString());
85    }
86  
87    public CreateTableHandler prepare()
88        throws NotAllMetaRegionsOnlineException, TableExistsException, IOException {
89      int timeout = conf.getInt("hbase.client.catalog.timeout", 10000);
90      // Need hbase:meta availability to create a table
91      try {
92        if (catalogTracker.waitForMeta(timeout) == null) {
93          throw new NotAllMetaRegionsOnlineException();
94        }
95      } catch (InterruptedException e) {
96        LOG.warn("Interrupted waiting for meta availability", e);
97        InterruptedIOException ie = new InterruptedIOException(e.getMessage());
98        ie.initCause(e);
99        throw ie;
100     }
101 
102     //acquire the table write lock, blocking. Make sure that it is released.
103     this.tableLock.acquire();
104     boolean success = false;
105     try {
106       TableName tableName = this.hTableDescriptor.getTableName();
107       if (MetaReader.tableExists(catalogTracker, tableName)) {
108         throw new TableExistsException(tableName);
109       }
110 
111       checkAndSetEnablingTable(assignmentManager, tableName);
112       success = true;
113     } finally {
114       if (!success) {
115         releaseTableLock();
116       }
117     }
118     return this;
119   }
120 
121   static void checkAndSetEnablingTable(final AssignmentManager assignmentManager,
122       final TableName tableName) throws IOException {
123     // If we have multiple client threads trying to create the table at the
124     // same time, given the async nature of the operation, the table
125     // could be in a state where hbase:meta table hasn't been updated yet in
126     // the process() function.
127     // Use enabling state to tell if there is already a request for the same
128     // table in progress. This will introduce a new zookeeper call. Given
129     // createTable isn't a frequent operation, that should be ok.
130     // TODO: now that we have table locks, re-evaluate above -- table locks are not enough.
131     // We could have cleared the hbase.rootdir and not zk.  How can we detect this case?
132     // Having to clean zk AND hdfs is awkward.
133     try {
134       if (!assignmentManager.getTableStateManager().setTableStateIfNotInStates(tableName,
135         ZooKeeperProtos.Table.State.ENABLING,
136         ZooKeeperProtos.Table.State.ENABLING,
137         ZooKeeperProtos.Table.State.ENABLED)) {
138         throw new TableExistsException(tableName);
139       }
140     } catch (CoordinatedStateException e) {
141       throw new IOException("Unable to ensure that the table will be" +
142         " enabling because of a ZooKeeper issue", e);
143     }
144   }
145 
146   static void removeEnablingTable(final AssignmentManager assignmentManager,
147       final TableName tableName) {
148     // Try deleting the enabling node in case of error
149     // If this does not happen then if the client tries to create the table
150     // again with the same Active master
151     // It will block the creation saying TableAlreadyExists.
152     try {
153       assignmentManager.getTableStateManager().checkAndRemoveTableState(tableName,
154         ZooKeeperProtos.Table.State.ENABLING, false);
155     } catch (CoordinatedStateException e) {
156       // Keeper exception should not happen here
157       LOG.error("Got a keeper exception while removing the ENABLING table znode "
158           + tableName, e);
159     }
160   }
161 
162   @Override
163   public String toString() {
164     String name = "UnknownServerName";
165     if(server != null && server.getServerName() != null) {
166       name = server.getServerName().toString();
167     }
168     return getClass().getSimpleName() + "-" + name + "-" + getSeqid() + "-" +
169       this.hTableDescriptor.getTableName();
170   }
171 
172   @Override
173   public void process() {
174     TableName tableName = this.hTableDescriptor.getTableName();
175     LOG.info("Create table " + tableName);
176 
177     try {
178       MasterCoprocessorHost cpHost = ((HMaster) this.server).getMasterCoprocessorHost();
179       if (cpHost != null) {
180         cpHost.preCreateTableHandler(this.hTableDescriptor, this.newRegions);
181       }
182       handleCreateTable(tableName);
183       completed(null);
184       if (cpHost != null) {
185         cpHost.postCreateTableHandler(this.hTableDescriptor, this.newRegions);
186       }
187     } catch (Throwable e) {
188       LOG.error("Error trying to create the table " + tableName, e);
189       completed(e);
190     }
191   }
192 
193   /**
194    * Called after that process() is completed.
195    * @param exception null if process() is successful or not null if something has failed.
196    */
197   protected void completed(final Throwable exception) {
198     releaseTableLock();
199     String msg = exception == null ? null : exception.getMessage();
200     LOG.info("Table, " + this.hTableDescriptor.getTableName() + ", creation " +
201         msg == null ? "successful" : "failed. " + msg);
202     if (exception != null) {
203       removeEnablingTable(this.assignmentManager, this.hTableDescriptor.getTableName());
204     }
205   }
206 
207   /**
208    * Responsible of table creation (on-disk and META) and assignment.
209    * - Create the table directory and descriptor (temp folder)
210    * - Create the on-disk regions (temp folder)
211    *   [If something fails here: we've just some trash in temp]
212    * - Move the table from temp to the root directory
213    *   [If something fails here: we've the table in place but some of the rows required
214    *    present in META. (hbck needed)]
215    * - Add regions to META
216    *   [If something fails here: we don't have regions assigned: table disabled]
217    * - Assign regions to Region Servers
218    *   [If something fails here: we still have the table in disabled state]
219    * - Update ZooKeeper with the enabled state
220    */
221   private void handleCreateTable(TableName tableName)
222       throws IOException, CoordinatedStateException {
223     Path tempdir = fileSystemManager.getTempDir();
224     FileSystem fs = fileSystemManager.getFileSystem();
225 
226     // 1. Create Table Descriptor
227     Path tempTableDir = FSUtils.getTableDir(tempdir, tableName);
228     new FSTableDescriptors(this.conf).createTableDescriptorForTableDirectory(
229       tempTableDir, this.hTableDescriptor, false);
230     Path tableDir = FSUtils.getTableDir(fileSystemManager.getRootDir(), tableName);
231 
232     // 2. Create Regions
233     List<HRegionInfo> regionInfos = handleCreateHdfsRegions(tempdir, tableName);
234     // 3. Move Table temp directory to the hbase root location
235     if (!fs.rename(tempTableDir, tableDir)) {
236       throw new IOException("Unable to move table from temp=" + tempTableDir +
237         " to hbase root=" + tableDir);
238     }
239 
240     if (regionInfos != null && regionInfos.size() > 0) {
241       // 4. Add regions to META
242       addRegionsToMeta(this.catalogTracker, regionInfos);
243 
244       // 5. Trigger immediate assignment of the regions in round-robin fashion
245       ModifyRegionUtils.assignRegions(assignmentManager, regionInfos);
246     }
247 
248     // 6. Set table enabled flag up in zk.
249     try {
250       assignmentManager.getTableStateManager().setTableState(tableName,
251         ZooKeeperProtos.Table.State.ENABLED);
252     } catch (CoordinatedStateException e) {
253       throw new IOException("Unable to ensure that " + tableName + " will be" +
254         " enabled because of a ZooKeeper issue", e);
255     }
256   }
257 
258   private void releaseTableLock() {
259     if (this.tableLock != null) {
260       try {
261         this.tableLock.release();
262       } catch (IOException ex) {
263         LOG.warn("Could not release the table lock", ex);
264       }
265     }
266   }
267 
268   /**
269    * Create the on-disk structure for the table, and returns the regions info.
270    * @param tableRootDir directory where the table is being created
271    * @param tableName name of the table under construction
272    * @return the list of regions created
273    */
274   protected List<HRegionInfo> handleCreateHdfsRegions(final Path tableRootDir,
275     final TableName tableName)
276       throws IOException {
277     return ModifyRegionUtils.createRegions(conf, tableRootDir,
278         hTableDescriptor, newRegions, null);
279   }
280 
281   /**
282    * Add the specified set of regions to the hbase:meta table.
283    */
284   protected void addRegionsToMeta(final CatalogTracker ct, final List<HRegionInfo> regionInfos)
285       throws IOException {
286     MetaEditor.addRegionsToMeta(this.catalogTracker, regionInfos);
287   }
288 }