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.HashSet;
26  import java.util.List;
27  import java.util.Set;
28  import java.util.concurrent.atomic.AtomicBoolean;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.hbase.HConstants;
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.TableName;
37  import org.apache.hadoop.hbase.TableNotDisabledException;
38  import org.apache.hadoop.hbase.TableNotFoundException;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.client.Connection;
41  import org.apache.hadoop.hbase.client.Result;
42  import org.apache.hadoop.hbase.client.ResultScanner;
43  import org.apache.hadoop.hbase.client.Scan;
44  import org.apache.hadoop.hbase.client.Table;
45  import org.apache.hadoop.hbase.executor.EventType;
46  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
47  import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
48  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos;
49  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.ModifyTableState;
50  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
51  import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
52  import org.apache.hadoop.security.UserGroupInformation;
53  
54  @InterfaceAudience.Private
55  public class ModifyTableProcedure
56      extends StateMachineProcedure<MasterProcedureEnv, ModifyTableState>
57      implements TableProcedureInterface {
58    private static final Log LOG = LogFactory.getLog(ModifyTableProcedure.class);
59  
60    private final AtomicBoolean aborted = new AtomicBoolean(false);
61  
62    private HTableDescriptor unmodifiedHTableDescriptor = null;
63    private HTableDescriptor modifiedHTableDescriptor;
64    private UserGroupInformation user;
65    private boolean deleteColumnFamilyInModify;
66  
67    private List<HRegionInfo> regionInfoList;
68    private Boolean traceEnabled = null;
69  
70    public ModifyTableProcedure() {
71      initilize();
72    }
73  
74    public ModifyTableProcedure(
75      final MasterProcedureEnv env,
76      final HTableDescriptor htd) throws IOException {
77      initilize();
78      this.modifiedHTableDescriptor = htd;
79      this.user = env.getRequestUser().getUGI();
80    }
81  
82    private void initilize() {
83      this.unmodifiedHTableDescriptor = null;
84      this.regionInfoList = null;
85      this.traceEnabled = null;
86      this.deleteColumnFamilyInModify = false;
87    }
88  
89    @Override
90    protected Flow executeFromState(final MasterProcedureEnv env, final ModifyTableState state) {
91      if (isTraceEnabled()) {
92        LOG.trace(this + " execute state=" + state);
93      }
94  
95      try {
96        switch (state) {
97        case MODIFY_TABLE_PREPARE:
98          prepareModify(env);
99          setNextState(ModifyTableState.MODIFY_TABLE_PRE_OPERATION);
100         break;
101       case MODIFY_TABLE_PRE_OPERATION:
102         preModify(env, state);
103         setNextState(ModifyTableState.MODIFY_TABLE_UPDATE_TABLE_DESCRIPTOR);
104         break;
105       case MODIFY_TABLE_UPDATE_TABLE_DESCRIPTOR:
106         updateTableDescriptor(env);
107         setNextState(ModifyTableState.MODIFY_TABLE_REMOVE_REPLICA_COLUMN);
108         break;
109       case MODIFY_TABLE_REMOVE_REPLICA_COLUMN:
110         updateReplicaColumnsIfNeeded(env, unmodifiedHTableDescriptor, modifiedHTableDescriptor);
111         if (deleteColumnFamilyInModify) {
112           setNextState(ModifyTableState.MODIFY_TABLE_DELETE_FS_LAYOUT);
113         } else {
114           setNextState(ModifyTableState.MODIFY_TABLE_POST_OPERATION);
115         }
116         break;
117       case MODIFY_TABLE_DELETE_FS_LAYOUT:
118         deleteFromFs(env, unmodifiedHTableDescriptor, modifiedHTableDescriptor);
119         setNextState(ModifyTableState.MODIFY_TABLE_POST_OPERATION);
120         break;
121       case MODIFY_TABLE_POST_OPERATION:
122         postModify(env, state);
123         setNextState(ModifyTableState.MODIFY_TABLE_REOPEN_ALL_REGIONS);
124         break;
125       case MODIFY_TABLE_REOPEN_ALL_REGIONS:
126         reOpenAllRegionsIfTableIsOnline(env);
127         return Flow.NO_MORE_STATE;
128       default:
129         throw new UnsupportedOperationException("unhandled state=" + state);
130       }
131     } catch (InterruptedException|IOException e) {
132       if (!isRollbackSupported(state)) {
133         // We reach a state that cannot be rolled back. We just need to keep retry.
134         LOG.warn("Error trying to modify table=" + getTableName() + " state=" + state, e);
135       } else {
136         LOG.error("Error trying to modify table=" + getTableName() + " state=" + state, e);
137         setFailure("master-modify-table", e);
138       }
139     }
140     return Flow.HAS_MORE_STATE;
141   }
142 
143   @Override
144   protected void rollbackState(final MasterProcedureEnv env, final ModifyTableState state)
145       throws IOException {
146     if (isTraceEnabled()) {
147       LOG.trace(this + " rollback state=" + state);
148     }
149     try {
150       switch (state) {
151       case MODIFY_TABLE_REOPEN_ALL_REGIONS:
152         break; // Nothing to undo.
153       case MODIFY_TABLE_POST_OPERATION:
154         // TODO-MAYBE: call the coprocessor event to un-modify?
155         break;
156       case MODIFY_TABLE_DELETE_FS_LAYOUT:
157         // Once we reach to this state - we could NOT rollback - as it is tricky to undelete
158         // the deleted files. We are not suppose to reach here, throw exception so that we know
159         // there is a code bug to investigate.
160         assert deleteColumnFamilyInModify;
161         throw new UnsupportedOperationException(this + " rollback of state=" + state
162             + " is unsupported.");
163       case MODIFY_TABLE_REMOVE_REPLICA_COLUMN:
164         // Undo the replica column update.
165         updateReplicaColumnsIfNeeded(env, modifiedHTableDescriptor, unmodifiedHTableDescriptor);
166         break;
167       case MODIFY_TABLE_UPDATE_TABLE_DESCRIPTOR:
168         restoreTableDescriptor(env);
169         break;
170       case MODIFY_TABLE_PRE_OPERATION:
171         // TODO-MAYBE: call the coprocessor event to un-modify?
172         break;
173       case MODIFY_TABLE_PREPARE:
174         break; // Nothing to undo.
175       default:
176         throw new UnsupportedOperationException("unhandled state=" + state);
177       }
178     } catch (IOException e) {
179       LOG.warn("Fail trying to rollback modify table=" + getTableName() + " state=" + state, e);
180       throw e;
181     }
182   }
183 
184   @Override
185   protected ModifyTableState getState(final int stateId) {
186     return ModifyTableState.valueOf(stateId);
187   }
188 
189   @Override
190   protected int getStateId(final ModifyTableState state) {
191     return state.getNumber();
192   }
193 
194   @Override
195   protected ModifyTableState getInitialState() {
196     return ModifyTableState.MODIFY_TABLE_PREPARE;
197   }
198 
199   @Override
200   protected void setNextState(final ModifyTableState state) {
201     if (aborted.get() && isRollbackSupported(state)) {
202       setAbortFailure("modify-table", "abort requested");
203     } else {
204       super.setNextState(state);
205     }
206   }
207 
208   @Override
209   public boolean abort(final MasterProcedureEnv env) {
210     aborted.set(true);
211     return true;
212   }
213 
214   @Override
215   protected boolean acquireLock(final MasterProcedureEnv env) {
216     if (!env.isInitialized()) return false;
217     return env.getProcedureQueue().tryAcquireTableWrite(
218       getTableName(),
219       EventType.C_M_MODIFY_TABLE.toString());
220   }
221 
222   @Override
223   protected void releaseLock(final MasterProcedureEnv env) {
224     env.getProcedureQueue().releaseTableWrite(getTableName());
225   }
226 
227   @Override
228   public void serializeStateData(final OutputStream stream) throws IOException {
229     super.serializeStateData(stream);
230 
231     MasterProcedureProtos.ModifyTableStateData.Builder modifyTableMsg =
232         MasterProcedureProtos.ModifyTableStateData.newBuilder()
233             .setUserInfo(MasterProcedureUtil.toProtoUserInfo(user))
234             .setModifiedTableSchema(modifiedHTableDescriptor.convert())
235             .setDeleteColumnFamilyInModify(deleteColumnFamilyInModify);
236 
237     if (unmodifiedHTableDescriptor != null) {
238       modifyTableMsg.setUnmodifiedTableSchema(unmodifiedHTableDescriptor.convert());
239     }
240 
241     modifyTableMsg.build().writeDelimitedTo(stream);
242   }
243 
244   @Override
245   public void deserializeStateData(final InputStream stream) throws IOException {
246     super.deserializeStateData(stream);
247 
248     MasterProcedureProtos.ModifyTableStateData modifyTableMsg =
249         MasterProcedureProtos.ModifyTableStateData.parseDelimitedFrom(stream);
250     user = MasterProcedureUtil.toUserInfo(modifyTableMsg.getUserInfo());
251     modifiedHTableDescriptor = HTableDescriptor.convert(modifyTableMsg.getModifiedTableSchema());
252     deleteColumnFamilyInModify = modifyTableMsg.getDeleteColumnFamilyInModify();
253 
254     if (modifyTableMsg.hasUnmodifiedTableSchema()) {
255       unmodifiedHTableDescriptor =
256           HTableDescriptor.convert(modifyTableMsg.getUnmodifiedTableSchema());
257     }
258   }
259 
260   @Override
261   public void toStringClassDetails(StringBuilder sb) {
262     sb.append(getClass().getSimpleName());
263     sb.append(" (table=");
264     sb.append(getTableName());
265     sb.append(") user=");
266     sb.append(user);
267   }
268 
269   @Override
270   public TableName getTableName() {
271     return modifiedHTableDescriptor.getTableName();
272   }
273 
274   @Override
275   public TableOperationType getTableOperationType() {
276     return TableOperationType.EDIT;
277   }
278 
279   /**
280    * Check conditions before any real action of modifying a table.
281    * @param env MasterProcedureEnv
282    * @throws IOException
283    */
284   private void prepareModify(final MasterProcedureEnv env) throws IOException {
285     // Checks whether the table exists
286     if (!MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), getTableName())) {
287       throw new TableNotFoundException(getTableName());
288     }
289 
290     // In order to update the descriptor, we need to retrieve the old descriptor for comparison.
291     this.unmodifiedHTableDescriptor =
292         env.getMasterServices().getTableDescriptors().get(getTableName());
293 
294     if (env.getMasterServices().getAssignmentManager().getTableStateManager()
295         .isTableState(getTableName(), ZooKeeperProtos.Table.State.ENABLED)) {
296       // We only execute this procedure with table online if online schema change config is set.
297       if (!MasterDDLOperationHelper.isOnlineSchemaChangeAllowed(env)) {
298         throw new TableNotDisabledException(getTableName());
299       }
300 
301       if (modifiedHTableDescriptor.getRegionReplication() != unmodifiedHTableDescriptor
302           .getRegionReplication()) {
303         throw new IOException("REGION_REPLICATION change is not supported for enabled tables");
304       }
305     }
306 
307     // Find out whether all column families in unmodifiedHTableDescriptor also exists in
308     // the modifiedHTableDescriptor. This is to determine whether we are safe to rollback.
309     final Set<byte[]> oldFamilies = unmodifiedHTableDescriptor.getFamiliesKeys();
310     final Set<byte[]> newFamilies = modifiedHTableDescriptor.getFamiliesKeys();
311     for (byte[] familyName : oldFamilies) {
312       if (!newFamilies.contains(familyName)) {
313         this.deleteColumnFamilyInModify = true;
314         break;
315       }
316     }
317   }
318 
319   /**
320    * Action before modifying table.
321    * @param env MasterProcedureEnv
322    * @param state the procedure state
323    * @throws IOException
324    * @throws InterruptedException
325    */
326   private void preModify(final MasterProcedureEnv env, final ModifyTableState state)
327       throws IOException, InterruptedException {
328     runCoprocessorAction(env, state);
329   }
330 
331   /**
332    * Update descriptor
333    * @param env MasterProcedureEnv
334    * @throws IOException
335    **/
336   private void updateTableDescriptor(final MasterProcedureEnv env) throws IOException {
337     env.getMasterServices().getTableDescriptors().add(modifiedHTableDescriptor);
338   }
339 
340   /**
341    * Undo the descriptor change (for rollback)
342    * @param env MasterProcedureEnv
343    * @throws IOException
344    **/
345   private void restoreTableDescriptor(final MasterProcedureEnv env) throws IOException {
346     env.getMasterServices().getTableDescriptors().add(unmodifiedHTableDescriptor);
347 
348     // delete any new column families from the modifiedHTableDescriptor.
349     deleteFromFs(env, modifiedHTableDescriptor, unmodifiedHTableDescriptor);
350 
351     // Make sure regions are opened after table descriptor is updated.
352     reOpenAllRegionsIfTableIsOnline(env);
353   }
354 
355   /**
356    * Removes from hdfs the families that are not longer present in the new table descriptor.
357    * @param env MasterProcedureEnv
358    * @throws IOException
359    */
360   private void deleteFromFs(final MasterProcedureEnv env,
361       final HTableDescriptor oldHTableDescriptor, final HTableDescriptor newHTableDescriptor)
362       throws IOException {
363     final Set<byte[]> oldFamilies = oldHTableDescriptor.getFamiliesKeys();
364     final Set<byte[]> newFamilies = newHTableDescriptor.getFamiliesKeys();
365     for (byte[] familyName : oldFamilies) {
366       if (!newFamilies.contains(familyName)) {
367         MasterDDLOperationHelper.deleteColumnFamilyFromFileSystem(
368           env,
369           getTableName(),
370           getRegionInfoList(env),
371           familyName);
372       }
373     }
374   }
375 
376   /**
377    * update replica column families if necessary.
378    * @param env MasterProcedureEnv
379    * @throws IOException
380    */
381   private void updateReplicaColumnsIfNeeded(
382     final MasterProcedureEnv env,
383     final HTableDescriptor oldHTableDescriptor,
384     final HTableDescriptor newHTableDescriptor) throws IOException {
385     final int oldReplicaCount = oldHTableDescriptor.getRegionReplication();
386     final int newReplicaCount = newHTableDescriptor.getRegionReplication();
387 
388     if (newReplicaCount < oldReplicaCount) {
389       Set<byte[]> tableRows = new HashSet<byte[]>();
390       Connection connection = env.getMasterServices().getConnection();
391       Scan scan = MetaTableAccessor.getScanForTableName(getTableName());
392       scan.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
393 
394       try (Table metaTable = connection.getTable(TableName.META_TABLE_NAME)) {
395         ResultScanner resScanner = metaTable.getScanner(scan);
396         for (Result result : resScanner) {
397           tableRows.add(result.getRow());
398         }
399         MetaTableAccessor.removeRegionReplicasFromMeta(
400           tableRows,
401           newReplicaCount,
402           oldReplicaCount - newReplicaCount,
403           connection);
404       }
405     }
406 
407     // Setup replication for region replicas if needed
408     if (newReplicaCount > 1 && oldReplicaCount <= 1) {
409       ServerRegionReplicaUtil.setupRegionReplicaReplication(env.getMasterConfiguration());
410     }
411   }
412 
413   /**
414    * Action after modifying table.
415    * @param env MasterProcedureEnv
416    * @param state the procedure state
417    * @throws IOException
418    * @throws InterruptedException
419    */
420   private void postModify(final MasterProcedureEnv env, final ModifyTableState state)
421       throws IOException, InterruptedException {
422     runCoprocessorAction(env, state);
423   }
424 
425   /**
426    * Last action from the procedure - executed when online schema change is supported.
427    * @param env MasterProcedureEnv
428    * @throws IOException
429    */
430   private void reOpenAllRegionsIfTableIsOnline(final MasterProcedureEnv env) throws IOException {
431     // This operation only run when the table is enabled.
432     if (!env.getMasterServices().getAssignmentManager().getTableStateManager()
433         .isTableState(getTableName(), ZooKeeperProtos.Table.State.ENABLED)) {
434       return;
435     }
436 
437     if (MasterDDLOperationHelper.reOpenAllRegions(env, getTableName(), getRegionInfoList(env))) {
438       LOG.info("Completed modify table operation on table " + getTableName());
439     } else {
440       LOG.warn("Error on reopening the regions on table " + getTableName());
441     }
442   }
443 
444   /**
445    * The procedure could be restarted from a different machine. If the variable is null, we need to
446    * retrieve it.
447    * @return traceEnabled whether the trace is enabled
448    */
449   private Boolean isTraceEnabled() {
450     if (traceEnabled == null) {
451       traceEnabled = LOG.isTraceEnabled();
452     }
453     return traceEnabled;
454   }
455 
456   /**
457    * Coprocessor Action.
458    * @param env MasterProcedureEnv
459    * @param state the procedure state
460    * @throws IOException
461    * @throws InterruptedException
462    */
463   private void runCoprocessorAction(final MasterProcedureEnv env, final ModifyTableState state)
464       throws IOException, InterruptedException {
465     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
466     if (cpHost != null) {
467       user.doAs(new PrivilegedExceptionAction<Void>() {
468         @Override
469         public Void run() throws Exception {
470           switch (state) {
471           case MODIFY_TABLE_PRE_OPERATION:
472             cpHost.preModifyTableHandler(getTableName(), modifiedHTableDescriptor);
473             break;
474           case MODIFY_TABLE_POST_OPERATION:
475             cpHost.postModifyTableHandler(getTableName(), modifiedHTableDescriptor);
476             break;
477           default:
478             throw new UnsupportedOperationException(this + " unhandled state=" + state);
479           }
480           return null;
481         }
482       });
483     }
484   }
485 
486   /*
487    * Check whether we are in the state that can be rollback
488    */
489   private boolean isRollbackSupported(final ModifyTableState state) {
490     if (deleteColumnFamilyInModify) {
491       switch (state) {
492       case MODIFY_TABLE_DELETE_FS_LAYOUT:
493       case MODIFY_TABLE_POST_OPERATION:
494       case MODIFY_TABLE_REOPEN_ALL_REGIONS:
495         // It is not safe to rollback if we reach to these states.
496         return false;
497       default:
498         break;
499       }
500     }
501     return true;
502   }
503 
504   private List<HRegionInfo> getRegionInfoList(final MasterProcedureEnv env) throws IOException {
505     if (regionInfoList == null) {
506       regionInfoList = ProcedureSyncWait.getRegionsFromMeta(env, getTableName());
507     }
508     return regionInfoList;
509   }
510 }