001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.master.procedure;
019
020import java.io.IOException;
021import java.lang.Thread.UncaughtExceptionHandler;
022import java.util.List;
023import java.util.Set;
024import java.util.concurrent.TimeUnit;
025import org.apache.hadoop.hbase.CallQueueTooBigException;
026import org.apache.hadoop.hbase.DoNotRetryIOException;
027import org.apache.hadoop.hbase.ServerName;
028import org.apache.hadoop.hbase.client.AsyncRegionServerAdmin;
029import org.apache.hadoop.hbase.client.RegionInfo;
030import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
031import org.apache.hadoop.hbase.master.MasterServices;
032import org.apache.hadoop.hbase.master.ServerListener;
033import org.apache.hadoop.hbase.master.ServerManager;
034import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
035import org.apache.hadoop.hbase.procedure2.RemoteProcedureDispatcher;
036import org.apache.hadoop.hbase.regionserver.RegionServerAbortedException;
037import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
038import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
039import org.apache.hadoop.hbase.util.FutureUtils;
040import org.apache.hadoop.ipc.RemoteException;
041import org.apache.yetus.audience.InterfaceAudience;
042import org.slf4j.Logger;
043import org.slf4j.LoggerFactory;
044import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
045import org.apache.hbase.thirdparty.com.google.common.collect.ArrayListMultimap;
046import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
047import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
048import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
049import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CloseRegionRequest;
050import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ExecuteProceduresRequest;
051import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ExecuteProceduresResponse;
052import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.OpenRegionRequest;
053import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RemoteProcedureRequest;
054
055/**
056 * A remote procecdure dispatcher for regionservers.
057 */
058@InterfaceAudience.Private
059public class RSProcedureDispatcher
060    extends RemoteProcedureDispatcher<MasterProcedureEnv, ServerName>
061    implements ServerListener {
062  private static final Logger LOG = LoggerFactory.getLogger(RSProcedureDispatcher.class);
063
064  public static final String RS_RPC_STARTUP_WAIT_TIME_CONF_KEY =
065      "hbase.regionserver.rpc.startup.waittime";
066  private static final int DEFAULT_RS_RPC_STARTUP_WAIT_TIME = 60000;
067
068  protected final MasterServices master;
069  private final long rsStartupWaitTime;
070  private MasterProcedureEnv procedureEnv;
071
072  public RSProcedureDispatcher(final MasterServices master) {
073    super(master.getConfiguration());
074
075    this.master = master;
076    this.rsStartupWaitTime = master.getConfiguration().getLong(
077      RS_RPC_STARTUP_WAIT_TIME_CONF_KEY, DEFAULT_RS_RPC_STARTUP_WAIT_TIME);
078  }
079
080  @Override
081  protected UncaughtExceptionHandler getUncaughtExceptionHandler() {
082    return new UncaughtExceptionHandler() {
083
084      @Override
085      public void uncaughtException(Thread t, Throwable e) {
086        LOG.error("Unexpected error caught, this may cause the procedure to hang forever", e);
087      }
088    };
089  }
090
091  @Override
092  public boolean start() {
093    if (!super.start()) {
094      return false;
095    }
096    if (master.isStopped()) {
097      LOG.debug("Stopped");
098      return false;
099    }
100    // Around startup, if failed, some of the below may be set back to null so NPE is possible.
101    ServerManager sm = master.getServerManager();
102    if (sm == null) {
103      LOG.debug("ServerManager is null");
104      return false;
105    }
106    sm.registerListener(this);
107    ProcedureExecutor<MasterProcedureEnv> pe = master.getMasterProcedureExecutor();
108    if (pe == null) {
109      LOG.debug("ProcedureExecutor is null");
110      return false;
111    }
112    this.procedureEnv = pe.getEnvironment();
113    if (this.procedureEnv == null) {
114      LOG.debug("ProcedureEnv is null; stopping={}", master.isStopping());
115      return false;
116    }
117    try {
118      for (ServerName serverName : sm.getOnlineServersList()) {
119        addNode(serverName);
120      }
121    } catch (Exception e) {
122      LOG.info("Failed start", e);
123      return false;
124    }
125    return true;
126  }
127
128  @Override
129  public boolean stop() {
130    if (!super.stop()) {
131      return false;
132    }
133
134    master.getServerManager().unregisterListener(this);
135    return true;
136  }
137
138  @Override
139  protected void remoteDispatch(final ServerName serverName,
140      final Set<RemoteProcedure> remoteProcedures) {
141    if (!master.getServerManager().isServerOnline(serverName)) {
142      // fail fast
143      submitTask(new DeadRSRemoteCall(serverName, remoteProcedures));
144    } else {
145      submitTask(new ExecuteProceduresRemoteCall(serverName, remoteProcedures));
146    }
147  }
148
149  @Override
150  protected void abortPendingOperations(final ServerName serverName,
151      final Set<RemoteProcedure> operations) {
152    // TODO: Replace with a ServerNotOnlineException()
153    final IOException e = new DoNotRetryIOException("server not online " + serverName);
154    for (RemoteProcedure proc: operations) {
155      proc.remoteCallFailed(procedureEnv, serverName, e);
156    }
157  }
158
159  @Override
160  public void serverAdded(final ServerName serverName) {
161    addNode(serverName);
162  }
163
164  @Override
165  public void serverRemoved(final ServerName serverName) {
166    removeNode(serverName);
167  }
168
169  private interface RemoteProcedureResolver {
170    void dispatchOpenRequests(MasterProcedureEnv env, List<RegionOpenOperation> operations);
171
172    void dispatchCloseRequests(MasterProcedureEnv env, List<RegionCloseOperation> operations);
173
174    void dispatchServerOperations(MasterProcedureEnv env, List<ServerOperation> operations);
175  }
176
177  /**
178   * Fetches {@link org.apache.hadoop.hbase.procedure2.RemoteProcedureDispatcher.RemoteOperation}s
179   * from the given {@code remoteProcedures} and groups them by class of the returned operation.
180   * Then {@code resolver} is used to dispatch {@link RegionOpenOperation}s and
181   * {@link RegionCloseOperation}s.
182   * @param serverName RegionServer to which the remote operations are sent
183   * @param operations Remote procedures which are dispatched to the given server
184   * @param resolver Used to dispatch remote procedures to given server.
185   */
186  public void splitAndResolveOperation(ServerName serverName, Set<RemoteProcedure> operations,
187      RemoteProcedureResolver resolver) {
188    MasterProcedureEnv env = master.getMasterProcedureExecutor().getEnvironment();
189    ArrayListMultimap<Class<?>, RemoteOperation> reqsByType =
190      buildAndGroupRequestByType(env, serverName, operations);
191
192    List<RegionOpenOperation> openOps = fetchType(reqsByType, RegionOpenOperation.class);
193    if (!openOps.isEmpty()) {
194      resolver.dispatchOpenRequests(env, openOps);
195    }
196
197    List<RegionCloseOperation> closeOps = fetchType(reqsByType, RegionCloseOperation.class);
198    if (!closeOps.isEmpty()) {
199      resolver.dispatchCloseRequests(env, closeOps);
200    }
201
202    List<ServerOperation> refreshOps = fetchType(reqsByType, ServerOperation.class);
203    if (!refreshOps.isEmpty()) {
204      resolver.dispatchServerOperations(env, refreshOps);
205    }
206
207    if (!reqsByType.isEmpty()) {
208      LOG.warn("unknown request type in the queue: " + reqsByType);
209    }
210  }
211
212  private class DeadRSRemoteCall extends ExecuteProceduresRemoteCall {
213
214    public DeadRSRemoteCall(ServerName serverName, Set<RemoteProcedure> remoteProcedures) {
215      super(serverName, remoteProcedures);
216    }
217
218    @Override
219    public void run() {
220      remoteCallFailed(procedureEnv,
221        new RegionServerStoppedException("Server " + getServerName() + " is not online"));
222    }
223  }
224
225  // ==========================================================================
226  //  Compatibility calls
227  // ==========================================================================
228  protected class ExecuteProceduresRemoteCall implements RemoteProcedureResolver, Runnable {
229
230    private final ServerName serverName;
231
232    private final Set<RemoteProcedure> remoteProcedures;
233
234    private int numberOfAttemptsSoFar = 0;
235    private long maxWaitTime = -1;
236
237    private ExecuteProceduresRequest.Builder request = null;
238
239    public ExecuteProceduresRemoteCall(final ServerName serverName,
240        final Set<RemoteProcedure> remoteProcedures) {
241      this.serverName = serverName;
242      this.remoteProcedures = remoteProcedures;
243    }
244
245    private AsyncRegionServerAdmin  getRsAdmin() throws IOException {
246      return master.getAsyncClusterConnection().getRegionServerAdmin(serverName);
247    }
248
249    protected final ServerName getServerName() {
250      return serverName;
251    }
252
253    private boolean scheduleForRetry(IOException e) {
254      LOG.debug("request to {} failed, try={}", serverName, numberOfAttemptsSoFar, e);
255      // Should we wait a little before retrying? If the server is starting it's yes.
256      if (e instanceof ServerNotRunningYetException) {
257        long remainingTime = getMaxWaitTime() - EnvironmentEdgeManager.currentTime();
258        if (remainingTime > 0) {
259          LOG.warn("waiting a little before trying on the same server={}," +
260            " try={}, can wait up to {}ms", serverName, numberOfAttemptsSoFar, remainingTime);
261          numberOfAttemptsSoFar++;
262          submitTask(this, 100, TimeUnit.MILLISECONDS);
263          return true;
264        }
265        LOG.warn("server {} is not up for a while; try a new one", serverName);
266        return false;
267      }
268      if (e instanceof DoNotRetryIOException) {
269        LOG.warn("server {} tells us do not retry due to {}, try={}, give up", serverName,
270          e.toString(), numberOfAttemptsSoFar);
271        return false;
272      }
273      // this exception is thrown in the rpc framework, where we can make sure that the call has not
274      // been executed yet, so it is safe to mark it as fail. Especially for open a region, we'd
275      // better choose another region server
276      // notice that, it is safe to quit only if this is the first time we send request to region
277      // server. Maybe the region server has accept our request the first time, and then there is a
278      // network error which prevents we receive the response, and the second time we hit a
279      // CallQueueTooBigException, obviously it is not safe to quit here, otherwise it may lead to a
280      // double assign...
281      if (e instanceof CallQueueTooBigException && numberOfAttemptsSoFar == 0) {
282        LOG.warn("request to {} failed due to {}, try={}, this usually because" +
283          " server is overloaded, give up", serverName, e.toString(), numberOfAttemptsSoFar);
284        return false;
285      }
286      // Always retry for other exception types if the region server is not dead yet.
287      if (!master.getServerManager().isServerOnline(serverName)) {
288        LOG.warn("request to {} failed due to {}, try={}, and the server is dead, give up",
289          serverName, e.toString(), numberOfAttemptsSoFar);
290        return false;
291      }
292      if (e instanceof RegionServerAbortedException || e instanceof RegionServerStoppedException) {
293        // A better way is to return true here to let the upper layer quit, and then schedule a
294        // background task to check whether the region server is dead. And if it is dead, call
295        // remoteCallFailed to tell the upper layer. Keep retrying here does not lead to incorrect
296        // result, but waste some resources.
297        LOG.warn("server {} is aborted or stopped, for safety we still need to" +
298          " wait until it is fully dead, try={}", serverName, numberOfAttemptsSoFar);
299      } else {
300        LOG.warn("request to server {} failed due to {}, try={}, retrying...", serverName,
301          e.toString(), numberOfAttemptsSoFar);
302      }
303      numberOfAttemptsSoFar++;
304      submitTask(this, 100, TimeUnit.MILLISECONDS);
305      return true;
306    }
307
308    private long getMaxWaitTime() {
309      if (this.maxWaitTime < 0) {
310        // This is the max attempts, not retries, so it should be at least 1.
311        this.maxWaitTime = EnvironmentEdgeManager.currentTime() + rsStartupWaitTime;
312      }
313      return this.maxWaitTime;
314    }
315
316    private IOException unwrapException(IOException e) {
317      if (e instanceof RemoteException) {
318        e = ((RemoteException)e).unwrapRemoteException();
319      }
320      return e;
321    }
322
323    @Override
324    public void run() {
325      request = ExecuteProceduresRequest.newBuilder();
326      if (LOG.isTraceEnabled()) {
327        LOG.trace("Building request with operations count=" + remoteProcedures.size());
328      }
329      splitAndResolveOperation(getServerName(), remoteProcedures, this);
330
331      try {
332        sendRequest(getServerName(), request.build());
333      } catch (IOException e) {
334        e = unwrapException(e);
335        // TODO: In the future some operation may want to bail out early.
336        // TODO: How many times should we retry (use numberOfAttemptsSoFar)
337        if (!scheduleForRetry(e)) {
338          remoteCallFailed(procedureEnv, e);
339        }
340      }
341    }
342
343    @Override
344    public void dispatchOpenRequests(final MasterProcedureEnv env,
345        final List<RegionOpenOperation> operations) {
346      request.addOpenRegion(buildOpenRegionRequest(env, getServerName(), operations));
347    }
348
349    @Override
350    public void dispatchCloseRequests(final MasterProcedureEnv env,
351        final List<RegionCloseOperation> operations) {
352      for (RegionCloseOperation op: operations) {
353        request.addCloseRegion(op.buildCloseRegionRequest(getServerName()));
354      }
355    }
356
357    @Override
358    public void dispatchServerOperations(MasterProcedureEnv env, List<ServerOperation> operations) {
359      operations.stream().map(o -> o.buildRequest()).forEachOrdered(request::addProc);
360    }
361
362    // will be overridden in test.
363    @VisibleForTesting
364    protected ExecuteProceduresResponse sendRequest(final ServerName serverName,
365        final ExecuteProceduresRequest request) throws IOException {
366      return FutureUtils.get(getRsAdmin().executeProcedures(request));
367    }
368
369    protected final void remoteCallFailed(final MasterProcedureEnv env, final IOException e) {
370      for (RemoteProcedure proc : remoteProcedures) {
371        proc.remoteCallFailed(env, getServerName(), e);
372      }
373    }
374  }
375
376  private static OpenRegionRequest buildOpenRegionRequest(final MasterProcedureEnv env,
377      final ServerName serverName, final List<RegionOpenOperation> operations) {
378    final OpenRegionRequest.Builder builder = OpenRegionRequest.newBuilder();
379    builder.setServerStartCode(serverName.getStartcode());
380    builder.setMasterSystemTime(EnvironmentEdgeManager.currentTime());
381    for (RegionOpenOperation op: operations) {
382      builder.addOpenInfo(op.buildRegionOpenInfoRequest(env));
383    }
384    return builder.build();
385  }
386
387  // ==========================================================================
388  //  RPC Messages
389  //  - ServerOperation: refreshConfig, grant, revoke, ... (TODO)
390  //  - RegionOperation: open, close, flush, snapshot, ...
391  // ==========================================================================
392
393  public static final class ServerOperation extends RemoteOperation {
394
395    private final long procId;
396
397    private final Class<?> rsProcClass;
398
399    private final byte[] rsProcData;
400
401    public ServerOperation(RemoteProcedure remoteProcedure, long procId, Class<?> rsProcClass,
402        byte[] rsProcData) {
403      super(remoteProcedure);
404      this.procId = procId;
405      this.rsProcClass = rsProcClass;
406      this.rsProcData = rsProcData;
407    }
408
409    public RemoteProcedureRequest buildRequest() {
410      return RemoteProcedureRequest.newBuilder().setProcId(procId)
411          .setProcClass(rsProcClass.getName()).setProcData(ByteString.copyFrom(rsProcData)).build();
412    }
413  }
414
415  public static abstract class RegionOperation extends RemoteOperation {
416    protected final RegionInfo regionInfo;
417    protected final long procId;
418
419    protected RegionOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo, long procId) {
420      super(remoteProcedure);
421      this.regionInfo = regionInfo;
422      this.procId = procId;
423    }
424  }
425
426  public static class RegionOpenOperation extends RegionOperation {
427
428    public RegionOpenOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo,
429        long procId) {
430      super(remoteProcedure, regionInfo, procId);
431    }
432
433    public OpenRegionRequest.RegionOpenInfo buildRegionOpenInfoRequest(
434        final MasterProcedureEnv env) {
435      return RequestConverter.buildRegionOpenInfo(regionInfo,
436        env.getAssignmentManager().getFavoredNodes(regionInfo), procId);
437    }
438  }
439
440  public static class RegionCloseOperation extends RegionOperation {
441    private final ServerName destinationServer;
442
443    public RegionCloseOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo, long procId,
444        ServerName destinationServer) {
445      super(remoteProcedure, regionInfo, procId);
446      this.destinationServer = destinationServer;
447    }
448
449    public ServerName getDestinationServer() {
450      return destinationServer;
451    }
452
453    public CloseRegionRequest buildCloseRegionRequest(final ServerName serverName) {
454      return ProtobufUtil.buildCloseRegionRequest(serverName, regionInfo.getRegionName(),
455        getDestinationServer(), procId);
456    }
457  }
458}