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