View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.master.procedure;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.OutputStream;
24  import java.security.PrivilegedExceptionAction;
25  import java.util.ArrayList;
26  import java.util.List;
27  import java.util.concurrent.atomic.AtomicBoolean;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.fs.FileSystem;
32  import org.apache.hadoop.fs.Path;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.HTableDescriptor;
35  import org.apache.hadoop.hbase.MetaTableAccessor;
36  import org.apache.hadoop.hbase.TableExistsException;
37  import org.apache.hadoop.hbase.TableName;
38  import org.apache.hadoop.hbase.TableStateManager;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
41  import org.apache.hadoop.hbase.exceptions.HBaseException;
42  import org.apache.hadoop.hbase.master.AssignmentManager;
43  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
44  import org.apache.hadoop.hbase.master.MasterFileSystem;
45  import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
46  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
47  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos;
48  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.CreateTableState;
49  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
50  import org.apache.hadoop.hbase.util.FSTableDescriptors;
51  import org.apache.hadoop.hbase.util.FSUtils;
52  import org.apache.hadoop.hbase.util.ModifyRegionUtils;
53  import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
54  import org.apache.hadoop.security.UserGroupInformation;
55  
56  import com.google.common.collect.Lists;
57  
58  @InterfaceAudience.Private
59  public class CreateTableProcedure
60      extends StateMachineProcedure<MasterProcedureEnv, CreateTableState>
61      implements TableProcedureInterface {
62    private static final Log LOG = LogFactory.getLog(CreateTableProcedure.class);
63  
64    private final AtomicBoolean aborted = new AtomicBoolean(false);
65  
66    // used for compatibility with old clients
67    private final ProcedurePrepareLatch syncLatch;
68  
69    private HTableDescriptor hTableDescriptor;
70    private List<HRegionInfo> newRegions;
71    private UserGroupInformation user;
72  
73    public CreateTableProcedure() {
74      // Required by the Procedure framework to create the procedure on replay
75      syncLatch = null;
76    }
77  
78    public CreateTableProcedure(final MasterProcedureEnv env,
79        final HTableDescriptor hTableDescriptor, final HRegionInfo[] newRegions)
80        throws IOException {
81      this(env, hTableDescriptor, newRegions, null);
82    }
83  
84    public CreateTableProcedure(final MasterProcedureEnv env,
85        final HTableDescriptor hTableDescriptor, final HRegionInfo[] newRegions,
86        final ProcedurePrepareLatch syncLatch)
87        throws IOException {
88      this.hTableDescriptor = hTableDescriptor;
89      this.newRegions = newRegions != null ? Lists.newArrayList(newRegions) : null;
90      this.user = env.getRequestUser().getUGI();
91  
92      // used for compatibility with clients without procedures
93      // they need a sync TableExistsException
94      this.syncLatch = syncLatch;
95    }
96  
97    @Override
98    protected Flow executeFromState(final MasterProcedureEnv env, final CreateTableState state) {
99      if (LOG.isTraceEnabled()) {
100       LOG.trace(this + " execute state=" + state);
101     }
102     try {
103       switch (state) {
104         case CREATE_TABLE_PRE_OPERATION:
105           // Verify if we can create the table
106           boolean exists = !prepareCreate(env);
107           ProcedurePrepareLatch.releaseLatch(syncLatch, this);
108 
109           if (exists) {
110             assert isFailed() : "the delete should have an exception here";
111             return Flow.NO_MORE_STATE;
112           }
113 
114           preCreate(env);
115           setNextState(CreateTableState.CREATE_TABLE_WRITE_FS_LAYOUT);
116           break;
117         case CREATE_TABLE_WRITE_FS_LAYOUT:
118           newRegions = createFsLayout(env, hTableDescriptor, newRegions);
119           setNextState(CreateTableState.CREATE_TABLE_ADD_TO_META);
120           break;
121         case CREATE_TABLE_ADD_TO_META:
122           newRegions = addTableToMeta(env, hTableDescriptor, newRegions);
123           setNextState(CreateTableState.CREATE_TABLE_ASSIGN_REGIONS);
124           break;
125         case CREATE_TABLE_ASSIGN_REGIONS:
126           assignRegions(env, getTableName(), newRegions);
127           setNextState(CreateTableState.CREATE_TABLE_UPDATE_DESC_CACHE);
128           break;
129         case CREATE_TABLE_UPDATE_DESC_CACHE:
130           updateTableDescCache(env, getTableName());
131           setNextState(CreateTableState.CREATE_TABLE_POST_OPERATION);
132           break;
133         case CREATE_TABLE_POST_OPERATION:
134           postCreate(env);
135           return Flow.NO_MORE_STATE;
136         default:
137           throw new UnsupportedOperationException("unhandled state=" + state);
138       }
139     } catch (InterruptedException|HBaseException|IOException e) {
140       LOG.error("Error trying to create table=" + getTableName() + " state=" + state, e);
141       setFailure("master-create-table", e);
142     }
143     return Flow.HAS_MORE_STATE;
144   }
145 
146   @Override
147   protected void rollbackState(final MasterProcedureEnv env, final CreateTableState state)
148       throws IOException {
149     if (LOG.isTraceEnabled()) {
150       LOG.trace(this + " rollback state=" + state);
151     }
152     try {
153       switch (state) {
154         case CREATE_TABLE_POST_OPERATION:
155           break;
156         case CREATE_TABLE_UPDATE_DESC_CACHE:
157           DeleteTableProcedure.deleteTableDescriptorCache(env, getTableName());
158           break;
159         case CREATE_TABLE_ASSIGN_REGIONS:
160           DeleteTableProcedure.deleteAssignmentState(env, getTableName());
161           break;
162         case CREATE_TABLE_ADD_TO_META:
163           DeleteTableProcedure.deleteFromMeta(env, getTableName(), newRegions);
164           break;
165         case CREATE_TABLE_WRITE_FS_LAYOUT:
166           DeleteTableProcedure.deleteFromFs(env, getTableName(), newRegions, false);
167           break;
168         case CREATE_TABLE_PRE_OPERATION:
169           DeleteTableProcedure.deleteTableStates(env, getTableName());
170           // TODO-MAYBE: call the deleteTable coprocessor event?
171           ProcedurePrepareLatch.releaseLatch(syncLatch, this);
172           break;
173         default:
174           throw new UnsupportedOperationException("unhandled state=" + state);
175       }
176     } catch (HBaseException e) {
177       LOG.warn("Failed rollback attempt step=" + state + " table=" + getTableName(), e);
178       throw new IOException(e);
179     } catch (IOException e) {
180       // This will be retried. Unless there is a bug in the code,
181       // this should be just a "temporary error" (e.g. network down)
182       LOG.warn("Failed rollback attempt step=" + state + " table=" + getTableName(), e);
183       throw e;
184     }
185   }
186 
187   @Override
188   protected CreateTableState getState(final int stateId) {
189     return CreateTableState.valueOf(stateId);
190   }
191 
192   @Override
193   protected int getStateId(final CreateTableState state) {
194     return state.getNumber();
195   }
196 
197   @Override
198   protected CreateTableState getInitialState() {
199     return CreateTableState.CREATE_TABLE_PRE_OPERATION;
200   }
201 
202   @Override
203   protected void setNextState(final CreateTableState state) {
204     if (aborted.get()) {
205       setAbortFailure("create-table", "abort requested");
206     } else {
207       super.setNextState(state);
208     }
209   }
210 
211   @Override
212   public TableName getTableName() {
213     return hTableDescriptor.getTableName();
214   }
215 
216   @Override
217   public TableOperationType getTableOperationType() {
218     return TableOperationType.CREATE;
219   }
220 
221   @Override
222   public boolean abort(final MasterProcedureEnv env) {
223     aborted.set(true);
224     return true;
225   }
226 
227   @Override
228   public void toStringClassDetails(StringBuilder sb) {
229     sb.append(getClass().getSimpleName());
230     sb.append(" (table=");
231     sb.append(getTableName());
232     sb.append(") user=");
233     sb.append(user);
234   }
235 
236   @Override
237   public void serializeStateData(final OutputStream stream) throws IOException {
238     super.serializeStateData(stream);
239 
240     MasterProcedureProtos.CreateTableStateData.Builder state =
241       MasterProcedureProtos.CreateTableStateData.newBuilder()
242         .setUserInfo(MasterProcedureUtil.toProtoUserInfo(this.user))
243         .setTableSchema(hTableDescriptor.convert());
244     if (newRegions != null) {
245       for (HRegionInfo hri: newRegions) {
246         state.addRegionInfo(HRegionInfo.convert(hri));
247       }
248     }
249     state.build().writeDelimitedTo(stream);
250   }
251 
252   @Override
253   public void deserializeStateData(final InputStream stream) throws IOException {
254     super.deserializeStateData(stream);
255 
256     MasterProcedureProtos.CreateTableStateData state =
257       MasterProcedureProtos.CreateTableStateData.parseDelimitedFrom(stream);
258     user = MasterProcedureUtil.toUserInfo(state.getUserInfo());
259     hTableDescriptor = HTableDescriptor.convert(state.getTableSchema());
260     if (state.getRegionInfoCount() == 0) {
261       newRegions = null;
262     } else {
263       newRegions = new ArrayList<HRegionInfo>(state.getRegionInfoCount());
264       for (HBaseProtos.RegionInfo hri: state.getRegionInfoList()) {
265         newRegions.add(HRegionInfo.convert(hri));
266       }
267     }
268   }
269 
270   @Override
271   protected boolean acquireLock(final MasterProcedureEnv env) {
272     return env.getProcedureQueue().tryAcquireTableWrite(getTableName(), "create table");
273   }
274 
275   @Override
276   protected void releaseLock(final MasterProcedureEnv env) {
277     env.getProcedureQueue().releaseTableWrite(getTableName());
278   }
279 
280   private boolean prepareCreate(final MasterProcedureEnv env) throws IOException {
281     final TableName tableName = getTableName();
282     if (MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), tableName)) {
283       setFailure("master-create-table", new TableExistsException(getTableName()));
284       return false;
285     }
286     TableStateManager tsm = env.getMasterServices().getAssignmentManager().getTableStateManager();
287     if (tsm.isTableState(tableName, true, ZooKeeperProtos.Table.State.ENABLING,
288           ZooKeeperProtos.Table.State.ENABLED)) {
289       LOG.warn("The table " + tableName + " does not exist in meta but has a znode. " +
290                "run hbck to fix inconsistencies.");
291       setFailure("master-create-table", new TableExistsException(getTableName()));
292       return false;
293     }
294     return true;
295   }
296 
297   private void preCreate(final MasterProcedureEnv env)
298       throws IOException, InterruptedException {
299     if (!getTableName().isSystemTable()) {
300       ProcedureSyncWait.getMasterQuotaManager(env).checkNamespaceTableAndRegionQuota(
301         getTableName(), newRegions.size());
302     }
303     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
304     if (cpHost != null) {
305       final HRegionInfo[] regions = newRegions == null ? null :
306         newRegions.toArray(new HRegionInfo[newRegions.size()]);
307       user.doAs(new PrivilegedExceptionAction<Void>() {
308         @Override
309         public Void run() throws Exception {
310           cpHost.preCreateTableHandler(hTableDescriptor, regions);
311           return null;
312         }
313       });
314     }
315   }
316 
317   private void postCreate(final MasterProcedureEnv env)
318       throws IOException, InterruptedException {
319     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
320     if (cpHost != null) {
321       final HRegionInfo[] regions = (newRegions == null) ? null :
322         newRegions.toArray(new HRegionInfo[newRegions.size()]);
323       user.doAs(new PrivilegedExceptionAction<Void>() {
324         @Override
325         public Void run() throws Exception {
326           cpHost.postCreateTableHandler(hTableDescriptor, regions);
327           return null;
328         }
329       });
330     }
331   }
332 
333   protected interface CreateHdfsRegions {
334     List<HRegionInfo> createHdfsRegions(final MasterProcedureEnv env,
335       final Path tableRootDir, final TableName tableName,
336       final List<HRegionInfo> newRegions) throws IOException;
337   }
338 
339   protected static List<HRegionInfo> createFsLayout(final MasterProcedureEnv env,
340       final HTableDescriptor hTableDescriptor, final List<HRegionInfo> newRegions)
341       throws IOException {
342     return createFsLayout(env, hTableDescriptor, newRegions, new CreateHdfsRegions() {
343       @Override
344       public List<HRegionInfo> createHdfsRegions(final MasterProcedureEnv env,
345           final Path tableRootDir, final TableName tableName,
346           final List<HRegionInfo> newRegions) throws IOException {
347         HRegionInfo[] regions = newRegions != null ?
348           newRegions.toArray(new HRegionInfo[newRegions.size()]) : null;
349         return ModifyRegionUtils.createRegions(env.getMasterConfiguration(),
350             tableRootDir, hTableDescriptor, regions, null);
351       }
352     });
353   }
354 
355   protected static List<HRegionInfo> createFsLayout(final MasterProcedureEnv env,
356       final HTableDescriptor hTableDescriptor, List<HRegionInfo> newRegions,
357       final CreateHdfsRegions hdfsRegionHandler) throws IOException {
358     final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem();
359     final Path tempdir = mfs.getTempDir();
360 
361     // 1. Create Table Descriptor
362     // using a copy of descriptor, table will be created enabling first
363     final Path tempTableDir = FSUtils.getTableDir(tempdir, hTableDescriptor.getTableName());
364     new FSTableDescriptors(env.getMasterConfiguration()).createTableDescriptorForTableDirectory(
365       tempTableDir, hTableDescriptor, false);
366 
367     // 2. Create Regions
368     newRegions = hdfsRegionHandler.createHdfsRegions(env, tempdir,
369       hTableDescriptor.getTableName(), newRegions);
370 
371     // 3. Move Table temp directory to the hbase root location
372     final Path tableDir = FSUtils.getTableDir(mfs.getRootDir(), hTableDescriptor.getTableName());
373     FileSystem fs = mfs.getFileSystem();
374     if (!fs.delete(tableDir, true) && fs.exists(tableDir)) {
375       throw new IOException("Couldn't delete " + tableDir);
376     }
377     if (!fs.rename(tempTableDir, tableDir)) {
378       throw new IOException("Unable to move table from temp=" + tempTableDir +
379         " to hbase root=" + tableDir);
380     }
381     return newRegions;
382   }
383 
384   protected static List<HRegionInfo> addTableToMeta(final MasterProcedureEnv env,
385       final HTableDescriptor hTableDescriptor,
386       final List<HRegionInfo> regions) throws IOException {
387     if (regions != null && regions.size() > 0) {
388       ProcedureSyncWait.waitMetaRegions(env);
389 
390       // Add regions to META
391       addRegionsToMeta(env, hTableDescriptor, regions);
392       // Add replicas if needed
393       List<HRegionInfo> newRegions = addReplicas(env, hTableDescriptor, regions);
394 
395       // Setup replication for region replicas if needed
396       if (hTableDescriptor.getRegionReplication() > 1) {
397         ServerRegionReplicaUtil.setupRegionReplicaReplication(env.getMasterConfiguration());
398       }
399       return newRegions;
400     }
401     return regions;
402   }
403 
404   /**
405    * Create any replicas for the regions (the default replicas that was
406    * already created is passed to the method)
407    * @param hTableDescriptor descriptor to use
408    * @param regions default replicas
409    * @return the combined list of default and non-default replicas
410    */
411   private static List<HRegionInfo> addReplicas(final MasterProcedureEnv env,
412       final HTableDescriptor hTableDescriptor,
413       final List<HRegionInfo> regions) {
414     int numRegionReplicas = hTableDescriptor.getRegionReplication() - 1;
415     if (numRegionReplicas <= 0) {
416       return regions;
417     }
418     List<HRegionInfo> hRegionInfos =
419         new ArrayList<HRegionInfo>((numRegionReplicas+1)*regions.size());
420     for (int i = 0; i < regions.size(); i++) {
421       for (int j = 1; j <= numRegionReplicas; j++) {
422         hRegionInfos.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(i), j));
423       }
424     }
425     hRegionInfos.addAll(regions);
426     return hRegionInfos;
427   }
428 
429   protected static void assignRegions(final MasterProcedureEnv env,
430       final TableName tableName, final List<HRegionInfo> regions)
431       throws HBaseException, IOException {
432     ProcedureSyncWait.waitRegionServers(env);
433 
434     final AssignmentManager assignmentManager = env.getMasterServices().getAssignmentManager();
435 
436     // Mark the table as Enabling
437     assignmentManager.getTableStateManager().setTableState(tableName,
438         ZooKeeperProtos.Table.State.ENABLING);
439 
440     // Trigger immediate assignment of the regions in round-robin fashion
441     ModifyRegionUtils.assignRegions(assignmentManager, regions);
442 
443     // Enable table
444     assignmentManager.getTableStateManager()
445       .setTableState(tableName, ZooKeeperProtos.Table.State.ENABLED);
446   }
447 
448   /**
449    * Add the specified set of regions to the hbase:meta table.
450    */
451   protected static void addRegionsToMeta(final MasterProcedureEnv env,
452       final HTableDescriptor hTableDescriptor,
453       final List<HRegionInfo> regionInfos) throws IOException {
454     MetaTableAccessor.addRegionsToMeta(env.getMasterServices().getConnection(),
455       regionInfos, hTableDescriptor.getRegionReplication());
456   }
457 
458   protected static void updateTableDescCache(final MasterProcedureEnv env,
459       final TableName tableName) throws IOException {
460     env.getMasterServices().getTableDescriptors().get(tableName);
461   }
462 }