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.procedure2.RemoteProcedureDispatcher;
034import org.apache.hadoop.hbase.regionserver.RegionServerAbortedException;
035import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
036import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
037import org.apache.hadoop.hbase.util.FutureUtils;
038import org.apache.hadoop.ipc.RemoteException;
039import org.apache.yetus.audience.InterfaceAudience;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042
043import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
044import org.apache.hbase.thirdparty.com.google.common.collect.ArrayListMultimap;
045import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
046
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
097    master.getServerManager().registerListener(this);
098    procedureEnv = master.getMasterProcedureExecutor().getEnvironment();
099    for (ServerName serverName: master.getServerManager().getOnlineServersList()) {
100      addNode(serverName);
101    }
102    return true;
103  }
104
105  @Override
106  public boolean stop() {
107    if (!super.stop()) {
108      return false;
109    }
110
111    master.getServerManager().unregisterListener(this);
112    return true;
113  }
114
115  @Override
116  protected void remoteDispatch(final ServerName serverName,
117      final Set<RemoteProcedure> remoteProcedures) {
118    if (!master.getServerManager().isServerOnline(serverName)) {
119      // fail fast
120      submitTask(new DeadRSRemoteCall(serverName, remoteProcedures));
121    } else {
122      submitTask(new ExecuteProceduresRemoteCall(serverName, remoteProcedures));
123    }
124  }
125
126  @Override
127  protected void abortPendingOperations(final ServerName serverName,
128      final Set<RemoteProcedure> operations) {
129    // TODO: Replace with a ServerNotOnlineException()
130    final IOException e = new DoNotRetryIOException("server not online " + serverName);
131    for (RemoteProcedure proc: operations) {
132      proc.remoteCallFailed(procedureEnv, serverName, e);
133    }
134  }
135
136  @Override
137  public void serverAdded(final ServerName serverName) {
138    addNode(serverName);
139  }
140
141  @Override
142  public void serverRemoved(final ServerName serverName) {
143    removeNode(serverName);
144  }
145
146  private interface RemoteProcedureResolver {
147    void dispatchOpenRequests(MasterProcedureEnv env, List<RegionOpenOperation> operations);
148
149    void dispatchCloseRequests(MasterProcedureEnv env, List<RegionCloseOperation> operations);
150
151    void dispatchServerOperations(MasterProcedureEnv env, List<ServerOperation> operations);
152  }
153
154  /**
155   * Fetches {@link org.apache.hadoop.hbase.procedure2.RemoteProcedureDispatcher.RemoteOperation}s
156   * from the given {@code remoteProcedures} and groups them by class of the returned operation.
157   * Then {@code resolver} is used to dispatch {@link RegionOpenOperation}s and
158   * {@link RegionCloseOperation}s.
159   * @param serverName RegionServer to which the remote operations are sent
160   * @param operations Remote procedures which are dispatched to the given server
161   * @param resolver Used to dispatch remote procedures to given server.
162   */
163  public void splitAndResolveOperation(ServerName serverName, Set<RemoteProcedure> operations,
164      RemoteProcedureResolver resolver) {
165    MasterProcedureEnv env = master.getMasterProcedureExecutor().getEnvironment();
166    ArrayListMultimap<Class<?>, RemoteOperation> reqsByType =
167      buildAndGroupRequestByType(env, serverName, operations);
168
169    List<RegionOpenOperation> openOps = fetchType(reqsByType, RegionOpenOperation.class);
170    if (!openOps.isEmpty()) {
171      resolver.dispatchOpenRequests(env, openOps);
172    }
173
174    List<RegionCloseOperation> closeOps = fetchType(reqsByType, RegionCloseOperation.class);
175    if (!closeOps.isEmpty()) {
176      resolver.dispatchCloseRequests(env, closeOps);
177    }
178
179    List<ServerOperation> refreshOps = fetchType(reqsByType, ServerOperation.class);
180    if (!refreshOps.isEmpty()) {
181      resolver.dispatchServerOperations(env, refreshOps);
182    }
183
184    if (!reqsByType.isEmpty()) {
185      LOG.warn("unknown request type in the queue: " + reqsByType);
186    }
187  }
188
189  private class DeadRSRemoteCall extends ExecuteProceduresRemoteCall {
190
191    public DeadRSRemoteCall(ServerName serverName, Set<RemoteProcedure> remoteProcedures) {
192      super(serverName, remoteProcedures);
193    }
194
195    @Override
196    public void run() {
197      remoteCallFailed(procedureEnv,
198        new RegionServerStoppedException("Server " + getServerName() + " is not online"));
199    }
200  }
201
202  // ==========================================================================
203  //  Compatibility calls
204  // ==========================================================================
205  protected class ExecuteProceduresRemoteCall implements RemoteProcedureResolver, Runnable {
206
207    private final ServerName serverName;
208
209    private final Set<RemoteProcedure> remoteProcedures;
210
211    private int numberOfAttemptsSoFar = 0;
212    private long maxWaitTime = -1;
213
214    private ExecuteProceduresRequest.Builder request = null;
215
216    public ExecuteProceduresRemoteCall(final ServerName serverName,
217        final Set<RemoteProcedure> remoteProcedures) {
218      this.serverName = serverName;
219      this.remoteProcedures = remoteProcedures;
220    }
221
222    private AsyncRegionServerAdmin  getRsAdmin() throws IOException {
223      return master.getAsyncClusterConnection().getRegionServerAdmin(serverName);
224    }
225
226    protected final ServerName getServerName() {
227      return serverName;
228    }
229
230    private boolean scheduleForRetry(IOException e) {
231      LOG.debug("request to {} failed, try={}", serverName, numberOfAttemptsSoFar, e);
232      // Should we wait a little before retrying? If the server is starting it's yes.
233      if (e instanceof ServerNotRunningYetException) {
234        long remainingTime = getMaxWaitTime() - EnvironmentEdgeManager.currentTime();
235        if (remainingTime > 0) {
236          LOG.warn("waiting a little before trying on the same server={}," +
237            " try={}, can wait up to {}ms", serverName, numberOfAttemptsSoFar, remainingTime);
238          numberOfAttemptsSoFar++;
239          submitTask(this, 100, TimeUnit.MILLISECONDS);
240          return true;
241        }
242        LOG.warn("server {} is not up for a while; try a new one", serverName);
243        return false;
244      }
245      if (e instanceof DoNotRetryIOException) {
246        LOG.warn("server {} tells us do not retry due to {}, try={}, give up", serverName,
247          e.toString(), numberOfAttemptsSoFar);
248        return false;
249      }
250      // this exception is thrown in the rpc framework, where we can make sure that the call has not
251      // been executed yet, so it is safe to mark it as fail. Especially for open a region, we'd
252      // better choose another region server
253      // notice that, it is safe to quit only if this is the first time we send request to region
254      // server. Maybe the region server has accept our request the first time, and then there is a
255      // network error which prevents we receive the response, and the second time we hit a
256      // CallQueueTooBigException, obviously it is not safe to quit here, otherwise it may lead to a
257      // double assign...
258      if (e instanceof CallQueueTooBigException && numberOfAttemptsSoFar == 0) {
259        LOG.warn("request to {} failed due to {}, try={}, this usually because" +
260          " server is overloaded, give up", serverName, e.toString(), numberOfAttemptsSoFar);
261        return false;
262      }
263      // Always retry for other exception types if the region server is not dead yet.
264      if (!master.getServerManager().isServerOnline(serverName)) {
265        LOG.warn("request to {} failed due to {}, try={}, and the server is dead, give up",
266          serverName, e.toString(), numberOfAttemptsSoFar);
267        return false;
268      }
269      if (e instanceof RegionServerAbortedException || e instanceof RegionServerStoppedException) {
270        // A better way is to return true here to let the upper layer quit, and then schedule a
271        // background task to check whether the region server is dead. And if it is dead, call
272        // remoteCallFailed to tell the upper layer. Keep retrying here does not lead to incorrect
273        // result, but waste some resources.
274        LOG.warn("server {} is aborted or stopped, for safety we still need to" +
275          " wait until it is fully dead, try={}", serverName, numberOfAttemptsSoFar);
276      } else {
277        LOG.warn("request to server {} failed due to {}, try={}, retrying...", serverName,
278          e.toString(), numberOfAttemptsSoFar);
279      }
280      numberOfAttemptsSoFar++;
281      submitTask(this, 100, TimeUnit.MILLISECONDS);
282      return true;
283    }
284
285    private long getMaxWaitTime() {
286      if (this.maxWaitTime < 0) {
287        // This is the max attempts, not retries, so it should be at least 1.
288        this.maxWaitTime = EnvironmentEdgeManager.currentTime() + rsStartupWaitTime;
289      }
290      return this.maxWaitTime;
291    }
292
293    private IOException unwrapException(IOException e) {
294      if (e instanceof RemoteException) {
295        e = ((RemoteException)e).unwrapRemoteException();
296      }
297      return e;
298    }
299
300    @Override
301    public void run() {
302      request = ExecuteProceduresRequest.newBuilder();
303      if (LOG.isTraceEnabled()) {
304        LOG.trace("Building request with operations count=" + remoteProcedures.size());
305      }
306      splitAndResolveOperation(getServerName(), remoteProcedures, this);
307
308      try {
309        sendRequest(getServerName(), request.build());
310      } catch (IOException e) {
311        e = unwrapException(e);
312        // TODO: In the future some operation may want to bail out early.
313        // TODO: How many times should we retry (use numberOfAttemptsSoFar)
314        if (!scheduleForRetry(e)) {
315          remoteCallFailed(procedureEnv, e);
316        }
317      }
318    }
319
320    @Override
321    public void dispatchOpenRequests(final MasterProcedureEnv env,
322        final List<RegionOpenOperation> operations) {
323      request.addOpenRegion(buildOpenRegionRequest(env, getServerName(), operations));
324    }
325
326    @Override
327    public void dispatchCloseRequests(final MasterProcedureEnv env,
328        final List<RegionCloseOperation> operations) {
329      for (RegionCloseOperation op: operations) {
330        request.addCloseRegion(op.buildCloseRegionRequest(getServerName()));
331      }
332    }
333
334    @Override
335    public void dispatchServerOperations(MasterProcedureEnv env, List<ServerOperation> operations) {
336      operations.stream().map(o -> o.buildRequest()).forEachOrdered(request::addProc);
337    }
338
339    // will be overridden in test.
340    @VisibleForTesting
341    protected ExecuteProceduresResponse sendRequest(final ServerName serverName,
342        final ExecuteProceduresRequest request) throws IOException {
343      return FutureUtils.get(getRsAdmin().executeProcedures(request));
344    }
345
346    protected final void remoteCallFailed(final MasterProcedureEnv env, final IOException e) {
347      for (RemoteProcedure proc : remoteProcedures) {
348        proc.remoteCallFailed(env, getServerName(), e);
349      }
350    }
351  }
352
353  private static OpenRegionRequest buildOpenRegionRequest(final MasterProcedureEnv env,
354      final ServerName serverName, final List<RegionOpenOperation> operations) {
355    final OpenRegionRequest.Builder builder = OpenRegionRequest.newBuilder();
356    builder.setServerStartCode(serverName.getStartcode());
357    builder.setMasterSystemTime(EnvironmentEdgeManager.currentTime());
358    for (RegionOpenOperation op: operations) {
359      builder.addOpenInfo(op.buildRegionOpenInfoRequest(env));
360    }
361    return builder.build();
362  }
363
364  // ==========================================================================
365  //  RPC Messages
366  //  - ServerOperation: refreshConfig, grant, revoke, ... (TODO)
367  //  - RegionOperation: open, close, flush, snapshot, ...
368  // ==========================================================================
369
370  public static final class ServerOperation extends RemoteOperation {
371
372    private final long procId;
373
374    private final Class<?> rsProcClass;
375
376    private final byte[] rsProcData;
377
378    public ServerOperation(RemoteProcedure remoteProcedure, long procId, Class<?> rsProcClass,
379        byte[] rsProcData) {
380      super(remoteProcedure);
381      this.procId = procId;
382      this.rsProcClass = rsProcClass;
383      this.rsProcData = rsProcData;
384    }
385
386    public RemoteProcedureRequest buildRequest() {
387      return RemoteProcedureRequest.newBuilder().setProcId(procId)
388          .setProcClass(rsProcClass.getName()).setProcData(ByteString.copyFrom(rsProcData)).build();
389    }
390  }
391
392  public static abstract class RegionOperation extends RemoteOperation {
393    protected final RegionInfo regionInfo;
394    protected final long procId;
395
396    protected RegionOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo, long procId) {
397      super(remoteProcedure);
398      this.regionInfo = regionInfo;
399      this.procId = procId;
400    }
401  }
402
403  public static class RegionOpenOperation extends RegionOperation {
404
405    public RegionOpenOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo,
406        long procId) {
407      super(remoteProcedure, regionInfo, procId);
408    }
409
410    public OpenRegionRequest.RegionOpenInfo buildRegionOpenInfoRequest(
411        final MasterProcedureEnv env) {
412      return RequestConverter.buildRegionOpenInfo(regionInfo,
413        env.getAssignmentManager().getFavoredNodes(regionInfo), procId);
414    }
415  }
416
417  public static class RegionCloseOperation extends RegionOperation {
418    private final ServerName destinationServer;
419
420    public RegionCloseOperation(RemoteProcedure remoteProcedure, RegionInfo regionInfo, long procId,
421        ServerName destinationServer) {
422      super(remoteProcedure, regionInfo, procId);
423      this.destinationServer = destinationServer;
424    }
425
426    public ServerName getDestinationServer() {
427      return destinationServer;
428    }
429
430    public CloseRegionRequest buildCloseRegionRequest(final ServerName serverName) {
431      return ProtobufUtil.buildCloseRegionRequest(serverName, regionInfo.getRegionName(),
432        getDestinationServer(), procId);
433    }
434  }
435}