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