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.List;
26  import java.util.concurrent.atomic.AtomicBoolean;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.hbase.HRegionInfo;
31  import org.apache.hadoop.hbase.HTableDescriptor;
32  import org.apache.hadoop.hbase.InvalidFamilyOperationException;
33  import org.apache.hadoop.hbase.TableName;
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  import org.apache.hadoop.hbase.executor.EventType;
36  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
37  import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
38  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
39  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos;
40  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DeleteColumnFamilyState;
41  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
42  import org.apache.hadoop.hbase.util.ByteStringer;
43  import org.apache.hadoop.hbase.util.Bytes;
44  import org.apache.hadoop.security.UserGroupInformation;
45  
46  /**
47   * The procedure to delete a column family from an existing table.
48   */
49  @InterfaceAudience.Private
50  public class DeleteColumnFamilyProcedure
51      extends StateMachineProcedure<MasterProcedureEnv, DeleteColumnFamilyState>
52      implements TableProcedureInterface {
53    private static final Log LOG = LogFactory.getLog(DeleteColumnFamilyProcedure.class);
54  
55    private final AtomicBoolean aborted = new AtomicBoolean(false);
56  
57    private HTableDescriptor unmodifiedHTableDescriptor;
58    private TableName tableName;
59    private byte [] familyName;
60    private UserGroupInformation user;
61  
62    private List<HRegionInfo> regionInfoList;
63    private Boolean traceEnabled;
64  
65    public DeleteColumnFamilyProcedure() {
66      this.unmodifiedHTableDescriptor = null;
67      this.regionInfoList = null;
68      this.traceEnabled = null;
69    }
70  
71    public DeleteColumnFamilyProcedure(
72        final MasterProcedureEnv env,
73        final TableName tableName,
74        final byte[] familyName) throws IOException {
75      this.tableName = tableName;
76      this.familyName = familyName;
77      this.user = env.getRequestUser().getUGI();
78      this.unmodifiedHTableDescriptor = null;
79      this.regionInfoList = null;
80      this.traceEnabled = null;
81    }
82  
83    @Override
84    protected Flow executeFromState(final MasterProcedureEnv env, DeleteColumnFamilyState state) {
85      if (isTraceEnabled()) {
86        LOG.trace(this + " execute state=" + state);
87      }
88  
89      try {
90        switch (state) {
91        case DELETE_COLUMN_FAMILY_PREPARE:
92          prepareDelete(env);
93          setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PRE_OPERATION);
94          break;
95        case DELETE_COLUMN_FAMILY_PRE_OPERATION:
96          preDelete(env, state);
97          setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR);
98          break;
99        case DELETE_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR:
100         updateTableDescriptor(env);
101         setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT);
102         break;
103       case DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT:
104         deleteFromFs(env);
105         setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_POST_OPERATION);
106         break;
107       case DELETE_COLUMN_FAMILY_POST_OPERATION:
108         postDelete(env, state);
109         setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS);
110         break;
111       case DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
112         reOpenAllRegionsIfTableIsOnline(env);
113         return Flow.NO_MORE_STATE;
114       default:
115         throw new UnsupportedOperationException(this + " unhandled state=" + state);
116       }
117     } catch (InterruptedException|IOException e) {
118       if (!isRollbackSupported(state)) {
119         // We reach a state that cannot be rolled back. We just need to keep retry.
120         LOG.warn("Error trying to delete the column family " + getColumnFamilyName()
121           + " from table " + tableName + "(in state=" + state + ")", e);
122       } else {
123         LOG.error("Error trying to delete the column family " + getColumnFamilyName()
124           + " from table " + tableName + "(in state=" + state + ")", e);
125         setFailure("master-delete-column-family", e);
126       }
127     }
128     return Flow.HAS_MORE_STATE;
129   }
130 
131   @Override
132   protected void rollbackState(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
133       throws IOException {
134     if (isTraceEnabled()) {
135       LOG.trace(this + " rollback state=" + state);
136     }
137     try {
138       switch (state) {
139       case DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
140         break; // Nothing to undo.
141       case DELETE_COLUMN_FAMILY_POST_OPERATION:
142         // TODO-MAYBE: call the coprocessor event to undo?
143         break;
144       case DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT:
145         // Once we reach to this state - we could NOT rollback - as it is tricky to undelete
146         // the deleted files. We are not suppose to reach here, throw exception so that we know
147         // there is a code bug to investigate.
148         throw new UnsupportedOperationException(this + " rollback of state=" + state
149             + " is unsupported.");
150       case DELETE_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR:
151         restoreTableDescriptor(env);
152         break;
153       case DELETE_COLUMN_FAMILY_PRE_OPERATION:
154         // TODO-MAYBE: call the coprocessor event to undo?
155         break;
156       case DELETE_COLUMN_FAMILY_PREPARE:
157         break; // nothing to do
158       default:
159         throw new UnsupportedOperationException(this + " unhandled state=" + state);
160       }
161     } catch (IOException e) {
162       // This will be retried. Unless there is a bug in the code,
163       // this should be just a "temporary error" (e.g. network down)
164       LOG.warn("Failed rollback attempt step " + state + " for deleting the column family"
165           + getColumnFamilyName() + " to the table " + tableName, e);
166       throw e;
167     }
168   }
169 
170   @Override
171   protected DeleteColumnFamilyState getState(final int stateId) {
172     return DeleteColumnFamilyState.valueOf(stateId);
173   }
174 
175   @Override
176   protected int getStateId(final DeleteColumnFamilyState state) {
177     return state.getNumber();
178   }
179 
180   @Override
181   protected DeleteColumnFamilyState getInitialState() {
182     return DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PREPARE;
183   }
184 
185   @Override
186   protected void setNextState(DeleteColumnFamilyState state) {
187     if (aborted.get() && isRollbackSupported(state)) {
188       setAbortFailure("delete-columnfamily", "abort requested");
189     } else {
190       super.setNextState(state);
191     }
192   }
193 
194   @Override
195   public boolean abort(final MasterProcedureEnv env) {
196     aborted.set(true);
197     return true;
198   }
199 
200   @Override
201   protected boolean acquireLock(final MasterProcedureEnv env) {
202     if (!env.isInitialized()) return false;
203     return env.getProcedureQueue().tryAcquireTableWrite(
204       tableName,
205       EventType.C_M_DELETE_FAMILY.toString());
206   }
207 
208   @Override
209   protected void releaseLock(final MasterProcedureEnv env) {
210     env.getProcedureQueue().releaseTableWrite(tableName);
211   }
212 
213   @Override
214   public void serializeStateData(final OutputStream stream) throws IOException {
215     super.serializeStateData(stream);
216 
217     MasterProcedureProtos.DeleteColumnFamilyStateData.Builder deleteCFMsg =
218         MasterProcedureProtos.DeleteColumnFamilyStateData.newBuilder()
219             .setUserInfo(MasterProcedureUtil.toProtoUserInfo(user))
220             .setTableName(ProtobufUtil.toProtoTableName(tableName))
221             .setColumnfamilyName(ByteStringer.wrap(familyName));
222     if (unmodifiedHTableDescriptor != null) {
223       deleteCFMsg.setUnmodifiedTableSchema(unmodifiedHTableDescriptor.convert());
224     }
225 
226     deleteCFMsg.build().writeDelimitedTo(stream);
227   }
228 
229   @Override
230   public void deserializeStateData(final InputStream stream) throws IOException {
231     super.deserializeStateData(stream);
232     MasterProcedureProtos.DeleteColumnFamilyStateData deleteCFMsg =
233         MasterProcedureProtos.DeleteColumnFamilyStateData.parseDelimitedFrom(stream);
234     user = MasterProcedureUtil.toUserInfo(deleteCFMsg.getUserInfo());
235     tableName = ProtobufUtil.toTableName(deleteCFMsg.getTableName());
236     familyName = deleteCFMsg.getColumnfamilyName().toByteArray();
237 
238     if (deleteCFMsg.hasUnmodifiedTableSchema()) {
239       unmodifiedHTableDescriptor = HTableDescriptor.convert(deleteCFMsg.getUnmodifiedTableSchema());
240     }
241   }
242 
243   @Override
244   public void toStringClassDetails(StringBuilder sb) {
245     sb.append(getClass().getSimpleName());
246     sb.append(" (table=");
247     sb.append(tableName);
248     sb.append(", columnfamily=");
249     if (familyName != null) {
250       sb.append(getColumnFamilyName());
251     } else {
252       sb.append("Unknown");
253     }
254     sb.append(") user=");
255     sb.append(user);
256   }
257 
258   @Override
259   public TableName getTableName() {
260     return tableName;
261   }
262 
263   @Override
264   public TableOperationType getTableOperationType() {
265     return TableOperationType.EDIT;
266   }
267 
268   /**
269    * Action before any real action of deleting column family.
270    * @param env MasterProcedureEnv
271    * @throws IOException
272    */
273   private void prepareDelete(final MasterProcedureEnv env) throws IOException {
274     // Checks whether the table is allowed to be modified.
275     MasterDDLOperationHelper.checkTableModifiable(env, tableName);
276 
277     // In order to update the descriptor, we need to retrieve the old descriptor for comparison.
278     unmodifiedHTableDescriptor = env.getMasterServices().getTableDescriptors().get(tableName);
279     if (unmodifiedHTableDescriptor == null) {
280       throw new IOException("HTableDescriptor missing for " + tableName);
281     }
282     if (!unmodifiedHTableDescriptor.hasFamily(familyName)) {
283       throw new InvalidFamilyOperationException("Family '" + getColumnFamilyName()
284           + "' does not exist, so it cannot be deleted");
285     }
286   }
287 
288   /**
289    * Action before deleting column family.
290    * @param env MasterProcedureEnv
291    * @param state the procedure state
292    * @throws IOException
293    * @throws InterruptedException
294    */
295   private void preDelete(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
296       throws IOException, InterruptedException {
297     runCoprocessorAction(env, state);
298   }
299 
300   /**
301    * Remove the column family from the file system and update the table descriptor
302    */
303   private void updateTableDescriptor(final MasterProcedureEnv env) throws IOException {
304     // Update table descriptor
305     LOG.info("DeleteColumn. Table = " + tableName + " family = " + getColumnFamilyName());
306 
307     HTableDescriptor htd = env.getMasterServices().getTableDescriptors().get(tableName);
308 
309     if (!htd.hasFamily(familyName)) {
310       // It is possible to reach this situation, as we could already delete the column family
311       // from table descriptor, but the master failover happens before we complete this state.
312       // We should be able to handle running this function multiple times without causing problem.
313       return;
314     }
315 
316     htd.removeFamily(familyName);
317     env.getMasterServices().getTableDescriptors().add(htd);
318   }
319 
320   /**
321    * Restore back to the old descriptor
322    * @param env MasterProcedureEnv
323    * @throws IOException
324    **/
325   private void restoreTableDescriptor(final MasterProcedureEnv env) throws IOException {
326     env.getMasterServices().getTableDescriptors().add(unmodifiedHTableDescriptor);
327 
328     // Make sure regions are opened after table descriptor is updated.
329     reOpenAllRegionsIfTableIsOnline(env);
330   }
331 
332   /**
333    * Remove the column family from the file system
334    **/
335   private void deleteFromFs(final MasterProcedureEnv env) throws IOException {
336     MasterDDLOperationHelper.deleteColumnFamilyFromFileSystem(env, tableName,
337       getRegionInfoList(env), familyName);
338   }
339 
340   /**
341    * Action after deleting column family.
342    * @param env MasterProcedureEnv
343    * @param state the procedure state
344    * @throws IOException
345    * @throws InterruptedException
346    */
347   private void postDelete(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
348       throws IOException, InterruptedException {
349     runCoprocessorAction(env, state);
350   }
351 
352   /**
353    * Last action from the procedure - executed when online schema change is supported.
354    * @param env MasterProcedureEnv
355    * @throws IOException
356    */
357   private void reOpenAllRegionsIfTableIsOnline(final MasterProcedureEnv env) throws IOException {
358     // This operation only run when the table is enabled.
359     if (!env.getMasterServices().getAssignmentManager().getTableStateManager()
360         .isTableState(getTableName(), ZooKeeperProtos.Table.State.ENABLED)) {
361       return;
362     }
363 
364     if (MasterDDLOperationHelper.reOpenAllRegions(env, getTableName(), getRegionInfoList(env))) {
365       LOG.info("Completed delete column family operation on table " + getTableName());
366     } else {
367       LOG.warn("Error on reopening the regions on table " + getTableName());
368     }
369   }
370 
371   /**
372    * The procedure could be restarted from a different machine. If the variable is null, we need to
373    * retrieve it.
374    * @return traceEnabled
375    */
376   private Boolean isTraceEnabled() {
377     if (traceEnabled == null) {
378       traceEnabled = LOG.isTraceEnabled();
379     }
380     return traceEnabled;
381   }
382 
383   private String getColumnFamilyName() {
384     return Bytes.toString(familyName);
385   }
386 
387   /**
388    * Coprocessor Action.
389    * @param env MasterProcedureEnv
390    * @param state the procedure state
391    * @throws IOException
392    * @throws InterruptedException
393    */
394   private void runCoprocessorAction(final MasterProcedureEnv env,
395       final DeleteColumnFamilyState state) throws IOException, InterruptedException {
396     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
397     if (cpHost != null) {
398       user.doAs(new PrivilegedExceptionAction<Void>() {
399         @Override
400         public Void run() throws Exception {
401           switch (state) {
402           case DELETE_COLUMN_FAMILY_PRE_OPERATION:
403             cpHost.preDeleteColumnHandler(tableName, familyName);
404             break;
405           case DELETE_COLUMN_FAMILY_POST_OPERATION:
406             cpHost.postDeleteColumnHandler(tableName, familyName);
407             break;
408           default:
409             throw new UnsupportedOperationException(this + " unhandled state=" + state);
410           }
411           return null;
412         }
413       });
414     }
415   }
416 
417   /*
418    * Check whether we are in the state that can be rollback
419    */
420   private boolean isRollbackSupported(final DeleteColumnFamilyState state) {
421     switch (state) {
422     case DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
423     case DELETE_COLUMN_FAMILY_POST_OPERATION:
424     case DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT:
425         // It is not safe to rollback if we reach to these states.
426         return false;
427       default:
428         break;
429     }
430     return true;
431   }
432 
433   private List<HRegionInfo> getRegionInfoList(final MasterProcedureEnv env) throws IOException {
434     if (regionInfoList == null) {
435       regionInfoList = ProcedureSyncWait.getRegionsFromMeta(env, getTableName());
436     }
437     return regionInfoList;
438   }
439 }