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  
19  package org.apache.hadoop.hbase.master.procedure;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.OutputStream;
24  import java.util.concurrent.atomic.AtomicInteger;
25  import java.util.concurrent.ConcurrentHashMap;
26  import java.util.ArrayList;
27  import java.util.HashSet;
28  import java.util.Map;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.HBaseConfiguration;
34  import org.apache.hadoop.hbase.TableName;
35  import org.apache.hadoop.hbase.master.TableLockManager;
36  import org.apache.hadoop.hbase.procedure2.Procedure;
37  import org.apache.hadoop.hbase.testclassification.SmallTests;
38  
39  import org.junit.After;
40  import org.junit.Assert;
41  import org.junit.Before;
42  import org.junit.Test;
43  import org.junit.experimental.categories.Category;
44  
45  import static org.junit.Assert.assertEquals;
46  import static org.junit.Assert.assertFalse;
47  import static org.junit.Assert.assertTrue;
48  import static org.junit.Assert.fail;
49  
50  @Category(SmallTests.class)
51  public class TestMasterProcedureQueue {
52    private static final Log LOG = LogFactory.getLog(TestMasterProcedureQueue.class);
53  
54    private MasterProcedureQueue queue;
55    private Configuration conf;
56  
57    @Before
58    public void setUp() throws IOException {
59      conf = HBaseConfiguration.create();
60      queue = new MasterProcedureQueue(conf, new TableLockManager.NullTableLockManager());
61    }
62  
63    @After
64    public void tearDown() throws IOException {
65      assertEquals(0, queue.size());
66    }
67  
68    /**
69     * Verify simple create/insert/fetch/delete of the table queue.
70     */
71    @Test
72    public void testSimpleTableOpsQueues() throws Exception {
73      final int NUM_TABLES = 10;
74      final int NUM_ITEMS = 10;
75  
76      int count = 0;
77      for (int i = 1; i <= NUM_TABLES; ++i) {
78        TableName tableName = TableName.valueOf(String.format("test-%04d", i));
79        // insert items
80        for (int j = 1; j <= NUM_ITEMS; ++j) {
81          queue.addBack(new TestTableProcedure(i * 1000 + j, tableName,
82            TableProcedureInterface.TableOperationType.EDIT));
83          assertEquals(++count, queue.size());
84        }
85      }
86      assertEquals(NUM_TABLES * NUM_ITEMS, queue.size());
87  
88      for (int j = 1; j <= NUM_ITEMS; ++j) {
89        for (int i = 1; i <= NUM_TABLES; ++i) {
90          Long procId = queue.poll();
91          assertEquals(--count, queue.size());
92          assertEquals(i * 1000 + j, procId.longValue());
93        }
94      }
95      assertEquals(0, queue.size());
96  
97      for (int i = 1; i <= NUM_TABLES; ++i) {
98        TableName tableName = TableName.valueOf(String.format("test-%04d", i));
99        // complete the table deletion
100       assertTrue(queue.markTableAsDeleted(tableName));
101     }
102   }
103 
104   /**
105    * Check that the table queue is not deletable until every procedure
106    * in-progress is completed (this is a special case for write-locks).
107    */
108   @Test
109   public void testCreateDeleteTableOperationsWithWriteLock() throws Exception {
110     TableName tableName = TableName.valueOf("testtb");
111 
112     queue.addBack(new TestTableProcedure(1, tableName,
113           TableProcedureInterface.TableOperationType.EDIT));
114 
115     // table can't be deleted because one item is in the queue
116     assertFalse(queue.markTableAsDeleted(tableName));
117 
118     // fetch item and take a lock
119     assertEquals(1, queue.poll().longValue());
120     // take the xlock
121     assertTrue(queue.tryAcquireTableWrite(tableName, "write"));
122     // table can't be deleted because we have the lock
123     assertEquals(0, queue.size());
124     assertFalse(queue.markTableAsDeleted(tableName));
125     // release the xlock
126     queue.releaseTableWrite(tableName);
127     // complete the table deletion
128     assertTrue(queue.markTableAsDeleted(tableName));
129   }
130 
131   /**
132    * Check that the table queue is not deletable until every procedure
133    * in-progress is completed (this is a special case for read-locks).
134    */
135   @Test
136   public void testCreateDeleteTableOperationsWithReadLock() throws Exception {
137     final TableName tableName = TableName.valueOf("testtb");
138     final int nitems = 2;
139 
140     for (int i = 1; i <= nitems; ++i) {
141       queue.addBack(new TestTableProcedure(i, tableName,
142             TableProcedureInterface.TableOperationType.READ));
143     }
144 
145     // table can't be deleted because one item is in the queue
146     assertFalse(queue.markTableAsDeleted(tableName));
147 
148     for (int i = 1; i <= nitems; ++i) {
149       // fetch item and take a lock
150       assertEquals(i, queue.poll().longValue());
151       // take the rlock
152       assertTrue(queue.tryAcquireTableRead(tableName, "read " + i));
153       // table can't be deleted because we have locks and/or items in the queue
154       assertFalse(queue.markTableAsDeleted(tableName));
155     }
156 
157     for (int i = 1; i <= nitems; ++i) {
158       // table can't be deleted because we have locks
159       assertFalse(queue.markTableAsDeleted(tableName));
160       // release the rlock
161       queue.releaseTableRead(tableName);
162     }
163 
164     // there are no items and no lock in the queeu
165     assertEquals(0, queue.size());
166     // complete the table deletion
167     assertTrue(queue.markTableAsDeleted(tableName));
168   }
169 
170   /**
171    * Verify the correct logic of RWLocks on the queue
172    */
173   @Test
174   public void testVerifyRwLocks() throws Exception {
175     TableName tableName = TableName.valueOf("testtb");
176     queue.addBack(new TestTableProcedure(1, tableName,
177           TableProcedureInterface.TableOperationType.EDIT));
178     queue.addBack(new TestTableProcedure(2, tableName,
179           TableProcedureInterface.TableOperationType.READ));
180     queue.addBack(new TestTableProcedure(3, tableName,
181           TableProcedureInterface.TableOperationType.EDIT));
182     queue.addBack(new TestTableProcedure(4, tableName,
183           TableProcedureInterface.TableOperationType.READ));
184     queue.addBack(new TestTableProcedure(5, tableName,
185           TableProcedureInterface.TableOperationType.READ));
186 
187     // Fetch the 1st item and take the write lock
188     Long procId = queue.poll();
189     assertEquals(1, procId.longValue());
190     assertEquals(true, queue.tryAcquireTableWrite(tableName, "write " + procId));
191 
192     // Fetch the 2nd item and verify that the lock can't be acquired
193     assertEquals(null, queue.poll());
194 
195     // Release the write lock and acquire the read lock
196     queue.releaseTableWrite(tableName);
197 
198     // Fetch the 2nd item and take the read lock
199     procId = queue.poll();
200     assertEquals(2, procId.longValue());
201     assertEquals(true, queue.tryAcquireTableRead(tableName, "read " + procId));
202 
203     // Fetch the 3rd item and verify that the lock can't be acquired
204     procId = queue.poll();
205     assertEquals(3, procId.longValue());
206     assertEquals(false, queue.tryAcquireTableWrite(tableName, "write " + procId));
207 
208     // release the rdlock of item 2 and take the wrlock for the 3d item
209     queue.releaseTableRead(tableName);
210     assertEquals(true, queue.tryAcquireTableWrite(tableName, "write " + procId));
211 
212     // Fetch 4th item and verify that the lock can't be acquired
213     assertEquals(null, queue.poll());
214 
215     // Release the write lock and acquire the read lock
216     queue.releaseTableWrite(tableName);
217 
218     // Fetch the 4th item and take the read lock
219     procId = queue.poll();
220     assertEquals(4, procId.longValue());
221     assertEquals(true, queue.tryAcquireTableRead(tableName, "read " + procId));
222 
223     // Fetch the 4th item and take the read lock
224     procId = queue.poll();
225     assertEquals(5, procId.longValue());
226     assertEquals(true, queue.tryAcquireTableRead(tableName, "read " + procId));
227 
228     // Release 4th and 5th read-lock
229     queue.releaseTableRead(tableName);
230     queue.releaseTableRead(tableName);
231 
232     // remove table queue
233     assertEquals(0, queue.size());
234     assertTrue("queue should be deleted", queue.markTableAsDeleted(tableName));
235   }
236 
237   /**
238    * Verify that "write" operations for a single table are serialized,
239    * but different tables can be executed in parallel.
240    */
241   @Test(timeout=90000)
242   public void testConcurrentWriteOps() throws Exception {
243     final TestTableProcSet procSet = new TestTableProcSet(queue);
244 
245     final int NUM_ITEMS = 10;
246     final int NUM_TABLES = 4;
247     final AtomicInteger opsCount = new AtomicInteger(0);
248     for (int i = 0; i < NUM_TABLES; ++i) {
249       TableName tableName = TableName.valueOf(String.format("testtb-%04d", i));
250       for (int j = 1; j < NUM_ITEMS; ++j) {
251         procSet.addBack(new TestTableProcedure(i * 100 + j, tableName,
252           TableProcedureInterface.TableOperationType.EDIT));
253         opsCount.incrementAndGet();
254       }
255     }
256     assertEquals(opsCount.get(), queue.size());
257 
258     final Thread[] threads = new Thread[NUM_TABLES * 2];
259     final HashSet<TableName> concurrentTables = new HashSet<TableName>();
260     final ArrayList<String> failures = new ArrayList<String>();
261     final AtomicInteger concurrentCount = new AtomicInteger(0);
262     for (int i = 0; i < threads.length; ++i) {
263       threads[i] = new Thread() {
264         @Override
265         public void run() {
266           while (opsCount.get() > 0) {
267             try {
268               TableProcedureInterface proc = procSet.acquire();
269               if (proc == null) {
270                 queue.signalAll();
271                 if (opsCount.get() > 0) {
272                   continue;
273                 }
274                 break;
275               }
276               synchronized (concurrentTables) {
277                 assertTrue("unexpected concurrency on " + proc.getTableName(),
278                   concurrentTables.add(proc.getTableName()));
279               }
280               assertTrue(opsCount.decrementAndGet() >= 0);
281               try {
282                 long procId = ((Procedure)proc).getProcId();
283                 TableName tableId = proc.getTableName();
284                 int concurrent = concurrentCount.incrementAndGet();
285                 assertTrue("inc-concurrent="+ concurrent +" 1 <= concurrent <= "+ NUM_TABLES,
286                   concurrent >= 1 && concurrent <= NUM_TABLES);
287                 LOG.debug("[S] tableId="+ tableId +" procId="+ procId +" concurrent="+ concurrent);
288                 Thread.sleep(2000);
289                 concurrent = concurrentCount.decrementAndGet();
290                 LOG.debug("[E] tableId="+ tableId +" procId="+ procId +" concurrent="+ concurrent);
291                 assertTrue("dec-concurrent=" + concurrent, concurrent < NUM_TABLES);
292               } finally {
293                 synchronized (concurrentTables) {
294                   assertTrue(concurrentTables.remove(proc.getTableName()));
295                 }
296                 procSet.release(proc);
297               }
298             } catch (Throwable e) {
299               LOG.error("Failed " + e.getMessage(), e);
300               synchronized (failures) {
301                 failures.add(e.getMessage());
302               }
303             } finally {
304               queue.signalAll();
305             }
306           }
307         }
308       };
309       threads[i].start();
310     }
311     for (int i = 0; i < threads.length; ++i) {
312       threads[i].join();
313     }
314     assertTrue(failures.toString(), failures.isEmpty());
315     assertEquals(0, opsCount.get());
316     assertEquals(0, queue.size());
317 
318     for (int i = 1; i <= NUM_TABLES; ++i) {
319       TableName table = TableName.valueOf(String.format("testtb-%04d", i));
320       assertTrue("queue should be deleted, table=" + table, queue.markTableAsDeleted(table));
321     }
322   }
323 
324   public static class TestTableProcSet {
325     private final MasterProcedureQueue queue;
326     private Map<Long, TableProcedureInterface> procsMap =
327       new ConcurrentHashMap<Long, TableProcedureInterface>();
328 
329     public TestTableProcSet(final MasterProcedureQueue queue) {
330       this.queue = queue;
331     }
332 
333     public void addBack(TableProcedureInterface tableProc) {
334       Procedure proc = (Procedure)tableProc;
335       procsMap.put(proc.getProcId(), tableProc);
336       queue.addBack(proc);
337     }
338 
339     public void addFront(TableProcedureInterface tableProc) {
340       Procedure proc = (Procedure)tableProc;
341       procsMap.put(proc.getProcId(), tableProc);
342       queue.addFront(proc);
343     }
344 
345     public TableProcedureInterface acquire() {
346       TableProcedureInterface proc = null;
347       boolean avail = false;
348       while (!avail) {
349         Long procId = queue.poll();
350         proc = procId != null ? procsMap.remove(procId) : null;
351         if (proc == null) break;
352         switch (proc.getTableOperationType()) {
353           case CREATE:
354           case DELETE:
355           case EDIT:
356             avail = queue.tryAcquireTableWrite(proc.getTableName(),
357               "op="+ proc.getTableOperationType());
358             break;
359           case READ:
360             avail = queue.tryAcquireTableRead(proc.getTableName(),
361               "op="+ proc.getTableOperationType());
362             break;
363         }
364         if (!avail) {
365           addFront(proc);
366           LOG.debug("yield procId=" + procId);
367         }
368       }
369       return proc;
370     }
371 
372     public void release(TableProcedureInterface proc) {
373       switch (proc.getTableOperationType()) {
374         case CREATE:
375         case DELETE:
376         case EDIT:
377           queue.releaseTableWrite(proc.getTableName());
378           break;
379         case READ:
380           queue.releaseTableRead(proc.getTableName());
381           break;
382       }
383     }
384   }
385 
386   public static class TestTableProcedure extends Procedure<Void>
387       implements TableProcedureInterface {
388     private final TableOperationType opType;
389     private final TableName tableName;
390 
391     public TestTableProcedure() {
392       throw new UnsupportedOperationException("recovery should not be triggered here");
393     }
394 
395     public TestTableProcedure(long procId, TableName tableName, TableOperationType opType) {
396       this.tableName = tableName;
397       this.opType = opType;
398       setProcId(procId);
399     }
400 
401     @Override
402     public TableName getTableName() {
403       return tableName;
404     }
405 
406     @Override
407     public TableOperationType getTableOperationType() {
408       return opType;
409     }
410 
411     @Override
412     protected Procedure[] execute(Void env) {
413       return null;
414     }
415 
416     @Override
417     protected void rollback(Void env) {
418       throw new UnsupportedOperationException();
419     }
420 
421     @Override
422     protected boolean abort(Void env) {
423       throw new UnsupportedOperationException();
424     }
425 
426     @Override
427     protected void serializeStateData(final OutputStream stream) throws IOException {}
428 
429     @Override
430     protected void deserializeStateData(final InputStream stream) throws IOException {}
431   }
432 }