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