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.HColumnDescriptor;
31  import org.apache.hadoop.hbase.HRegionInfo;
32  import org.apache.hadoop.hbase.HTableDescriptor;
33  import org.apache.hadoop.hbase.InvalidFamilyOperationException;
34  import org.apache.hadoop.hbase.TableName;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.executor.EventType;
37  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
38  import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
39  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
40  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos;
41  import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.ModifyColumnFamilyState;
42  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
43  import org.apache.hadoop.security.UserGroupInformation;
44  
45  /**
46   * The procedure to modify a column family from an existing table.
47   */
48  @InterfaceAudience.Private
49  public class ModifyColumnFamilyProcedure
50      extends StateMachineProcedure<MasterProcedureEnv, ModifyColumnFamilyState>
51      implements TableProcedureInterface {
52    private static final Log LOG = LogFactory.getLog(ModifyColumnFamilyProcedure.class);
53  
54    private final AtomicBoolean aborted = new AtomicBoolean(false);
55  
56    private TableName tableName;
57    private HTableDescriptor unmodifiedHTableDescriptor;
58    private HColumnDescriptor cfDescriptor;
59    private UserGroupInformation user;
60  
61    private Boolean traceEnabled;
62  
63    public ModifyColumnFamilyProcedure() {
64      this.unmodifiedHTableDescriptor = null;
65      this.traceEnabled = null;
66    }
67  
68    public ModifyColumnFamilyProcedure(
69        final MasterProcedureEnv env,
70        final TableName tableName,
71        final HColumnDescriptor cfDescriptor) throws IOException {
72      this.tableName = tableName;
73      this.cfDescriptor = cfDescriptor;
74      this.user = env.getRequestUser().getUGI();
75      this.unmodifiedHTableDescriptor = null;
76      this.traceEnabled = null;
77    }
78  
79    @Override
80    protected Flow executeFromState(final MasterProcedureEnv env,
81        final ModifyColumnFamilyState state) {
82      if (isTraceEnabled()) {
83        LOG.trace(this + " execute state=" + state);
84      }
85  
86      try {
87        switch (state) {
88        case MODIFY_COLUMN_FAMILY_PREPARE:
89          prepareModify(env);
90          setNextState(ModifyColumnFamilyState.MODIFY_COLUMN_FAMILY_PRE_OPERATION);
91          break;
92        case MODIFY_COLUMN_FAMILY_PRE_OPERATION:
93          preModify(env, state);
94          setNextState(ModifyColumnFamilyState.MODIFY_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR);
95          break;
96        case MODIFY_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR:
97          updateTableDescriptor(env);
98          setNextState(ModifyColumnFamilyState.MODIFY_COLUMN_FAMILY_POST_OPERATION);
99          break;
100       case MODIFY_COLUMN_FAMILY_POST_OPERATION:
101         postModify(env, state);
102         setNextState(ModifyColumnFamilyState.MODIFY_COLUMN_FAMILY_REOPEN_ALL_REGIONS);
103         break;
104       case MODIFY_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
105         reOpenAllRegionsIfTableIsOnline(env);
106         return Flow.NO_MORE_STATE;
107       default:
108         throw new UnsupportedOperationException(this + " unhandled state=" + state);
109       }
110     } catch (InterruptedException|IOException e) {
111       LOG.warn("Error trying to modify the column family " + getColumnFamilyName()
112           + " of the table " + tableName + "(in state=" + state + ")", e);
113 
114       setFailure("master-modify-columnfamily", e);
115     }
116     return Flow.HAS_MORE_STATE;
117   }
118 
119   @Override
120   protected void rollbackState(final MasterProcedureEnv env, final ModifyColumnFamilyState state)
121       throws IOException {
122     if (isTraceEnabled()) {
123       LOG.trace(this + " rollback state=" + state);
124     }
125     try {
126       switch (state) {
127       case MODIFY_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
128         break; // Nothing to undo.
129       case MODIFY_COLUMN_FAMILY_POST_OPERATION:
130         // TODO-MAYBE: call the coprocessor event to undo?
131         break;
132       case MODIFY_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR:
133         restoreTableDescriptor(env);
134         break;
135       case MODIFY_COLUMN_FAMILY_PRE_OPERATION:
136         // TODO-MAYBE: call the coprocessor event to undo?
137         break;
138       case MODIFY_COLUMN_FAMILY_PREPARE:
139         break; // nothing to do
140       default:
141         throw new UnsupportedOperationException(this + " unhandled state=" + state);
142       }
143     } catch (IOException e) {
144       // This will be retried. Unless there is a bug in the code,
145       // this should be just a "temporary error" (e.g. network down)
146       LOG.warn("Failed rollback attempt step " + state + " for adding the column family"
147           + getColumnFamilyName() + " to the table " + tableName, e);
148       throw e;
149     }
150   }
151 
152   @Override
153   protected ModifyColumnFamilyState getState(final int stateId) {
154     return ModifyColumnFamilyState.valueOf(stateId);
155   }
156 
157   @Override
158   protected int getStateId(final ModifyColumnFamilyState state) {
159     return state.getNumber();
160   }
161 
162   @Override
163   protected ModifyColumnFamilyState getInitialState() {
164     return ModifyColumnFamilyState.MODIFY_COLUMN_FAMILY_PREPARE;
165   }
166 
167   @Override
168   protected void setNextState(ModifyColumnFamilyState state) {
169     if (aborted.get()) {
170       setAbortFailure("modify-columnfamily", "abort requested");
171     } else {
172       super.setNextState(state);
173     }
174   }
175 
176   @Override
177   public boolean abort(final MasterProcedureEnv env) {
178     aborted.set(true);
179     return true;
180   }
181 
182   @Override
183   protected boolean acquireLock(final MasterProcedureEnv env) {
184     if (!env.isInitialized()) return false;
185     return env.getProcedureQueue().tryAcquireTableWrite(
186       tableName,
187       EventType.C_M_MODIFY_FAMILY.toString());
188   }
189 
190   @Override
191   protected void releaseLock(final MasterProcedureEnv env) {
192     env.getProcedureQueue().releaseTableWrite(tableName);
193   }
194 
195   @Override
196   public void serializeStateData(final OutputStream stream) throws IOException {
197     super.serializeStateData(stream);
198 
199     MasterProcedureProtos.ModifyColumnFamilyStateData.Builder modifyCFMsg =
200         MasterProcedureProtos.ModifyColumnFamilyStateData.newBuilder()
201             .setUserInfo(MasterProcedureUtil.toProtoUserInfo(user))
202             .setTableName(ProtobufUtil.toProtoTableName(tableName))
203             .setColumnfamilySchema(cfDescriptor.convert());
204     if (unmodifiedHTableDescriptor != null) {
205       modifyCFMsg.setUnmodifiedTableSchema(unmodifiedHTableDescriptor.convert());
206     }
207 
208     modifyCFMsg.build().writeDelimitedTo(stream);
209   }
210 
211   @Override
212   public void deserializeStateData(final InputStream stream) throws IOException {
213     super.deserializeStateData(stream);
214 
215     MasterProcedureProtos.ModifyColumnFamilyStateData modifyCFMsg =
216         MasterProcedureProtos.ModifyColumnFamilyStateData.parseDelimitedFrom(stream);
217     user = MasterProcedureUtil.toUserInfo(modifyCFMsg.getUserInfo());
218     tableName = ProtobufUtil.toTableName(modifyCFMsg.getTableName());
219     cfDescriptor = HColumnDescriptor.convert(modifyCFMsg.getColumnfamilySchema());
220     if (modifyCFMsg.hasUnmodifiedTableSchema()) {
221       unmodifiedHTableDescriptor = HTableDescriptor.convert(modifyCFMsg.getUnmodifiedTableSchema());
222     }
223   }
224 
225   @Override
226   public void toStringClassDetails(StringBuilder sb) {
227     sb.append(getClass().getSimpleName());
228     sb.append(" (table=");
229     sb.append(tableName);
230     sb.append(", columnfamily=");
231     if (cfDescriptor != null) {
232       sb.append(getColumnFamilyName());
233     } else {
234       sb.append("Unknown");
235     }
236     sb.append(") user=");
237     sb.append(user);
238   }
239 
240   @Override
241   public TableName getTableName() {
242     return tableName;
243   }
244 
245   @Override
246   public TableOperationType getTableOperationType() {
247     return TableOperationType.EDIT;
248   }
249 
250   /**
251    * Action before any real action of modifying column family.
252    * @param env MasterProcedureEnv
253    * @throws IOException
254    */
255   private void prepareModify(final MasterProcedureEnv env) throws IOException {
256     // Checks whether the table is allowed to be modified.
257     MasterDDLOperationHelper.checkTableModifiable(env, tableName);
258 
259     unmodifiedHTableDescriptor = env.getMasterServices().getTableDescriptors().get(tableName);
260     if (unmodifiedHTableDescriptor == null) {
261       throw new IOException("HTableDescriptor missing for " + tableName);
262     }
263     if (!unmodifiedHTableDescriptor.hasFamily(cfDescriptor.getName())) {
264       throw new InvalidFamilyOperationException("Family '" + getColumnFamilyName()
265           + "' does not exist, so it cannot be modified");
266     }
267   }
268 
269   /**
270    * Action before modifying column family.
271    * @param env MasterProcedureEnv
272    * @param state the procedure state
273    * @throws IOException
274    * @throws InterruptedException
275    */
276   private void preModify(final MasterProcedureEnv env, final ModifyColumnFamilyState state)
277       throws IOException, InterruptedException {
278     runCoprocessorAction(env, state);
279   }
280 
281   /**
282    * Modify the column family from the file system
283    */
284   private void updateTableDescriptor(final MasterProcedureEnv env) throws IOException {
285     // Update table descriptor
286     LOG.info("ModifyColumnFamily. Table = " + tableName + " HCD = " + cfDescriptor.toString());
287 
288     HTableDescriptor htd = env.getMasterServices().getTableDescriptors().get(tableName);
289     htd.modifyFamily(cfDescriptor);
290     env.getMasterServices().getTableDescriptors().add(htd);
291   }
292 
293   /**
294    * Restore back to the old descriptor
295    * @param env MasterProcedureEnv
296    * @throws IOException
297    **/
298   private void restoreTableDescriptor(final MasterProcedureEnv env) throws IOException {
299     env.getMasterServices().getTableDescriptors().add(unmodifiedHTableDescriptor);
300 
301     // Make sure regions are opened after table descriptor is updated.
302     reOpenAllRegionsIfTableIsOnline(env);
303   }
304 
305   /**
306    * Action after modifying column family.
307    * @param env MasterProcedureEnv
308    * @param state the procedure state
309    * @throws IOException
310    * @throws InterruptedException
311    */
312   private void postModify(final MasterProcedureEnv env, final ModifyColumnFamilyState state)
313       throws IOException, InterruptedException {
314     runCoprocessorAction(env, state);
315   }
316 
317   /**
318    * Last action from the procedure - executed when online schema change is supported.
319    * @param env MasterProcedureEnv
320    * @throws IOException
321    */
322   private void reOpenAllRegionsIfTableIsOnline(final MasterProcedureEnv env) throws IOException {
323     // This operation only run when the table is enabled.
324     if (!env.getMasterServices().getAssignmentManager().getTableStateManager()
325         .isTableState(getTableName(), ZooKeeperProtos.Table.State.ENABLED)) {
326       return;
327     }
328 
329     List<HRegionInfo> regionInfoList = ProcedureSyncWait.getRegionsFromMeta(env, getTableName());
330     if (MasterDDLOperationHelper.reOpenAllRegions(env, getTableName(), regionInfoList)) {
331       LOG.info("Completed add column family operation on table " + getTableName());
332     } else {
333       LOG.warn("Error on reopening the regions on table " + getTableName());
334     }
335   }
336 
337   /**
338    * The procedure could be restarted from a different machine. If the variable is null, we need to
339    * retrieve it.
340    * @return traceEnabled
341    */
342   private Boolean isTraceEnabled() {
343     if (traceEnabled == null) {
344       traceEnabled = LOG.isTraceEnabled();
345     }
346     return traceEnabled;
347   }
348 
349   private String getColumnFamilyName() {
350     return cfDescriptor.getNameAsString();
351   }
352 
353   /**
354    * Coprocessor Action.
355    * @param env MasterProcedureEnv
356    * @param state the procedure state
357    * @throws IOException
358    * @throws InterruptedException
359    */
360   private void runCoprocessorAction(final MasterProcedureEnv env,
361       final ModifyColumnFamilyState state) throws IOException, InterruptedException {
362     final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
363     if (cpHost != null) {
364       user.doAs(new PrivilegedExceptionAction<Void>() {
365         @Override
366         public Void run() throws Exception {
367           switch (state) {
368           case MODIFY_COLUMN_FAMILY_PRE_OPERATION:
369             cpHost.preModifyColumnHandler(tableName, cfDescriptor);
370             break;
371           case MODIFY_COLUMN_FAMILY_POST_OPERATION:
372             cpHost.postModifyColumnHandler(tableName, cfDescriptor);
373             break;
374           default:
375             throw new UnsupportedOperationException(this + " unhandled state=" + state);
376           }
377           return null;
378         }
379       });
380     }
381   }
382 }