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;
20  
21  import java.io.IOException;
22  import java.util.Map.Entry;
23  import java.util.concurrent.ConcurrentHashMap;
24  import java.util.concurrent.atomic.AtomicBoolean;
25  import java.util.concurrent.locks.ReentrantLock;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.HConstants;
31  import org.apache.hadoop.hbase.RemoteExceptionHandler;
32  import org.apache.hadoop.hbase.Server;
33  import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException;
34  import org.apache.hadoop.hbase.wal.WAL;
35  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
36  import org.apache.hadoop.hbase.util.Bytes;
37  import org.apache.hadoop.hbase.util.HasThread;
38  
39  import java.io.IOException;
40  import java.util.concurrent.atomic.AtomicBoolean;
41  import java.util.concurrent.locks.ReentrantLock;
42  
43  import com.google.common.annotations.VisibleForTesting;
44  
45  /**
46   * Runs periodically to determine if the WAL should be rolled.
47   *
48   * NOTE: This class extends Thread rather than Chore because the sleep time
49   * can be interrupted when there is something to do, rather than the Chore
50   * sleep time which is invariant.
51   *
52   * TODO: change to a pool of threads
53   */
54  @InterfaceAudience.Private
55  @VisibleForTesting
56  public class LogRoller extends HasThread {
57    static final Log LOG = LogFactory.getLog(LogRoller.class);
58    private final ReentrantLock rollLock = new ReentrantLock();
59    private final AtomicBoolean rollLog = new AtomicBoolean(false);
60    private final ConcurrentHashMap<WAL, Boolean> walNeedsRoll =
61        new ConcurrentHashMap<WAL, Boolean>();
62    private final Server server;
63    protected final RegionServerServices services;
64    private volatile long lastrolltime = System.currentTimeMillis();
65    // Period to roll log.
66    private final long rollperiod;
67    private final int threadWakeFrequency;
68  
69    public void addWAL(final WAL wal) {
70      if (null == walNeedsRoll.putIfAbsent(wal, Boolean.FALSE)) {
71        wal.registerWALActionsListener(new WALActionsListener.Base() {
72          @Override
73          public void logRollRequested(boolean lowReplicas) {
74            walNeedsRoll.put(wal, Boolean.TRUE);
75            // TODO logs will contend with each other here, replace with e.g. DelayedQueue
76            synchronized(rollLog) {
77              rollLog.set(true);
78              rollLog.notifyAll();
79            }
80          }
81        });
82      }
83    }
84  
85    public void requestRollAll() {
86      for (WAL wal : walNeedsRoll.keySet()) {
87        walNeedsRoll.put(wal, Boolean.TRUE);
88      }
89      synchronized(rollLog) {
90        rollLog.set(true);
91        rollLog.notifyAll();
92      }
93    }
94  
95    /** @param server */
96    public LogRoller(final Server server, final RegionServerServices services) {
97      super();
98      this.server = server;
99      this.services = services;
100     this.rollperiod = this.server.getConfiguration().
101       getLong("hbase.regionserver.logroll.period", 3600000);
102     this.threadWakeFrequency = this.server.getConfiguration().
103       getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000);
104   }
105 
106   @Override
107   public void run() {
108     while (!server.isStopped()) {
109       long now = System.currentTimeMillis();
110       boolean periodic = false;
111       if (!rollLog.get()) {
112         periodic = (now - this.lastrolltime) > this.rollperiod;
113         if (!periodic) {
114           synchronized (rollLog) {
115             try {
116               if (!rollLog.get()) rollLog.wait(this.threadWakeFrequency);
117             } catch (InterruptedException e) {
118               // Fall through
119             }
120           }
121           continue;
122         }
123         // Time for periodic roll
124         if (LOG.isDebugEnabled()) {
125           LOG.debug("Wal roll period " + this.rollperiod + "ms elapsed");
126         }
127       } else if (LOG.isDebugEnabled()) {
128         LOG.debug("WAL roll requested");
129       }
130       rollLock.lock(); // FindBugs UL_UNRELEASED_LOCK_EXCEPTION_PATH
131       try {
132         this.lastrolltime = now;
133         for (Entry<WAL, Boolean> entry : walNeedsRoll.entrySet()) {
134           final WAL wal = entry.getKey();
135           // Force the roll if the logroll.period is elapsed or if a roll was requested.
136           // The returned value is an array of actual region names.
137           final byte [][] regionsToFlush = wal.rollWriter(periodic ||
138               entry.getValue().booleanValue());
139           walNeedsRoll.put(wal, Boolean.FALSE);
140           if (regionsToFlush != null) {
141             for (byte [] r: regionsToFlush) scheduleFlush(r);
142           }
143         }
144       } catch (FailedLogCloseException e) {
145         server.abort("Failed log close in log roller", e);
146       } catch (java.net.ConnectException e) {
147         server.abort("Failed log close in log roller", e);
148       } catch (IOException ex) {
149         // Abort if we get here.  We probably won't recover an IOE. HBASE-1132
150         server.abort("IOE in log roller",
151           RemoteExceptionHandler.checkIOException(ex));
152       } catch (Exception ex) {
153         LOG.error("Log rolling failed", ex);
154         server.abort("Log rolling failed", ex);
155       } finally {
156         try {
157           rollLog.set(false);
158         } finally {
159           rollLock.unlock();
160         }
161       }
162     }
163     LOG.info("LogRoller exiting.");
164   }
165 
166   /**
167    * @param encodedRegionName Encoded name of region to flush.
168    */
169   private void scheduleFlush(final byte [] encodedRegionName) {
170     boolean scheduled = false;
171     HRegion r = this.services.getFromOnlineRegions(Bytes.toString(encodedRegionName));
172     FlushRequester requester = null;
173     if (r != null) {
174       requester = this.services.getFlushRequester();
175       if (requester != null) {
176         requester.requestFlush(r);
177         scheduled = true;
178       }
179     }
180     if (!scheduled) {
181       LOG.warn("Failed to schedule flush of " +
182         Bytes.toString(encodedRegionName) + ", region=" + r + ", requester=" +
183         requester);
184     }
185   }
186 
187 }