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.DoNotRetryIOException;
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.TableExistsException;
38  import org.apache.hadoop.hbase.TableName;
39  import org.apache.hadoop.hbase.TableStateManager;
40  import org.apache.hadoop.hbase.classification.InterfaceAudience;
41  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
42  import org.apache.hadoop.hbase.exceptions.HBaseException;
43  import org.apache.hadoop.hbase.master.AssignmentManager;
44  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
45  import org.apache.hadoop.hbase.master.MasterFileSystem;
46  import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
47  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
48  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos;
49  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.CreateTableState;
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  import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
55  import org.apache.hadoop.security.UserGroupInformation;
56  
57  import com.google.common.collect.Lists;
58  
59  @InterfaceAudience.Private
60  public class CreateTableProcedure
61      extends StateMachineProcedure<MasterProcedureEnv, CreateTableState>
62      implements TableProcedureInterface {
63    private static final Log LOG = LogFactory.getLog(CreateTableProcedure.class);
64  
65    private final AtomicBoolean aborted = new AtomicBoolean(false);
66  
67    // used for compatibility with old clients
68    private final ProcedurePrepareLatch syncLatch;
69  
70    private HTableDescriptor hTableDescriptor;
71    private List<HRegionInfo> newRegions;
72    private UserGroupInformation user;
73  
74    public CreateTableProcedure() {
75      // Required by the Procedure framework to create the procedure on replay
76      syncLatch = null;
77    }
78  
79    public CreateTableProcedure(final MasterProcedureEnv env,
80        final HTableDescriptor hTableDescriptor, final HRegionInfo[] newRegions) {
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      this.hTableDescriptor = hTableDescriptor;
88      this.newRegions = newRegions != null ? Lists.newArrayList(newRegions) : null;
89      this.user = env.getRequestUser().getUGI();
90      this.setOwner(this.user.getShortUserName());
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        throws InterruptedException {
100     if (LOG.isTraceEnabled()) {
101       LOG.trace(this + " execute state=" + state);
102     }
103     try {
104       switch (state) {
105         case CREATE_TABLE_PRE_OPERATION:
106           // Verify if we can create the table
107           boolean exists = !prepareCreate(env);
108           ProcedurePrepareLatch.releaseLatch(syncLatch, this);
109 
110           if (exists) {
111             assert isFailed() : "the delete should have an exception here";
112             return Flow.NO_MORE_STATE;
113           }
114 
115           preCreate(env);
116           setNextState(CreateTableState.CREATE_TABLE_WRITE_FS_LAYOUT);
117           break;
118         case CREATE_TABLE_WRITE_FS_LAYOUT:
119           newRegions = createFsLayout(env, hTableDescriptor, newRegions);
120           setNextState(CreateTableState.CREATE_TABLE_ADD_TO_META);
121           break;
122         case CREATE_TABLE_ADD_TO_META:
123           newRegions = addTableToMeta(env, hTableDescriptor, newRegions);
124           setNextState(CreateTableState.CREATE_TABLE_ASSIGN_REGIONS);
125           break;
126         case CREATE_TABLE_ASSIGN_REGIONS:
127           assignRegions(env, getTableName(), newRegions);
128           setNextState(CreateTableState.CREATE_TABLE_UPDATE_DESC_CACHE);
129           break;
130         case CREATE_TABLE_UPDATE_DESC_CACHE:
131           updateTableDescCache(env, getTableName());
132           setNextState(CreateTableState.CREATE_TABLE_POST_OPERATION);
133           break;
134         case CREATE_TABLE_POST_OPERATION:
135           postCreate(env);
136           return Flow.NO_MORE_STATE;
137         default:
138           throw new UnsupportedOperationException("unhandled state=" + state);
139       }
140     } catch (HBaseException|IOException e) {
141       LOG.error("Error trying to create table=" + getTableName() + " state=" + state, e);
142       setFailure("master-create-table", e);
143     }
144     return Flow.HAS_MORE_STATE;
145   }
146 
147   @Override
148   protected void rollbackState(final MasterProcedureEnv env, final CreateTableState state)
149       throws IOException {
150     if (LOG.isTraceEnabled()) {
151       LOG.trace(this + " rollback state=" + state);
152     }
153     try {
154       switch (state) {
155         case CREATE_TABLE_POST_OPERATION:
156           break;
157         case CREATE_TABLE_UPDATE_DESC_CACHE:
158           DeleteTableProcedure.deleteTableDescriptorCache(env, getTableName());
159           break;
160         case CREATE_TABLE_ASSIGN_REGIONS:
161           DeleteTableProcedure.deleteAssignmentState(env, getTableName());
162           break;
163         case CREATE_TABLE_ADD_TO_META:
164           DeleteTableProcedure.deleteFromMeta(env, getTableName(), newRegions);
165           break;
166         case CREATE_TABLE_WRITE_FS_LAYOUT:
167           DeleteTableProcedure.deleteFromFs(env, getTableName(), newRegions, false);
168           break;
169         case CREATE_TABLE_PRE_OPERATION:
170           DeleteTableProcedure.deleteTableStates(env, getTableName());
171           // TODO-MAYBE: call the deleteTable coprocessor event?
172           final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
173           if (cpHost != null) {
174             cpHost.postDeleteTable(getTableName());
175           }
176           ProcedurePrepareLatch.releaseLatch(syncLatch, this);
177           break;
178         default:
179           throw new UnsupportedOperationException("unhandled state=" + state);
180       }
181     } catch (HBaseException e) {
182       LOG.warn("Failed rollback attempt step=" + state + " table=" + getTableName(), e);
183       throw new IOException(e);
184     } catch (IOException e) {
185       // This will be retried. Unless there is a bug in the code,
186       // this should be just a "temporary error" (e.g. network down)
187       LOG.warn("Failed rollback attempt step=" + state + " table=" + getTableName(), e);
188       throw e;
189     }
190   }
191 
192   @Override
193   protected CreateTableState getState(final int stateId) {
194     return CreateTableState.valueOf(stateId);
195   }
196 
197   @Override
198   protected int getStateId(final CreateTableState state) {
199     return state.getNumber();
200   }
201 
202   @Override
203   protected CreateTableState getInitialState() {
204     return CreateTableState.CREATE_TABLE_PRE_OPERATION;
205   }
206 
207   @Override
208   protected void setNextState(final CreateTableState state) {
209     if (aborted.get()) {
210       setAbortFailure("create-table", "abort requested");
211     } else {
212       super.setNextState(state);
213     }
214   }
215 
216   @Override
217   public TableName getTableName() {
218     return hTableDescriptor.getTableName();
219   }
220 
221   @Override
222   public TableOperationType getTableOperationType() {
223     return TableOperationType.CREATE;
224   }
225 
226   @Override
227   public boolean abort(final MasterProcedureEnv env) {
228     aborted.set(true);
229     return true;
230   }
231 
232   @Override
233   public void toStringClassDetails(StringBuilder sb) {
234     sb.append(getClass().getSimpleName());
235     sb.append(" (table=");
236     sb.append(getTableName());
237     sb.append(")");
238   }
239 
240   @Override
241   public void serializeStateData(final OutputStream stream) throws IOException {
242     super.serializeStateData(stream);
243 
244     MasterProcedureProtos.CreateTableStateData.Builder state =
245       MasterProcedureProtos.CreateTableStateData.newBuilder()
246         .setUserInfo(MasterProcedureUtil.toProtoUserInfo(this.user))
247         .setTableSchema(hTableDescriptor.convert());
248     if (newRegions != null) {
249       for (HRegionInfo hri: newRegions) {
250         state.addRegionInfo(HRegionInfo.convert(hri));
251       }
252     }
253     state.build().writeDelimitedTo(stream);
254   }
255 
256   @Override
257   public void deserializeStateData(final InputStream stream) throws IOException {
258     super.deserializeStateData(stream);
259 
260     MasterProcedureProtos.CreateTableStateData state =
261       MasterProcedureProtos.CreateTableStateData.parseDelimitedFrom(stream);
262     user = MasterProcedureUtil.toUserInfo(state.getUserInfo());
263     hTableDescriptor = HTableDescriptor.convert(state.getTableSchema());
264     if (state.getRegionInfoCount() == 0) {
265       newRegions = null;
266     } else {
267       newRegions = new ArrayList<HRegionInfo>(state.getRegionInfoCount());
268       for (HBaseProtos.RegionInfo hri: state.getRegionInfoList()) {
269         newRegions.add(HRegionInfo.convert(hri));
270       }
271     }
272   }
273 
274   @Override
275   protected boolean acquireLock(final MasterProcedureEnv env) {
276     if (!getTableName().isSystemTable() && env.waitInitialized(this)) {
277       return false;
278     }
279     return env.getProcedureQueue().tryAcquireTableExclusiveLock(this, getTableName());
280   }
281 
282   @Override
283   protected void releaseLock(final MasterProcedureEnv env) {
284     env.getProcedureQueue().releaseTableExclusiveLock(this, getTableName());
285   }
286 
287   private boolean prepareCreate(final MasterProcedureEnv env) throws IOException {
288     final TableName tableName = getTableName();
289     if (MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), tableName)) {
290       setFailure("master-create-table", new TableExistsException(getTableName()));
291       return false;
292     }
293     // During master initialization, the ZK state could be inconsistent from failed DDL
294     // in the past. If we fail here, it would prevent master to start.  We should force
295     // setting the system table state regardless the table state.
296     boolean skipTableStateCheck =
297         !(env.getMasterServices().isInitialized()) && tableName.isSystemTable();
298     if (!skipTableStateCheck) {
299       TableStateManager tsm = env.getMasterServices().getAssignmentManager().getTableStateManager();
300       if (tsm.isTableState(tableName, true, ZooKeeperProtos.Table.State.ENABLING,
301           ZooKeeperProtos.Table.State.ENABLED)) {
302         LOG.warn("The table " + tableName + " does not exist in meta but has a znode. " +
303                "run hbck to fix inconsistencies.");
304         setFailure("master-create-table", new TableExistsException(getTableName()));
305         return false;
306       }
307     }
308 
309     // check that we have at least 1 CF
310     if (hTableDescriptor.getColumnFamilies().length == 0) {
311       setFailure("master-create-table", new DoNotRetryIOException("Table " +
312           getTableName().toString() + " should have at least one column family."));
313       return false;
314     }
315 
316     return true;
317   }
318 
319   private void preCreate(final MasterProcedureEnv env)
320       throws IOException, InterruptedException {
321     if (!getTableName().isSystemTable()) {
322       ProcedureSyncWait.getMasterQuotaManager(env)
323         .checkNamespaceTableAndRegionQuota(getTableName(), newRegions.size());
324     }
325 
326     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
327     if (cpHost != null) {
328       final HRegionInfo[] regions = newRegions == null ? null :
329         newRegions.toArray(new HRegionInfo[newRegions.size()]);
330       user.doAs(new PrivilegedExceptionAction<Void>() {
331         @Override
332         public Void run() throws Exception {
333           cpHost.preCreateTableHandler(hTableDescriptor, regions);
334           return null;
335         }
336       });
337     }
338   }
339 
340   private void postCreate(final MasterProcedureEnv env)
341       throws IOException, InterruptedException {
342     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
343     if (cpHost != null) {
344       final HRegionInfo[] regions = (newRegions == null) ? null :
345         newRegions.toArray(new HRegionInfo[newRegions.size()]);
346       user.doAs(new PrivilegedExceptionAction<Void>() {
347         @Override
348         public Void run() throws Exception {
349           cpHost.postCreateTableHandler(hTableDescriptor, regions);
350           return null;
351         }
352       });
353     }
354   }
355 
356   protected interface CreateHdfsRegions {
357     List<HRegionInfo> createHdfsRegions(final MasterProcedureEnv env,
358       final Path tableRootDir, final TableName tableName,
359       final List<HRegionInfo> newRegions) throws IOException;
360   }
361 
362   protected static List<HRegionInfo> createFsLayout(final MasterProcedureEnv env,
363       final HTableDescriptor hTableDescriptor, final List<HRegionInfo> newRegions)
364       throws IOException {
365     return createFsLayout(env, hTableDescriptor, newRegions, new CreateHdfsRegions() {
366       @Override
367       public List<HRegionInfo> createHdfsRegions(final MasterProcedureEnv env,
368           final Path tableRootDir, final TableName tableName,
369           final List<HRegionInfo> newRegions) throws IOException {
370         HRegionInfo[] regions = newRegions != null ?
371           newRegions.toArray(new HRegionInfo[newRegions.size()]) : null;
372         return ModifyRegionUtils.createRegions(env.getMasterConfiguration(),
373             tableRootDir, hTableDescriptor, regions, null);
374       }
375     });
376   }
377 
378   protected static List<HRegionInfo> createFsLayout(final MasterProcedureEnv env,
379       final HTableDescriptor hTableDescriptor, List<HRegionInfo> newRegions,
380       final CreateHdfsRegions hdfsRegionHandler) throws IOException {
381     final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem();
382     final Path tempdir = mfs.getTempDir();
383 
384     // 1. Create Table Descriptor
385     // using a copy of descriptor, table will be created enabling first
386     final Path tempTableDir = FSUtils.getTableDir(tempdir, hTableDescriptor.getTableName());
387     new FSTableDescriptors(env.getMasterConfiguration()).createTableDescriptorForTableDirectory(
388       tempTableDir, hTableDescriptor, false);
389 
390     // 2. Create Regions
391     newRegions = hdfsRegionHandler.createHdfsRegions(env, tempdir,
392       hTableDescriptor.getTableName(), newRegions);
393 
394     // 3. Move Table temp directory to the hbase root location
395     final Path tableDir = FSUtils.getTableDir(mfs.getRootDir(), hTableDescriptor.getTableName());
396     FileSystem fs = mfs.getFileSystem();
397     if (!fs.delete(tableDir, true) && fs.exists(tableDir)) {
398       throw new IOException("Couldn't delete " + tableDir);
399     }
400     if (!fs.rename(tempTableDir, tableDir)) {
401       throw new IOException("Unable to move table from temp=" + tempTableDir +
402         " to hbase root=" + tableDir);
403     }
404     return newRegions;
405   }
406 
407   protected static List<HRegionInfo> addTableToMeta(final MasterProcedureEnv env,
408       final HTableDescriptor hTableDescriptor,
409       final List<HRegionInfo> regions) throws IOException {
410     if (regions != null && regions.size() > 0) {
411       ProcedureSyncWait.waitMetaRegions(env);
412 
413       // Add regions to META
414       addRegionsToMeta(env, hTableDescriptor, regions);
415       // Add replicas if needed
416       List<HRegionInfo> newRegions = addReplicas(env, hTableDescriptor, regions);
417 
418       // Setup replication for region replicas if needed
419       if (hTableDescriptor.getRegionReplication() > 1) {
420         ServerRegionReplicaUtil.setupRegionReplicaReplication(env.getMasterConfiguration());
421       }
422       return newRegions;
423     }
424     return regions;
425   }
426 
427   /**
428    * Create any replicas for the regions (the default replicas that was
429    * already created is passed to the method)
430    * @param hTableDescriptor descriptor to use
431    * @param regions default replicas
432    * @return the combined list of default and non-default replicas
433    */
434   private static List<HRegionInfo> addReplicas(final MasterProcedureEnv env,
435       final HTableDescriptor hTableDescriptor,
436       final List<HRegionInfo> regions) {
437     int numRegionReplicas = hTableDescriptor.getRegionReplication() - 1;
438     if (numRegionReplicas <= 0) {
439       return regions;
440     }
441     List<HRegionInfo> hRegionInfos =
442         new ArrayList<HRegionInfo>((numRegionReplicas+1)*regions.size());
443     for (int i = 0; i < regions.size(); i++) {
444       for (int j = 1; j <= numRegionReplicas; j++) {
445         hRegionInfos.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(i), j));
446       }
447     }
448     hRegionInfos.addAll(regions);
449     return hRegionInfos;
450   }
451 
452   protected static void assignRegions(final MasterProcedureEnv env,
453       final TableName tableName, final List<HRegionInfo> regions)
454       throws HBaseException, IOException {
455     ProcedureSyncWait.waitRegionServers(env);
456 
457     final AssignmentManager assignmentManager = env.getMasterServices().getAssignmentManager();
458 
459     // Mark the table as Enabling
460     assignmentManager.getTableStateManager().setTableState(tableName,
461         ZooKeeperProtos.Table.State.ENABLING);
462 
463     // Trigger immediate assignment of the regions in round-robin fashion
464     ModifyRegionUtils.assignRegions(assignmentManager, regions);
465 
466     // Enable table
467     assignmentManager.getTableStateManager()
468       .setTableState(tableName, ZooKeeperProtos.Table.State.ENABLED);
469   }
470 
471   /**
472    * Add the specified set of regions to the hbase:meta table.
473    */
474   protected static void addRegionsToMeta(final MasterProcedureEnv env,
475       final HTableDescriptor hTableDescriptor,
476       final List<HRegionInfo> regionInfos) throws IOException {
477     MetaTableAccessor.addRegionsToMeta(env.getMasterServices().getConnection(),
478       regionInfos, hTableDescriptor.getRegionReplication());
479   }
480 
481   protected static void updateTableDescCache(final MasterProcedureEnv env,
482       final TableName tableName) throws IOException {
483     env.getMasterServices().getTableDescriptors().get(tableName);
484   }
485 
486   @Override
487   protected boolean shouldWaitClientAck(MasterProcedureEnv env) {
488     // system tables are created on bootstrap internally by the system
489     // the client does not know about this procedures.
490     return !getTableName().isSystemTable();
491   }
492 }