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.security.PrivilegedExceptionAction;
24  import java.util.ArrayList;
25  import java.util.List;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.fs.FileSystem;
32  import org.apache.hadoop.fs.Path;
33  import org.apache.hadoop.hbase.CoordinatedStateException;
34  import org.apache.hadoop.hbase.HRegionInfo;
35  import org.apache.hadoop.hbase.HTableDescriptor;
36  import org.apache.hadoop.hbase.MetaTableAccessor;
37  import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
38  import org.apache.hadoop.hbase.Server;
39  import org.apache.hadoop.hbase.TableDescriptor;
40  import org.apache.hadoop.hbase.TableExistsException;
41  import org.apache.hadoop.hbase.TableName;
42  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
43  import org.apache.hadoop.hbase.client.TableState;
44  import org.apache.hadoop.hbase.executor.EventHandler;
45  import org.apache.hadoop.hbase.executor.EventType;
46  import org.apache.hadoop.hbase.ipc.RpcServer;
47  import org.apache.hadoop.hbase.master.AssignmentManager;
48  import org.apache.hadoop.hbase.master.HMaster;
49  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
50  import org.apache.hadoop.hbase.master.MasterFileSystem;
51  import org.apache.hadoop.hbase.master.MasterServices;
52  import org.apache.hadoop.hbase.master.TableLockManager;
53  import org.apache.hadoop.hbase.master.TableLockManager.TableLock;
54  import org.apache.hadoop.hbase.security.User;
55  import org.apache.hadoop.hbase.security.UserProvider;
56  import org.apache.hadoop.hbase.util.FSTableDescriptors;
57  import org.apache.hadoop.hbase.util.FSUtils;
58  import org.apache.hadoop.hbase.util.ModifyRegionUtils;
59  import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
60  
61  /**
62   * Handler to create a table.
63   */
64  @InterfaceAudience.Private
65  public class CreateTableHandler extends EventHandler {
66    private static final Log LOG = LogFactory.getLog(CreateTableHandler.class);
67    protected final MasterFileSystem fileSystemManager;
68    protected final HTableDescriptor hTableDescriptor;
69    protected final Configuration conf;
70    private final AssignmentManager assignmentManager;
71    private final TableLockManager tableLockManager;
72    private final HRegionInfo [] newRegions;
73    private final MasterServices masterServices;
74    private final TableLock tableLock;
75    private User activeUser;
76  
77    public CreateTableHandler(Server server, MasterFileSystem fileSystemManager,
78        HTableDescriptor hTableDescriptor, Configuration conf, HRegionInfo [] newRegions,
79        MasterServices masterServices) {
80      super(server, EventType.C_M_CREATE_TABLE);
81  
82      this.fileSystemManager = fileSystemManager;
83      this.hTableDescriptor = hTableDescriptor;
84      this.conf = conf;
85      this.newRegions = newRegions;
86      this.masterServices = masterServices;
87      this.assignmentManager = masterServices.getAssignmentManager();
88      this.tableLockManager = masterServices.getTableLockManager();
89  
90      this.tableLock = this.tableLockManager.writeLock(this.hTableDescriptor.getTableName()
91          , EventType.C_M_CREATE_TABLE.toString());
92    }
93  
94    @Override
95    public CreateTableHandler prepare()
96        throws NotAllMetaRegionsOnlineException, TableExistsException, IOException {
97      int timeout = conf.getInt("hbase.client.catalog.timeout", 10000);
98      // Need hbase:meta availability to create a table
99      try {
100       if (server.getMetaTableLocator().waitMetaRegionLocation(
101           server.getZooKeeper(), timeout) == null) {
102         throw new NotAllMetaRegionsOnlineException();
103       }
104       // If we are creating the table in service to an RPC request, record the
105       // active user for later, so proper permissions will be applied to the
106       // new table by the AccessController if it is active
107       this.activeUser = RpcServer.getRequestUser();
108       if (this.activeUser == null) {
109         this.activeUser = UserProvider.instantiate(conf).getCurrent();
110       }
111     } catch (InterruptedException e) {
112       LOG.warn("Interrupted waiting for meta availability", e);
113       InterruptedIOException ie = new InterruptedIOException(e.getMessage());
114       ie.initCause(e);
115       throw ie;
116     }
117 
118     //acquire the table write lock, blocking. Make sure that it is released.
119     this.tableLock.acquire();
120     boolean success = false;
121     try {
122       TableName tableName = this.hTableDescriptor.getTableName();
123       if (MetaTableAccessor.tableExists(this.server.getConnection(), tableName)) {
124         throw new TableExistsException(tableName);
125       }
126       success = true;
127     } finally {
128       if (!success) {
129         releaseTableLock();
130       }
131     }
132     return this;
133   }
134 
135   @Override
136   public String toString() {
137     String name = "UnknownServerName";
138     if(server != null && server.getServerName() != null) {
139       name = server.getServerName().toString();
140     }
141     return getClass().getSimpleName() + "-" + name + "-" + getSeqid() + "-" +
142       this.hTableDescriptor.getTableName();
143   }
144 
145   @Override
146   public void process() {
147     TableName tableName = this.hTableDescriptor.getTableName();
148     LOG.info("Create table " + tableName);
149     HMaster master = ((HMaster) this.server);
150     try {
151       final MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
152       if (cpHost != null) {
153         cpHost.preCreateTableHandler(this.hTableDescriptor, this.newRegions);
154       }
155       handleCreateTable(tableName);
156       completed(null);
157       if (cpHost != null) {
158         this.activeUser.runAs(new PrivilegedExceptionAction<Void>() {
159           @Override
160           public Void run() throws Exception {
161             cpHost.postCreateTableHandler(hTableDescriptor, newRegions);
162             return null;
163           }
164         });
165       }
166     } catch (Throwable e) {
167       LOG.error("Error trying to create the table " + tableName, e);
168       if (master.isInitialized()) {
169         try {
170           ((HMaster) this.server).getMasterQuotaManager().removeTableFromNamespaceQuota(
171             hTableDescriptor.getTableName());
172         } catch (IOException e1) {
173           LOG.error("Error trying to update namespace quota " + e1);
174         }
175       }
176       completed(e);
177       
178     }
179   }
180 
181   /**
182    * Called after that process() is completed.
183    * @param exception null if process() is successful or not null if something has failed.
184    */
185   protected void completed(final Throwable exception) {
186     releaseTableLock();
187     LOG.info("Table, " + this.hTableDescriptor.getTableName() + ", creation " +
188         (exception == null ? "successful" : "failed. " + exception));
189   }
190 
191   /**
192    * Responsible of table creation (on-disk and META) and assignment.
193    * - Create the table directory and descriptor (temp folder)
194    * - Create the on-disk regions (temp folder)
195    *   [If something fails here: we've just some trash in temp]
196    * - Move the table from temp to the root directory
197    *   [If something fails here: we've the table in place but some of the rows required
198    *    present in META. (hbck needed)]
199    * - Add regions to META
200    *   [If something fails here: we don't have regions assigned: table disabled]
201    * - Assign regions to Region Servers
202    *   [If something fails here: we still have the table in disabled state]
203    * - Update ZooKeeper with the enabled state
204    */
205   private void handleCreateTable(TableName tableName)
206       throws IOException, CoordinatedStateException {
207     Path tempdir = fileSystemManager.getTempDir();
208     FileSystem fs = fileSystemManager.getFileSystem();
209 
210     // 1. Create Table Descriptor
211     // using a copy of descriptor, table will be created enabling first
212     TableDescriptor underConstruction = new TableDescriptor(
213         this.hTableDescriptor);
214     Path tempTableDir = FSUtils.getTableDir(tempdir, tableName);
215     ((FSTableDescriptors)(masterServices.getTableDescriptors()))
216         .createTableDescriptorForTableDirectory(
217         tempTableDir, underConstruction, false);
218     Path tableDir = FSUtils.getTableDir(fileSystemManager.getRootDir(), tableName);
219 
220     // 2. Create Regions
221     List<HRegionInfo> regionInfos = handleCreateHdfsRegions(tempdir, tableName);
222     // 3. Move Table temp directory to the hbase root location
223     if (!fs.rename(tempTableDir, tableDir)) {
224       throw new IOException("Unable to move table from temp=" + tempTableDir +
225         " to hbase root=" + tableDir);
226     }
227 
228     // populate descriptors cache to be visible in getAll
229     masterServices.getTableDescriptors().get(tableName);
230 
231     MetaTableAccessor.updateTableState(this.server.getConnection(), hTableDescriptor.getTableName(),
232         TableState.State.ENABLING);
233 
234     if (regionInfos != null && regionInfos.size() > 0) {
235       // 4. Add regions to META
236       addRegionsToMeta(regionInfos, hTableDescriptor.getRegionReplication());
237       // 5. Add replicas if needed
238       regionInfos = addReplicas(hTableDescriptor, regionInfos);
239 
240       // 6. Setup replication for region replicas if needed
241       if (hTableDescriptor.getRegionReplication() > 1) {
242         ServerRegionReplicaUtil.setupRegionReplicaReplication(conf);
243       }
244 
245       // 7. Trigger immediate assignment of the regions in round-robin fashion
246       ModifyRegionUtils.assignRegions(assignmentManager, regionInfos);
247     }
248 
249     // 8. Enable table
250     assignmentManager.getTableStateManager().setTableState(tableName,
251             TableState.State.ENABLED);
252 
253     // 9. Update the tabledescriptor cache.
254     ((HMaster) this.server).getTableDescriptors().get(tableName);
255   }
256 
257   /**
258    * Create any replicas for the regions (the default replicas that was
259    * already created is passed to the method)
260    * @param hTableDescriptor descriptor to use
261    * @param regions default replicas
262    * @return the combined list of default and non-default replicas
263    */
264   protected List<HRegionInfo> addReplicas(HTableDescriptor hTableDescriptor,
265       List<HRegionInfo> regions) {
266     int numRegionReplicas = hTableDescriptor.getRegionReplication() - 1;
267     if (numRegionReplicas <= 0) {
268       return regions;
269     }
270     List<HRegionInfo> hRegionInfos =
271         new ArrayList<HRegionInfo>((numRegionReplicas+1)*regions.size());
272     for (int i = 0; i < regions.size(); i++) {
273       for (int j = 1; j <= numRegionReplicas; j++) {
274         hRegionInfos.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(i), j));
275       }
276     }
277     hRegionInfos.addAll(regions);
278     return hRegionInfos;
279   }
280 
281   private void releaseTableLock() {
282     if (this.tableLock != null) {
283       try {
284         this.tableLock.release();
285       } catch (IOException ex) {
286         LOG.warn("Could not release the table lock", ex);
287       }
288     }
289   }
290 
291   /**
292    * Create the on-disk structure for the table, and returns the regions info.
293    * @param tableRootDir directory where the table is being created
294    * @param tableName name of the table under construction
295    * @return the list of regions created
296    */
297   protected List<HRegionInfo> handleCreateHdfsRegions(final Path tableRootDir,
298     final TableName tableName)
299       throws IOException {
300     return ModifyRegionUtils.createRegions(conf, tableRootDir,
301         hTableDescriptor, newRegions, null);
302   }
303 
304   /**
305    * Add the specified set of regions to the hbase:meta table.
306    */
307   protected void addRegionsToMeta(final List<HRegionInfo> regionInfos, int regionReplication)
308       throws IOException {
309     MetaTableAccessor.addRegionsToMeta(this.server.getConnection(), regionInfos, regionReplication);
310   }
311 }