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.ArrayList;
24  import java.util.List;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.fs.FileSystem;
31  import org.apache.hadoop.fs.Path;
32  import org.apache.hadoop.hbase.CoordinatedStateException;
33  import org.apache.hadoop.hbase.TableName;
34  import org.apache.hadoop.hbase.HRegionInfo;
35  import org.apache.hadoop.hbase.HTableDescriptor;
36  import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
37  import org.apache.hadoop.hbase.Server;
38  import org.apache.hadoop.hbase.TableExistsException;
39  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
40  import org.apache.hadoop.hbase.MetaTableAccessor;
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 TableLockManager tableLockManager;
66    private final HRegionInfo [] newRegions;
67    private final TableLock tableLock;
68  
69    public CreateTableHandler(Server server, MasterFileSystem fileSystemManager,
70        HTableDescriptor hTableDescriptor, Configuration conf, HRegionInfo [] newRegions,
71        MasterServices masterServices) {
72      super(server, EventType.C_M_CREATE_TABLE);
73  
74      this.fileSystemManager = fileSystemManager;
75      this.hTableDescriptor = hTableDescriptor;
76      this.conf = conf;
77      this.newRegions = newRegions;
78      this.assignmentManager = masterServices.getAssignmentManager();
79      this.tableLockManager = masterServices.getTableLockManager();
80  
81      this.tableLock = this.tableLockManager.writeLock(this.hTableDescriptor.getTableName()
82          , EventType.C_M_CREATE_TABLE.toString());
83    }
84  
85    @Override
86    public CreateTableHandler prepare()
87        throws NotAllMetaRegionsOnlineException, TableExistsException, IOException {
88      int timeout = conf.getInt("hbase.client.catalog.timeout", 10000);
89      // Need hbase:meta availability to create a table
90      try {
91        if (server.getMetaTableLocator().waitMetaRegionLocation(
92            server.getZooKeeper(), 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 (MetaTableAccessor.tableExists(this.server.getShortCircuitConnection(), 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(regionInfos);
243       // 5. Add replicas if needed
244       regionInfos = addReplicas(hTableDescriptor, regionInfos);
245 
246       // 6. Trigger immediate assignment of the regions in round-robin fashion
247       ModifyRegionUtils.assignRegions(assignmentManager, regionInfos);
248     }
249 
250     // 6. Set table enabled flag up in zk.
251     try {
252       assignmentManager.getTableStateManager().setTableState(tableName,
253         ZooKeeperProtos.Table.State.ENABLED);
254     } catch (CoordinatedStateException e) {
255       throw new IOException("Unable to ensure that " + tableName + " will be" +
256         " enabled because of a ZooKeeper issue", e);
257     }
258   }
259 
260   /**
261    * Create any replicas for the regions (the default replicas that was
262    * already created is passed to the method)
263    * @param hTableDescriptor
264    * @param regions default replicas
265    * @return the combined list of default and non-default replicas
266    */
267   protected List<HRegionInfo> addReplicas(HTableDescriptor hTableDescriptor,
268       List<HRegionInfo> regions) {
269     int numRegionReplicas = hTableDescriptor.getRegionReplication() - 1;
270     if (numRegionReplicas <= 0) {
271       return regions;
272     }
273     List<HRegionInfo> hRegionInfos =
274         new ArrayList<HRegionInfo>((numRegionReplicas+1)*regions.size());
275     for (int i = 0; i < regions.size(); i++) {
276       for (int j = 1; j <= numRegionReplicas; j++) {
277         hRegionInfos.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(i), j));
278       }
279     }
280     hRegionInfos.addAll(regions);
281     return hRegionInfos;
282   }
283 
284   private void releaseTableLock() {
285     if (this.tableLock != null) {
286       try {
287         this.tableLock.release();
288       } catch (IOException ex) {
289         LOG.warn("Could not release the table lock", ex);
290       }
291     }
292   }
293 
294   /**
295    * Create the on-disk structure for the table, and returns the regions info.
296    * @param tableRootDir directory where the table is being created
297    * @param tableName name of the table under construction
298    * @return the list of regions created
299    */
300   protected List<HRegionInfo> handleCreateHdfsRegions(final Path tableRootDir,
301     final TableName tableName)
302       throws IOException {
303     return ModifyRegionUtils.createRegions(conf, tableRootDir,
304         hTableDescriptor, newRegions, null);
305   }
306 
307   /**
308    * Add the specified set of regions to the hbase:meta table.
309    */
310   protected void addRegionsToMeta(final List<HRegionInfo> regionInfos)
311       throws IOException {
312     MetaTableAccessor.addRegionsToMeta(this.server.getShortCircuitConnection(), regionInfos);
313   }
314 }