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.regionserver.handler;
20  
21  import java.io.IOException;
22  import java.util.concurrent.atomic.AtomicBoolean;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.HRegionInfo;
28  import org.apache.hadoop.hbase.HTableDescriptor;
29  import org.apache.hadoop.hbase.Server;
30  import org.apache.hadoop.hbase.executor.EventHandler;
31  import org.apache.hadoop.hbase.executor.EventType;
32  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
33  import org.apache.hadoop.hbase.regionserver.HRegion;
34  import org.apache.hadoop.hbase.regionserver.RegionServerAccounting;
35  import org.apache.hadoop.hbase.regionserver.RegionServerServices;
36  import org.apache.hadoop.hbase.regionserver.RegionServerServices.PostOpenDeployContext;
37  import org.apache.hadoop.hbase.util.CancelableProgressable;
38  /**
39   * Handles opening of a region on a region server.
40   * <p>
41   * This is executed after receiving an OPEN RPC from the master or client.
42   */
43  @InterfaceAudience.Private
44  public class OpenRegionHandler extends EventHandler {
45    private static final Log LOG = LogFactory.getLog(OpenRegionHandler.class);
46  
47    protected final RegionServerServices rsServices;
48  
49    private final HRegionInfo regionInfo;
50    private final HTableDescriptor htd;
51    private final long masterSystemTime;
52  
53    public OpenRegionHandler(final Server server,
54        final RegionServerServices rsServices, HRegionInfo regionInfo,
55        HTableDescriptor htd, long masterSystemTime) {
56      this(server, rsServices, regionInfo, htd, masterSystemTime, EventType.M_RS_OPEN_REGION);
57    }
58  
59    protected OpenRegionHandler(final Server server,
60        final RegionServerServices rsServices, final HRegionInfo regionInfo,
61        final HTableDescriptor htd, long masterSystemTime, EventType eventType) {
62      super(server, eventType);
63      this.rsServices = rsServices;
64      this.regionInfo = regionInfo;
65      this.htd = htd;
66      this.masterSystemTime = masterSystemTime;
67    }
68  
69    public HRegionInfo getRegionInfo() {
70      return regionInfo;
71    }
72  
73    @Override
74    public void process() throws IOException {
75      boolean openSuccessful = false;
76      final String regionName = regionInfo.getRegionNameAsString();
77      HRegion region = null;
78  
79      try {
80        if (this.server.isStopped() || this.rsServices.isStopping()) {
81          return;
82        }
83        final String encodedName = regionInfo.getEncodedName();
84  
85        // 2 different difficult situations can occur
86        // 1) The opening was cancelled. This is an expected situation
87        // 2) The region is now marked as online while we're suppose to open. This would be a bug.
88  
89        // Check that this region is not already online
90        if (this.rsServices.getFromOnlineRegions(encodedName) != null) {
91          LOG.error("Region " + encodedName +
92              " was already online when we started processing the opening. " +
93              "Marking this new attempt as failed");
94          return;
95        }
96  
97        // Check that we're still supposed to open the region.
98        // If fails, just return.  Someone stole the region from under us.
99        if (!isRegionStillOpening()){
100         LOG.error("Region " + encodedName + " opening cancelled");
101         return;
102       }
103 
104       // Open region.  After a successful open, failures in subsequent
105       // processing needs to do a close as part of cleanup.
106       region = openRegion();
107       if (region == null) {
108         return;
109       }
110 
111       if (!updateMeta(region, masterSystemTime) || this.server.isStopped() ||
112           this.rsServices.isStopping()) {
113         return;
114       }
115 
116       if (!isRegionStillOpening()) {
117         return;
118       }
119 
120       // Successful region open, and add it to OnlineRegions
121       this.rsServices.addToOnlineRegions(region);
122       openSuccessful = true;
123 
124       // Done!  Successful region open
125       LOG.debug("Opened " + regionName + " on " +
126         this.server.getServerName());
127     } finally {
128       // Do all clean up here
129       if (!openSuccessful) {
130         doCleanUpOnFailedOpen(region);
131       }
132       final Boolean current = this.rsServices.getRegionsInTransitionInRS().
133           remove(this.regionInfo.getEncodedNameAsBytes());
134 
135       // Let's check if we have met a race condition on open cancellation....
136       // A better solution would be to not have any race condition.
137       // this.rsServices.getRegionsInTransitionInRS().remove(
138       //  this.regionInfo.getEncodedNameAsBytes(), Boolean.TRUE);
139       // would help.
140       if (openSuccessful) {
141         if (current == null) { // Should NEVER happen, but let's be paranoid.
142           LOG.error("Bad state: we've just opened a region that was NOT in transition. Region="
143               + regionName);
144         } else if (Boolean.FALSE.equals(current)) { // Can happen, if we're
145                                                     // really unlucky.
146           LOG.error("Race condition: we've finished to open a region, while a close was requested "
147               + " on region=" + regionName + ". It can be a critical error, as a region that"
148               + " should be closed is now opened. Closing it now");
149           cleanupFailedOpen(region);
150         }
151       }
152     }
153   }
154 
155   private void doCleanUpOnFailedOpen(HRegion region)
156       throws IOException {
157     try {
158       if (region != null) {
159         cleanupFailedOpen(region);
160       }
161     } finally {
162       rsServices.reportRegionStateTransition(TransitionCode.FAILED_OPEN, regionInfo);
163     }
164   }
165 
166   /**
167    * Update ZK or META.  This can take a while if for example the
168    * hbase:meta is not available -- if server hosting hbase:meta crashed and we are
169    * waiting on it to come back -- so run in a thread and keep updating znode
170    * state meantime so master doesn't timeout our region-in-transition.
171    * Caller must cleanup region if this fails.
172    */
173   boolean updateMeta(final HRegion r, long masterSystemTime) {
174     if (this.server.isStopped() || this.rsServices.isStopping()) {
175       return false;
176     }
177     // Object we do wait/notify on.  Make it boolean.  If set, we're done.
178     // Else, wait.
179     final AtomicBoolean signaller = new AtomicBoolean(false);
180     PostOpenDeployTasksThread t = new PostOpenDeployTasksThread(r,
181       this.server, this.rsServices, signaller, masterSystemTime);
182     t.start();
183     // Post open deploy task:
184     //   meta => update meta location in ZK
185     //   other region => update meta
186     while (!signaller.get() && t.isAlive() && !this.server.isStopped() &&
187         !this.rsServices.isStopping() && isRegionStillOpening()) {
188       synchronized (signaller) {
189         try {
190           // Wait for 10 seconds, so that server shutdown
191           // won't take too long if this thread happens to run.
192           if (!signaller.get()) signaller.wait(10000);
193         } catch (InterruptedException e) {
194           // Go to the loop check.
195         }
196       }
197     }
198     // Is thread still alive?  We may have left above loop because server is
199     // stopping or we timed out the edit.  Is so, interrupt it.
200     if (t.isAlive()) {
201       if (!signaller.get()) {
202         // Thread still running; interrupt
203         LOG.debug("Interrupting thread " + t);
204         t.interrupt();
205       }
206       try {
207         t.join();
208       } catch (InterruptedException ie) {
209         LOG.warn("Interrupted joining " +
210           r.getRegionInfo().getRegionNameAsString(), ie);
211         Thread.currentThread().interrupt();
212       }
213     }
214 
215     // Was there an exception opening the region?  This should trigger on
216     // InterruptedException too.  If so, we failed.
217     return (!Thread.interrupted() && t.getException() == null);
218   }
219 
220   /**
221    * Thread to run region post open tasks. Call {@link #getException()} after
222    * the thread finishes to check for exceptions running
223    * {@link RegionServerServices#postOpenDeployTasks(HRegion)
224    */
225   static class PostOpenDeployTasksThread extends Thread {
226     private Throwable exception = null;
227     private final Server server;
228     private final RegionServerServices services;
229     private final HRegion region;
230     private final AtomicBoolean signaller;
231     private final long masterSystemTime;
232 
233     PostOpenDeployTasksThread(final HRegion region, final Server server,
234         final RegionServerServices services, final AtomicBoolean signaller, long masterSystemTime) {
235       super("PostOpenDeployTasks:" + region.getRegionInfo().getEncodedName());
236       this.setDaemon(true);
237       this.server = server;
238       this.services = services;
239       this.region = region;
240       this.signaller = signaller;
241       this.masterSystemTime = masterSystemTime;
242     }
243 
244     @Override
245     public void run() {
246       try {
247         this.services.postOpenDeployTasks(new PostOpenDeployContext(region, masterSystemTime));
248       } catch (Throwable e) {
249         String msg = "Exception running postOpenDeployTasks; region=" +
250           this.region.getRegionInfo().getEncodedName();
251         this.exception = e;
252         if (e instanceof IOException
253             && isRegionStillOpening(region.getRegionInfo(), services)) {
254           server.abort(msg, e);
255         } else {
256           LOG.warn(msg, e);
257         }
258       }
259       // We're done.  Set flag then wake up anyone waiting on thread to complete.
260       this.signaller.set(true);
261       synchronized (this.signaller) {
262         this.signaller.notify();
263       }
264     }
265 
266     /**
267      * @return Null or the run exception; call this method after thread is done.
268      */
269     Throwable getException() {
270       return this.exception;
271     }
272   }
273 
274   /**
275    * @return Instance of HRegion if successful open else null.
276    */
277   HRegion openRegion() {
278     HRegion region = null;
279     try {
280       // Instantiate the region.  This also periodically tickles OPENING
281       // state so master doesn't timeout this region in transition.
282       region = HRegion.openHRegion(this.regionInfo, this.htd,
283         this.rsServices.getWAL(this.regionInfo),
284         this.server.getConfiguration(),
285         this.rsServices,
286         new CancelableProgressable() {
287           @Override
288           public boolean progress() {
289             if (!isRegionStillOpening()) {
290               LOG.warn("Open region aborted since it isn't opening any more");
291               return false;
292             }
293             return true;
294           }
295         });
296     } catch (Throwable t) {
297       // We failed open. Our caller will see the 'null' return value
298       // and transition the node back to FAILED_OPEN. If that fails,
299       // we rely on the Timeout Monitor in the master to reassign.
300       LOG.error(
301           "Failed open of region=" + this.regionInfo.getRegionNameAsString()
302               + ", starting to roll back the global memstore size.", t);
303       // Decrease the global memstore size.
304       if (this.rsServices != null) {
305         RegionServerAccounting rsAccounting =
306           this.rsServices.getRegionServerAccounting();
307         if (rsAccounting != null) {
308           rsAccounting.rollbackRegionReplayEditsSize(this.regionInfo.getRegionName());
309         }
310       }
311     }
312     return region;
313   }
314 
315   void cleanupFailedOpen(final HRegion region) throws IOException {
316     if (region != null) {
317       this.rsServices.removeFromOnlineRegions(region, null);
318       region.close();
319     }
320   }
321 
322   private static boolean isRegionStillOpening(
323       HRegionInfo regionInfo, RegionServerServices rsServices) {
324     byte[] encodedName = regionInfo.getEncodedNameAsBytes();
325     Boolean action = rsServices.getRegionsInTransitionInRS().get(encodedName);
326     return Boolean.TRUE.equals(action); // true means opening for RIT
327   }
328 
329   private boolean isRegionStillOpening() {
330     return isRegionStillOpening(regionInfo, rsServices);
331   }
332 }