View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master.handler;
20  
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.LinkedList;
25  import java.util.List;
26  import java.util.NavigableMap;
27  import java.util.TreeMap;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.CoordinatedStateException;
32  import org.apache.hadoop.hbase.HRegionInfo;
33  import org.apache.hadoop.hbase.HRegionLocation;
34  import org.apache.hadoop.hbase.HTableDescriptor;
35  import org.apache.hadoop.hbase.InvalidFamilyOperationException;
36  import org.apache.hadoop.hbase.MetaTableAccessor;
37  import org.apache.hadoop.hbase.Server;
38  import org.apache.hadoop.hbase.ServerName;
39  import org.apache.hadoop.hbase.TableDescriptor;
40  import org.apache.hadoop.hbase.TableName;
41  import org.apache.hadoop.hbase.TableNotDisabledException;
42  import org.apache.hadoop.hbase.classification.InterfaceAudience;
43  import org.apache.hadoop.hbase.client.Connection;
44  import org.apache.hadoop.hbase.client.RegionLocator;
45  import org.apache.hadoop.hbase.client.TableState;
46  import org.apache.hadoop.hbase.executor.EventHandler;
47  import org.apache.hadoop.hbase.executor.EventType;
48  import org.apache.hadoop.hbase.master.BulkReOpen;
49  import org.apache.hadoop.hbase.master.MasterServices;
50  import org.apache.hadoop.hbase.master.TableLockManager.TableLock;
51  import org.apache.hadoop.hbase.util.Bytes;
52  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
53  
54  import com.google.common.collect.Lists;
55  import com.google.common.collect.Maps;
56  
57  /**
58   * Base class for performing operations against tables.
59   * Checks on whether the process can go forward are done in constructor rather
60   * than later on in {@link #process()}.  The idea is to fail fast rather than
61   * later down in an async invocation of {@link #process()} (which currently has
62   * no means of reporting back issues once started).
63   */
64  @InterfaceAudience.Private
65  public abstract class TableEventHandler extends EventHandler {
66    private static final Log LOG = LogFactory.getLog(TableEventHandler.class);
67    protected final MasterServices masterServices;
68    protected final TableName tableName;
69    protected TableLock tableLock;
70    private boolean isPrepareCalled = false;
71  
72    public TableEventHandler(EventType eventType, TableName tableName, Server server,
73        MasterServices masterServices) {
74      super(server, eventType);
75      this.masterServices = masterServices;
76      this.tableName = tableName;
77    }
78  
79    public TableEventHandler prepare() throws IOException {
80      //acquire the table write lock, blocking
81      this.tableLock = masterServices.getTableLockManager()
82          .writeLock(tableName, eventType.toString());
83      this.tableLock.acquire();
84      boolean success = false;
85      try {
86        try {
87          this.masterServices.checkTableModifiable(tableName);
88        } catch (TableNotDisabledException ex)  {
89          if (isOnlineSchemaChangeAllowed()
90              && eventType.isOnlineSchemaChangeSupported()) {
91            LOG.debug("Ignoring table not disabled exception " +
92                "for supporting online schema changes.");
93          } else {
94            throw ex;
95          }
96        }
97        prepareWithTableLock();
98        success = true;
99      } finally {
100       if (!success ) {
101         releaseTableLock();
102       }
103     }
104     this.isPrepareCalled = true;
105     return this;
106   }
107 
108   /** Called from prepare() while holding the table lock. Subclasses
109    * can do extra initialization, and not worry about the releasing
110    * the table lock. */
111   protected void prepareWithTableLock() throws IOException {
112   }
113 
114   private boolean isOnlineSchemaChangeAllowed() {
115     return this.server.getConfiguration().getBoolean(
116       "hbase.online.schema.update.enable", false);
117   }
118 
119   @Override
120   public void process() {
121     if (!isPrepareCalled) {
122       //For proper table locking semantics, the implementor should ensure to call
123       //TableEventHandler.prepare() before calling process()
124       throw new RuntimeException("Implementation should have called prepare() first");
125     }
126     try {
127       LOG.info("Handling table operation " + eventType + " on table " +
128           tableName);
129 
130       List<HRegionInfo> hris;
131       if (TableName.META_TABLE_NAME.equals(tableName)) {
132         hris = new MetaTableLocator().getMetaRegions(server.getZooKeeper());
133       } else {
134         hris = MetaTableAccessor.getTableRegions(server.getConnection(), tableName);
135       }
136       handleTableOperation(hris);
137       if (eventType.isOnlineSchemaChangeSupported() && this.masterServices.
138           getAssignmentManager().getTableStateManager().isTableState(
139           tableName, TableState.State.ENABLED)) {
140         if (reOpenAllRegions(hris)) {
141           LOG.info("Completed table operation " + eventType + " on table " +
142               tableName);
143         } else {
144           LOG.warn("Error on reopening the regions");
145         }
146       }
147       completed(null);
148     } catch (IOException e) {
149       LOG.error("Error manipulating table " + tableName, e);
150       completed(e);
151     } catch (CoordinatedStateException e) {
152       LOG.error("Error manipulating table " + tableName, e);
153       completed(e);
154     } finally {
155       releaseTableLock();
156     }
157   }
158 
159   protected void releaseTableLock() {
160     if (this.tableLock != null) {
161       try {
162         this.tableLock.release();
163       } catch (IOException ex) {
164         LOG.warn("Could not release the table lock", ex);
165       }
166     }
167   }
168 
169   /**
170    * Called after that process() is completed.
171    * @param exception null if process() is successful or not null if something has failed.
172    */
173   protected void completed(final Throwable exception) {
174   }
175 
176   public boolean reOpenAllRegions(List<HRegionInfo> regions) throws IOException {
177     boolean done = false;
178     LOG.info("Bucketing regions by region server...");
179     List<HRegionLocation> regionLocations = null;
180     Connection connection = this.masterServices.getConnection();
181     try (RegionLocator locator = connection.getRegionLocator(tableName)) {
182       regionLocations = locator.getAllRegionLocations();
183     }
184     // Convert List<HRegionLocation> to Map<HRegionInfo, ServerName>.
185     NavigableMap<HRegionInfo, ServerName> hri2Sn = new TreeMap<HRegionInfo, ServerName>();
186     for (HRegionLocation location: regionLocations) {
187       hri2Sn.put(location.getRegionInfo(), location.getServerName());
188     }
189     TreeMap<ServerName, List<HRegionInfo>> serverToRegions = Maps.newTreeMap();
190     List<HRegionInfo> reRegions = new ArrayList<HRegionInfo>();
191     for (HRegionInfo hri : regions) {
192       ServerName sn = hri2Sn.get(hri);
193       // Skip the offlined split parent region
194       // See HBASE-4578 for more information.
195       if (null == sn) {
196         LOG.info("Skip " + hri);
197         continue;
198       }
199       if (!serverToRegions.containsKey(sn)) {
200         LinkedList<HRegionInfo> hriList = Lists.newLinkedList();
201         serverToRegions.put(sn, hriList);
202       }
203       reRegions.add(hri);
204       serverToRegions.get(sn).add(hri);
205     }
206 
207     LOG.info("Reopening " + reRegions.size() + " regions on "
208         + serverToRegions.size() + " region servers.");
209     this.masterServices.getAssignmentManager().setRegionsToReopen(reRegions);
210     BulkReOpen bulkReopen = new BulkReOpen(this.server, serverToRegions,
211         this.masterServices.getAssignmentManager());
212     while (true) {
213       try {
214         if (bulkReopen.bulkReOpen()) {
215           done = true;
216           break;
217         } else {
218           LOG.warn("Timeout before reopening all regions");
219         }
220       } catch (InterruptedException e) {
221         LOG.warn("Reopen was interrupted");
222         // Preserve the interrupt.
223         Thread.currentThread().interrupt();
224         break;
225       }
226     }
227     return done;
228   }
229 
230 
231   /**
232    * Gets a TableDescriptor from the masterServices.  Can Throw exceptions.
233    *
234    * @return Table descriptor for this table
235    * @throws TableExistsException
236    * @throws FileNotFoundException
237    * @throws IOException
238    */
239   public TableDescriptor getTableDescriptor()
240   throws FileNotFoundException, IOException {
241     TableDescriptor htd =
242       this.masterServices.getTableDescriptors().getDescriptor(tableName);
243     if (htd == null) {
244       throw new IOException("HTableDescriptor missing for " + tableName);
245     }
246     return htd;
247   }
248 
249   byte [] hasColumnFamily(final HTableDescriptor htd, final byte [] cf)
250   throws InvalidFamilyOperationException {
251     if (!htd.hasFamily(cf)) {
252       throw new InvalidFamilyOperationException("Column family '" +
253         Bytes.toString(cf) + "' does not exist");
254     }
255     return cf;
256   }
257 
258   protected abstract void handleTableOperation(List<HRegionInfo> regions)
259     throws IOException, CoordinatedStateException;
260 }