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.coprocessor;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.io.IOException;
25  import java.util.Collections;
26  import java.util.concurrent.ExecutorService;
27  import java.util.concurrent.SynchronousQueue;
28  import java.util.concurrent.ThreadPoolExecutor;
29  import java.util.concurrent.TimeUnit;
30  
31  import org.apache.hadoop.hbase.HBaseTestingUtility;
32  import org.apache.hadoop.hbase.HColumnDescriptor;
33  import org.apache.hadoop.hbase.HTableDescriptor;
34  import org.apache.hadoop.hbase.testclassification.MediumTests;
35  import org.apache.hadoop.hbase.TableName;
36  import org.apache.hadoop.hbase.client.Durability;
37  import org.apache.hadoop.hbase.client.HBaseAdmin;
38  import org.apache.hadoop.hbase.client.HTable;
39  import org.apache.hadoop.hbase.client.HTableInterface;
40  import org.apache.hadoop.hbase.client.Put;
41  import org.apache.hadoop.hbase.client.Result;
42  import org.apache.hadoop.hbase.client.ResultScanner;
43  import org.apache.hadoop.hbase.client.Scan;
44  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
45  import org.apache.hadoop.hbase.util.Threads;
46  import org.junit.After;
47  import org.junit.AfterClass;
48  import org.junit.BeforeClass;
49  import org.junit.Test;
50  import org.junit.experimental.categories.Category;
51  
52  /**
53   * Test that a coprocessor can open a connection and write to another table, inside a hook.
54   */
55  @Category(MediumTests.class)
56  public class TestOpenTableInCoprocessor {
57  
58    private static final TableName otherTable = TableName.valueOf("otherTable");
59    private static final TableName primaryTable = TableName.valueOf("primary");
60    private static final byte[] family = new byte[] { 'f' };
61  
62    private static boolean[] completed = new boolean[1];
63    /**
64     * Custom coprocessor that just copies the write to another table.
65     */
66    public static class SendToOtherTableCoprocessor extends BaseRegionObserver {
67  
68      @Override
69      public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put,
70          final WALEdit edit, final Durability durability) throws IOException {
71        HTableInterface table = e.getEnvironment().getTable(otherTable);
72        table.put(put);
73        table.flushCommits();
74        completed[0] = true;
75        table.close();
76      }
77  
78    }
79  
80    private static boolean[] completedWithPool = new boolean[1];
81    /**
82     * Coprocessor that creates an HTable with a pool to write to another table
83     */
84    public static class CustomThreadPoolCoprocessor extends BaseRegionObserver {
85  
86      /**
87       * Get a pool that has only ever one thread. A second action added to the pool (running
88       * concurrently), will cause an exception.
89       * @return
90       */
91      private ExecutorService getPool() {
92        int maxThreads = 1;
93        long keepAliveTime = 60;
94        ThreadPoolExecutor pool =
95            new ThreadPoolExecutor(1, maxThreads, keepAliveTime, TimeUnit.SECONDS,
96                new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("hbase-table"));
97        pool.allowCoreThreadTimeOut(true);
98        return pool;
99      }
100 
101     @Override
102     public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put,
103         final WALEdit edit, final Durability durability) throws IOException {
104       HTableInterface table = e.getEnvironment().getTable(otherTable, getPool());
105       Put p = new Put(new byte[] { 'a' });
106       p.add(family, null, new byte[] { 'a' });
107       try {
108         table.batch(Collections.singletonList(put));
109       } catch (InterruptedException e1) {
110         throw new IOException(e1);
111       }
112       completedWithPool[0] = true;
113       table.close();
114     }
115   }
116 
117   private static HBaseTestingUtility UTIL = new HBaseTestingUtility();
118 
119   @BeforeClass
120   public static void setupCluster() throws Exception {
121     UTIL.startMiniCluster();
122   }
123 
124   @After
125   public void cleanupTestTable() throws Exception {
126     UTIL.getHBaseAdmin().disableTable(primaryTable);
127     UTIL.getHBaseAdmin().deleteTable(primaryTable);
128 
129     UTIL.getHBaseAdmin().disableTable(otherTable);
130     UTIL.getHBaseAdmin().deleteTable(otherTable);
131 
132   }
133 
134   @AfterClass
135   public static void teardownCluster() throws Exception {
136     UTIL.shutdownMiniCluster();
137   }
138 
139   @Test
140   public void testCoprocessorCanCreateConnectionToRemoteTable() throws Throwable {
141     runCoprocessorConnectionToRemoteTable(SendToOtherTableCoprocessor.class, completed);
142   }
143 
144   @Test
145   public void testCoprocessorCanCreateConnectionToRemoteTableWithCustomPool() throws Throwable {
146     runCoprocessorConnectionToRemoteTable(CustomThreadPoolCoprocessor.class, completedWithPool);
147   }
148 
149   private void runCoprocessorConnectionToRemoteTable(Class<? extends BaseRegionObserver> clazz,
150       boolean[] completeCheck) throws Throwable {
151     HTableDescriptor primary = new HTableDescriptor(primaryTable);
152     primary.addFamily(new HColumnDescriptor(family));
153     // add our coprocessor
154     primary.addCoprocessor(clazz.getName());
155 
156     HTableDescriptor other = new HTableDescriptor(otherTable);
157     other.addFamily(new HColumnDescriptor(family));
158 
159 
160     HBaseAdmin admin = UTIL.getHBaseAdmin();
161     admin.createTable(primary);
162     admin.createTable(other);
163 
164     HTable table = new HTable(UTIL.getConfiguration(), "primary");
165     Put p = new Put(new byte[] { 'a' });
166     p.add(family, null, new byte[] { 'a' });
167     table.put(p);
168     table.flushCommits();
169     table.close();
170 
171     HTable target = new HTable(UTIL.getConfiguration(), otherTable);
172     assertTrue("Didn't complete update to target table!", completeCheck[0]);
173     assertEquals("Didn't find inserted row", 1, getKeyValueCount(target));
174     target.close();
175   }
176 
177   /**
178    * Count the number of keyvalue in the table. Scans all possible versions
179    * @param table table to scan
180    * @return number of keyvalues over all rows in the table
181    * @throws IOException
182    */
183   private int getKeyValueCount(HTable table) throws IOException {
184     Scan scan = new Scan();
185     scan.setMaxVersions(Integer.MAX_VALUE - 1);
186 
187     ResultScanner results = table.getScanner(scan);
188     int count = 0;
189     for (Result res : results) {
190       count += res.listCells().size();
191       System.out.println(count + ") " + res);
192     }
193     results.close();
194 
195     return count;
196   }
197 }