View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.ipc;
19  import static org.junit.Assert.assertEquals;
20  import static org.junit.Assert.assertFalse;
21  import static org.junit.Assert.assertNotEquals;
22  import static org.junit.Assert.assertTrue;
23  import static org.mockito.Matchers.any;
24  import static org.mockito.Matchers.anyObject;
25  import static org.mockito.Matchers.eq;
26  import static org.mockito.Mockito.doAnswer;
27  import static org.mockito.Mockito.mock;
28  import static org.mockito.Mockito.timeout;
29  import static org.mockito.Mockito.verify;
30  import static org.mockito.Mockito.when;
31  
32  import java.io.IOException;
33  import java.net.InetSocketAddress;
34  import java.util.ArrayList;
35  import java.util.HashSet;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.Set;
39  import java.util.concurrent.BlockingQueue;
40  import java.util.concurrent.CountDownLatch;
41  import java.util.concurrent.LinkedBlockingQueue;
42  
43  import org.apache.commons.logging.Log;
44  import org.apache.commons.logging.LogFactory;
45  import org.apache.hadoop.conf.Configuration;
46  import org.apache.hadoop.hbase.HBaseConfiguration;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.client.Put;
49  import org.apache.hadoop.hbase.ipc.RpcServer.Call;
50  import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandlerImpl;
51  import org.apache.hadoop.hbase.protobuf.RequestConverter;
52  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
53  import org.apache.hadoop.hbase.protobuf.generated.RPCProtos;
54  import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;
55  import org.apache.hadoop.hbase.security.User;
56  import org.apache.hadoop.hbase.testclassification.SmallTests;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.hbase.util.EnvironmentEdge;
59  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
60  import org.apache.hadoop.hbase.util.Threads;
61  import org.junit.Before;
62  import org.junit.Test;
63  import org.junit.experimental.categories.Category;
64  import org.mockito.invocation.InvocationOnMock;
65  import org.mockito.stubbing.Answer;
66  
67  import com.google.common.collect.ImmutableList;
68  import com.google.common.collect.ImmutableMap;
69  import com.google.common.collect.ImmutableSet;
70  import com.google.common.collect.Maps;
71  import com.google.protobuf.Message;
72  
73  @Category(SmallTests.class)
74  public class TestSimpleRpcScheduler {
75    private static final Log LOG = LogFactory.getLog(TestSimpleRpcScheduler.class);
76  
77    private final RpcScheduler.Context CONTEXT = new RpcScheduler.Context() {
78      @Override
79      public InetSocketAddress getListenerAddress() {
80        return InetSocketAddress.createUnresolved("127.0.0.1", 1000);
81      }
82    };
83    private Configuration conf;
84  
85    @Before
86    public void setUp() {
87      conf = HBaseConfiguration.create();
88    }
89  
90    @Test
91    public void testBasic() throws IOException, InterruptedException {
92      PriorityFunction qosFunction = mock(PriorityFunction.class);
93      RpcScheduler scheduler = new SimpleRpcScheduler(
94          conf, 10, 0, 0, qosFunction, 0);
95      scheduler.init(CONTEXT);
96      scheduler.start();
97      CallRunner task = createMockTask();
98      task.setStatus(new MonitoredRPCHandlerImpl());
99      scheduler.dispatch(task);
100     verify(task, timeout(1000)).run();
101     scheduler.stop();
102   }
103 
104   @Test
105   public void testHandlerIsolation() throws IOException, InterruptedException {
106     CallRunner generalTask = createMockTask();
107     CallRunner priorityTask = createMockTask();
108     CallRunner replicationTask = createMockTask();
109     List<CallRunner> tasks = ImmutableList.of(
110         generalTask,
111         priorityTask,
112         replicationTask);
113     Map<CallRunner, Integer> qos = ImmutableMap.of(
114         generalTask, 0,
115         priorityTask, HConstants.HIGH_QOS + 1,
116         replicationTask, HConstants.REPLICATION_QOS);
117     PriorityFunction qosFunction = mock(PriorityFunction.class);
118     final Map<CallRunner, Thread> handlerThreads = Maps.newHashMap();
119     final CountDownLatch countDownLatch = new CountDownLatch(tasks.size());
120     Answer<Void> answerToRun = new Answer<Void>() {
121       @Override
122       public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
123         synchronized (handlerThreads) {
124           handlerThreads.put(
125               (CallRunner) invocationOnMock.getMock(),
126               Thread.currentThread());
127         }
128         countDownLatch.countDown();
129         return null;
130       }
131     };
132     for (CallRunner task : tasks) {
133       task.setStatus(new MonitoredRPCHandlerImpl());
134       doAnswer(answerToRun).when(task).run();
135     }
136 
137     RpcScheduler scheduler = new SimpleRpcScheduler(
138         conf, 1, 1 ,1, qosFunction, HConstants.HIGH_QOS);
139     scheduler.init(CONTEXT);
140     scheduler.start();
141     for (CallRunner task : tasks) {
142       when(qosFunction.getPriority((RPCProtos.RequestHeader) anyObject(),
143         (Message) anyObject(), (User) anyObject()))
144           .thenReturn(qos.get(task));
145       scheduler.dispatch(task);
146     }
147     for (CallRunner task : tasks) {
148       verify(task, timeout(1000)).run();
149     }
150     scheduler.stop();
151 
152     // Tests that these requests are handled by three distinct threads.
153     countDownLatch.await();
154     assertEquals(3, ImmutableSet.copyOf(handlerThreads.values()).size());
155   }
156 
157   private CallRunner createMockTask() {
158     Call call = mock(Call.class);
159     CallRunner task = mock(CallRunner.class);
160     when(task.getCall()).thenReturn(call);
161     return task;
162   }
163 
164   @Test
165   public void testRpcScheduler() throws Exception {
166     testRpcScheduler(RpcExecutor.CALL_QUEUE_TYPE_DEADLINE_CONF_VALUE);
167     testRpcScheduler(RpcExecutor.CALL_QUEUE_TYPE_FIFO_CONF_VALUE);
168   }
169 
170   private void testRpcScheduler(final String queueType) throws Exception {
171     Configuration schedConf = HBaseConfiguration.create();
172     schedConf.set(RpcExecutor.CALL_QUEUE_TYPE_CONF_KEY, queueType);
173 
174     PriorityFunction priority = mock(PriorityFunction.class);
175     when(priority.getPriority(any(RequestHeader.class),
176       any(Message.class), any(User.class)))
177       .thenReturn(HConstants.NORMAL_QOS);
178 
179     RpcScheduler scheduler = new SimpleRpcScheduler(schedConf, 1, 1, 1, priority,
180                                                     HConstants.QOS_THRESHOLD);
181     try {
182       scheduler.start();
183 
184       CallRunner smallCallTask = mock(CallRunner.class);
185       RpcServer.Call smallCall = mock(RpcServer.Call.class);
186       RequestHeader smallHead = RequestHeader.newBuilder().setCallId(1).build();
187       when(smallCallTask.getCall()).thenReturn(smallCall);
188       when(smallCall.getHeader()).thenReturn(smallHead);
189 
190       CallRunner largeCallTask = mock(CallRunner.class);
191       RpcServer.Call largeCall = mock(RpcServer.Call.class);
192       RequestHeader largeHead = RequestHeader.newBuilder().setCallId(50).build();
193       when(largeCallTask.getCall()).thenReturn(largeCall);
194       when(largeCall.getHeader()).thenReturn(largeHead);
195 
196       CallRunner hugeCallTask = mock(CallRunner.class);
197       RpcServer.Call hugeCall = mock(RpcServer.Call.class);
198       RequestHeader hugeHead = RequestHeader.newBuilder().setCallId(100).build();
199       when(hugeCallTask.getCall()).thenReturn(hugeCall);
200       when(hugeCall.getHeader()).thenReturn(hugeHead);
201 
202       when(priority.getDeadline(eq(smallHead), any(Message.class))).thenReturn(0L);
203       when(priority.getDeadline(eq(largeHead), any(Message.class))).thenReturn(50L);
204       when(priority.getDeadline(eq(hugeHead), any(Message.class))).thenReturn(100L);
205 
206       final ArrayList<Integer> work = new ArrayList<Integer>();
207       doAnswerTaskExecution(smallCallTask, work, 10, 250);
208       doAnswerTaskExecution(largeCallTask, work, 50, 250);
209       doAnswerTaskExecution(hugeCallTask, work, 100, 250);
210 
211       scheduler.dispatch(smallCallTask);
212       scheduler.dispatch(smallCallTask);
213       scheduler.dispatch(smallCallTask);
214       scheduler.dispatch(hugeCallTask);
215       scheduler.dispatch(smallCallTask);
216       scheduler.dispatch(largeCallTask);
217       scheduler.dispatch(smallCallTask);
218       scheduler.dispatch(smallCallTask);
219 
220       while (work.size() < 8) {
221         Thread.sleep(100);
222       }
223 
224       int seqSum = 0;
225       int totalTime = 0;
226       for (int i = 0; i < work.size(); ++i) {
227         LOG.debug("Request i=" + i + " value=" + work.get(i));
228         seqSum += work.get(i);
229         totalTime += seqSum;
230       }
231       LOG.debug("Total Time: " + totalTime);
232 
233       // -> [small small small huge small large small small]
234       // -> NO REORDER   [10 10 10 100 10 50 10 10] -> 930 (FIFO Queue)
235       // -> WITH REORDER [10 10 10 10 10 10 50 100] -> 530 (Deadline Queue)
236       if (queueType.equals(RpcExecutor.CALL_QUEUE_TYPE_DEADLINE_CONF_VALUE)) {
237         assertEquals(530, totalTime);
238       } else if (queueType.equals(RpcExecutor.CALL_QUEUE_TYPE_FIFO_CONF_VALUE)) {
239         assertEquals(930, totalTime);
240       }
241     } finally {
242       scheduler.stop();
243     }
244   }
245 
246   @Test
247   public void testScanQueueWithZeroScanRatio() throws Exception {
248     Configuration schedConf = HBaseConfiguration.create();
249     schedConf.setFloat(RpcExecutor.CALL_QUEUE_HANDLER_FACTOR_CONF_KEY, 1.0f);
250     schedConf.setFloat(RWQueueRpcExecutor.CALL_QUEUE_READ_SHARE_CONF_KEY, 0.5f);
251     schedConf.setFloat(RWQueueRpcExecutor.CALL_QUEUE_SCAN_SHARE_CONF_KEY, 0f);
252 
253     PriorityFunction priority = mock(PriorityFunction.class);
254     when(priority.getPriority(any(RequestHeader.class), any(Message.class),
255       any(User.class))).thenReturn(HConstants.NORMAL_QOS);
256 
257     RpcScheduler scheduler = new SimpleRpcScheduler(schedConf, 2, 1, 1, priority,
258                                                     HConstants.QOS_THRESHOLD);
259     assertNotEquals(scheduler, null);
260   }
261 
262   @Test
263   public void testScanQueues() throws Exception {
264     Configuration schedConf = HBaseConfiguration.create();
265     schedConf.setFloat(RpcExecutor.CALL_QUEUE_HANDLER_FACTOR_CONF_KEY, 1.0f);
266     schedConf.setFloat(RWQueueRpcExecutor.CALL_QUEUE_READ_SHARE_CONF_KEY, 0.7f);
267     schedConf.setFloat(RWQueueRpcExecutor.CALL_QUEUE_SCAN_SHARE_CONF_KEY, 0.5f);
268 
269     PriorityFunction priority = mock(PriorityFunction.class);
270     when(priority.getPriority(any(RequestHeader.class), any(Message.class),
271       any(User.class))).thenReturn(HConstants.NORMAL_QOS);
272 
273     RpcScheduler scheduler = new SimpleRpcScheduler(schedConf, 3, 1, 1, priority,
274                                                     HConstants.QOS_THRESHOLD);
275     try {
276       scheduler.start();
277 
278       CallRunner putCallTask = mock(CallRunner.class);
279       RpcServer.Call putCall = mock(RpcServer.Call.class);
280       putCall.param = RequestConverter.buildMutateRequest(
281           Bytes.toBytes("abc"), new Put(Bytes.toBytes("row")));
282       RequestHeader putHead = RequestHeader.newBuilder().setMethodName("mutate").build();
283       when(putCallTask.getCall()).thenReturn(putCall);
284       when(putCall.getHeader()).thenReturn(putHead);
285 
286       CallRunner getCallTask = mock(CallRunner.class);
287       RpcServer.Call getCall = mock(RpcServer.Call.class);
288       RequestHeader getHead = RequestHeader.newBuilder().setMethodName("get").build();
289       when(getCallTask.getCall()).thenReturn(getCall);
290       when(getCall.getHeader()).thenReturn(getHead);
291 
292       CallRunner scanCallTask = mock(CallRunner.class);
293       RpcServer.Call scanCall = mock(RpcServer.Call.class);
294       scanCall.param = ScanRequest.newBuilder().build();
295       RequestHeader scanHead = RequestHeader.newBuilder().setMethodName("scan").build();
296       when(scanCallTask.getCall()).thenReturn(scanCall);
297       when(scanCall.getHeader()).thenReturn(scanHead);
298 
299       ArrayList<Integer> work = new ArrayList<Integer>();
300       doAnswerTaskExecution(putCallTask, work, 1, 1000);
301       doAnswerTaskExecution(getCallTask, work, 2, 1000);
302       doAnswerTaskExecution(scanCallTask, work, 3, 1000);
303 
304       // There are 3 queues: [puts], [gets], [scans]
305       // so the calls will be interleaved
306       scheduler.dispatch(putCallTask);
307       scheduler.dispatch(putCallTask);
308       scheduler.dispatch(putCallTask);
309       scheduler.dispatch(getCallTask);
310       scheduler.dispatch(getCallTask);
311       scheduler.dispatch(getCallTask);
312       scheduler.dispatch(scanCallTask);
313       scheduler.dispatch(scanCallTask);
314       scheduler.dispatch(scanCallTask);
315 
316       while (work.size() < 6) {
317         Thread.sleep(100);
318       }
319 
320       for (int i = 0; i < work.size() - 2; i += 3) {
321         assertNotEquals(work.get(i + 0), work.get(i + 1));
322         assertNotEquals(work.get(i + 0), work.get(i + 2));
323         assertNotEquals(work.get(i + 1), work.get(i + 2));
324       }
325     } finally {
326       scheduler.stop();
327     }
328   }
329 
330   private void doAnswerTaskExecution(final CallRunner callTask,
331       final ArrayList<Integer> results, final int value, final int sleepInterval) {
332     callTask.setStatus(new MonitoredRPCHandlerImpl());
333     doAnswer(new Answer<Object>() {
334       @Override
335       public Object answer(InvocationOnMock invocation) {
336         synchronized (results) {
337           results.add(value);
338         }
339         Threads.sleepWithoutInterrupt(sleepInterval);
340         return null;
341       }
342     }).when(callTask).run();
343   }
344 
345   private static void waitUntilQueueEmpty(SimpleRpcScheduler scheduler)
346       throws InterruptedException {
347     while (scheduler.getGeneralQueueLength() > 0) {
348       Thread.sleep(100);
349     }
350   }
351 
352   @Test
353   public void testSoftAndHardQueueLimits() throws Exception {
354     Configuration schedConf = HBaseConfiguration.create();
355 
356     schedConf.setInt(HConstants.REGION_SERVER_HANDLER_COUNT, 0);
357     schedConf.setInt("hbase.ipc.server.max.callqueue.length", 5);
358 
359     PriorityFunction priority = mock(PriorityFunction.class);
360     when(priority.getPriority(any(RequestHeader.class), any(Message.class),
361       any(User.class))).thenReturn(HConstants.NORMAL_QOS);
362     SimpleRpcScheduler scheduler = new SimpleRpcScheduler(schedConf, 0, 0, 0, priority,
363       HConstants.QOS_THRESHOLD);
364     try {
365       scheduler.start();
366 
367       CallRunner putCallTask = mock(CallRunner.class);
368       RpcServer.Call putCall = mock(RpcServer.Call.class);
369       putCall.param = RequestConverter.buildMutateRequest(
370         Bytes.toBytes("abc"), new Put(Bytes.toBytes("row")));
371       RequestHeader putHead = RequestHeader.newBuilder().setMethodName("mutate").build();
372       when(putCallTask.getCall()).thenReturn(putCall);
373       when(putCall.getHeader()).thenReturn(putHead);
374 
375       assertTrue(scheduler.dispatch(putCallTask));
376       waitUntilQueueEmpty(scheduler);
377 
378       schedConf.setInt("hbase.ipc.server.max.callqueue.length", 0);
379       scheduler.onConfigurationChange(schedConf);
380       assertFalse(scheduler.dispatch(putCallTask));
381       waitUntilQueueEmpty(scheduler);
382       schedConf.setInt("hbase.ipc.server.max.callqueue.length", 1);
383       scheduler.onConfigurationChange(schedConf);
384       assertTrue(scheduler.dispatch(putCallTask));
385     } finally {
386       scheduler.stop();
387     }
388   }
389 
390   private static final class CoDelEnvironmentEdge implements EnvironmentEdge {
391 
392     private final BlockingQueue<Long> timeQ = new LinkedBlockingQueue<>();
393 
394     private long offset;
395 
396     private final Set<String> threadNamePrefixs = new HashSet<>();
397 
398     @Override
399     public long currentTime() {
400       for (String threadNamePrefix : threadNamePrefixs) {
401         String threadName = Thread.currentThread().getName();
402         if (threadName.startsWith(threadNamePrefix)) {
403           return timeQ.poll().longValue() + offset;
404         }
405       }
406       return System.currentTimeMillis();
407     }
408   }
409 
410   @Test
411   public void testCoDelScheduling() throws Exception {
412     CoDelEnvironmentEdge envEdge = new CoDelEnvironmentEdge();
413     envEdge.threadNamePrefixs.add("RpcServer.default.FPBQ.Codel.handler");
414     Configuration schedConf = HBaseConfiguration.create();
415     schedConf.setInt(RpcScheduler.IPC_SERVER_MAX_CALLQUEUE_LENGTH, 250);
416 
417     schedConf.set(RpcExecutor.CALL_QUEUE_TYPE_CONF_KEY,
418       RpcExecutor.CALL_QUEUE_TYPE_CODEL_CONF_VALUE);
419 
420     PriorityFunction priority = mock(PriorityFunction.class);
421     when(priority.getPriority(any(RPCProtos.RequestHeader.class), any(Message.class),
422       any(User.class))).thenReturn(HConstants.NORMAL_QOS);
423     SimpleRpcScheduler scheduler = new SimpleRpcScheduler(schedConf, 1, 1, 1, priority,
424       HConstants.QOS_THRESHOLD);
425     try {
426       scheduler.start();
427       EnvironmentEdgeManager.injectEdge(envEdge);
428       envEdge.offset = 5;
429       // calls faster than min delay
430       for (int i = 0; i < 100; i++) {
431         long time = System.currentTimeMillis();
432         envEdge.timeQ.put(time);
433         CallRunner cr = getMockedCallRunner(time, 2);
434         scheduler.dispatch(cr);
435       }
436       // make sure fast calls are handled
437       waitUntilQueueEmpty(scheduler);
438       Thread.sleep(100);
439       assertEquals("None of these calls should have been discarded", 0,
440         scheduler.getNumGeneralCallsDropped());
441 
442       envEdge.offset = 151;
443       // calls slower than min delay, but not individually slow enough to be dropped
444       for (int i = 0; i < 20; i++) {
445         long time = System.currentTimeMillis();
446         envEdge.timeQ.put(time);
447         CallRunner cr = getMockedCallRunner(time, 2);
448         scheduler.dispatch(cr);
449       }
450 
451       // make sure somewhat slow calls are handled
452       waitUntilQueueEmpty(scheduler);
453       Thread.sleep(100);
454       assertEquals("None of these calls should have been discarded", 0,
455         scheduler.getNumGeneralCallsDropped());
456 
457       envEdge.offset = 2000;
458       // now slow calls and the ones to be dropped
459       for (int i = 0; i < 60; i++) {
460         long time = System.currentTimeMillis();
461         envEdge.timeQ.put(time);
462         CallRunner cr = getMockedCallRunner(time, 100);
463         scheduler.dispatch(cr);
464       }
465 
466       // make sure somewhat slow calls are handled
467       waitUntilQueueEmpty(scheduler);
468       Thread.sleep(100);
469       assertTrue(
470           "There should have been at least 12 calls dropped however there were "
471               + scheduler.getNumGeneralCallsDropped(),
472           scheduler.getNumGeneralCallsDropped() > 12);
473     } finally {
474       scheduler.stop();
475     }
476   }
477 
478   // Get mocked call that has the CallRunner sleep for a while so that the fast
479   // path isn't hit.
480   private CallRunner getMockedCallRunner(long timestamp, final long sleepTime) throws IOException {
481     final RpcServer.Call putCall = mock(RpcServer.Call.class);
482 
483     putCall.timestamp = timestamp;
484     putCall.param = RequestConverter.buildMutateRequest(
485         Bytes.toBytes("abc"), new Put(Bytes.toBytes("row")));
486 
487     RPCProtos.RequestHeader putHead = RPCProtos.RequestHeader.newBuilder()
488                                                              .setMethodName("mutate")
489                                                              .build();
490     when(putCall.getSize()).thenReturn(9L);
491     when(putCall.getHeader()).thenReturn(putHead);
492 
493     CallRunner cr = new CallRunner(null, putCall) {
494       public void run() {
495         try {
496           LOG.warn("Sleeping for " + sleepTime);
497           Thread.sleep(sleepTime);
498           LOG.warn("Done Sleeping for " + sleepTime);
499         } catch (InterruptedException e) {
500         }
501       }
502       public Call getCall() {
503         return putCall;
504       }
505 
506       public void drop() {}
507     };
508 
509     return cr;
510   }
511 }