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.coprocessor;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertTrue;
024
025import java.io.File;
026import java.io.IOException;
027import java.util.Arrays;
028import java.util.HashMap;
029import java.util.HashSet;
030import java.util.Map;
031import java.util.Optional;
032import java.util.Set;
033import org.apache.hadoop.conf.Configuration;
034import org.apache.hadoop.fs.FileSystem;
035import org.apache.hadoop.fs.Path;
036import org.apache.hadoop.hbase.Coprocessor;
037import org.apache.hadoop.hbase.CoprocessorEnvironment;
038import org.apache.hadoop.hbase.HBaseClassTestRule;
039import org.apache.hadoop.hbase.HBaseTestingUtility;
040import org.apache.hadoop.hbase.HColumnDescriptor;
041import org.apache.hadoop.hbase.HTableDescriptor;
042import org.apache.hadoop.hbase.MiniHBaseCluster;
043import org.apache.hadoop.hbase.RegionMetrics;
044import org.apache.hadoop.hbase.ServerMetrics;
045import org.apache.hadoop.hbase.ServerName;
046import org.apache.hadoop.hbase.TableName;
047import org.apache.hadoop.hbase.client.Admin;
048import org.apache.hadoop.hbase.regionserver.HRegion;
049import org.apache.hadoop.hbase.regionserver.Region;
050import org.apache.hadoop.hbase.regionserver.TestServerCustomProtocol;
051import org.apache.hadoop.hbase.testclassification.CoprocessorTests;
052import org.apache.hadoop.hbase.testclassification.MediumTests;
053import org.apache.hadoop.hbase.util.ClassLoaderTestHelper;
054import org.apache.hadoop.hbase.util.CoprocessorClassLoader;
055import org.apache.hadoop.hdfs.MiniDFSCluster;
056import org.junit.AfterClass;
057import org.junit.BeforeClass;
058import org.junit.ClassRule;
059import org.junit.Test;
060import org.junit.experimental.categories.Category;
061import org.slf4j.Logger;
062import org.slf4j.LoggerFactory;
063
064/**
065 * Test coprocessors class loading.
066 */
067@Category({CoprocessorTests.class, MediumTests.class})
068public class TestClassLoading {
069
070  @ClassRule
071  public static final HBaseClassTestRule CLASS_RULE =
072      HBaseClassTestRule.forClass(TestClassLoading.class);
073
074  private static final Logger LOG = LoggerFactory.getLogger(TestClassLoading.class);
075  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
076
077  public static class TestMasterCoprocessor implements MasterCoprocessor, MasterObserver {
078    @Override
079    public Optional<MasterObserver> getMasterObserver() {
080      return Optional.of(this);
081    }
082  }
083
084  private static MiniDFSCluster cluster;
085
086  static final TableName tableName = TableName.valueOf("TestClassLoading");
087  static final String cpName1 = "TestCP1";
088  static final String cpName2 = "TestCP2";
089  static final String cpName3 = "TestCP3";
090  static final String cpName4 = "TestCP4";
091  static final String cpName5 = "TestCP5";
092  static final String cpName6 = "TestCP6";
093
094  private static Class<?> regionCoprocessor1 = ColumnAggregationEndpoint.class;
095  // TOOD: Fix the import of this handler.  It is coming in from a package that is far away.
096  private static Class<?> regionCoprocessor2 = TestServerCustomProtocol.PingHandler.class;
097  private static Class<?> regionServerCoprocessor = SampleRegionWALCoprocessor.class;
098  private static Class<?> masterCoprocessor = TestMasterCoprocessor.class;
099
100  private static final String[] regionServerSystemCoprocessors =
101      new String[]{
102      regionServerCoprocessor.getSimpleName()
103  };
104
105  private static final String[] masterRegionServerSystemCoprocessors = new String[] {
106      regionCoprocessor1.getSimpleName(), MultiRowMutationEndpoint.class.getSimpleName(),
107      regionServerCoprocessor.getSimpleName() };
108
109  @BeforeClass
110  public static void setUpBeforeClass() throws Exception {
111    Configuration conf = TEST_UTIL.getConfiguration();
112
113    // regionCoprocessor1 will be loaded on all regionservers, since it is
114    // loaded for any tables (user or meta).
115    conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
116        regionCoprocessor1.getName());
117
118    // regionCoprocessor2 will be loaded only on regionservers that serve a
119    // user table region. Therefore, if there are no user tables loaded,
120    // this coprocessor will not be loaded on any regionserver.
121    conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
122        regionCoprocessor2.getName());
123
124    conf.setStrings(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY,
125        regionServerCoprocessor.getName());
126    conf.setStrings(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
127        masterCoprocessor.getName());
128    TEST_UTIL.startMiniCluster(1);
129    cluster = TEST_UTIL.getDFSCluster();
130  }
131
132  @AfterClass
133  public static void tearDownAfterClass() throws Exception {
134    TEST_UTIL.shutdownMiniCluster();
135  }
136
137  static File buildCoprocessorJar(String className) throws Exception {
138    String code =
139        "import org.apache.hadoop.hbase.coprocessor.*;" +
140            "public class " + className + " implements RegionCoprocessor {}";
141    return ClassLoaderTestHelper.buildJar(
142      TEST_UTIL.getDataTestDir().toString(), className, code);
143  }
144
145  @Test
146  // HBASE-3516: Test CP Class loading from HDFS
147  public void testClassLoadingFromHDFS() throws Exception {
148    FileSystem fs = cluster.getFileSystem();
149
150    File jarFile1 = buildCoprocessorJar(cpName1);
151    File jarFile2 = buildCoprocessorJar(cpName2);
152
153    // copy the jars into dfs
154    fs.copyFromLocalFile(new Path(jarFile1.getPath()),
155      new Path(fs.getUri().toString() + Path.SEPARATOR));
156    String jarFileOnHDFS1 = fs.getUri().toString() + Path.SEPARATOR +
157      jarFile1.getName();
158    Path pathOnHDFS1 = new Path(jarFileOnHDFS1);
159    assertTrue("Copy jar file to HDFS failed.",
160      fs.exists(pathOnHDFS1));
161    LOG.info("Copied jar file to HDFS: " + jarFileOnHDFS1);
162
163    fs.copyFromLocalFile(new Path(jarFile2.getPath()),
164        new Path(fs.getUri().toString() + Path.SEPARATOR));
165    String jarFileOnHDFS2 = fs.getUri().toString() + Path.SEPARATOR +
166      jarFile2.getName();
167    Path pathOnHDFS2 = new Path(jarFileOnHDFS2);
168    assertTrue("Copy jar file to HDFS failed.",
169      fs.exists(pathOnHDFS2));
170    LOG.info("Copied jar file to HDFS: " + jarFileOnHDFS2);
171
172    // create a table that references the coprocessors
173    HTableDescriptor htd = new HTableDescriptor(tableName);
174    htd.addFamily(new HColumnDescriptor("test"));
175      // without configuration values
176    htd.setValue("COPROCESSOR$1", jarFileOnHDFS1.toString() + "|" + cpName1 +
177      "|" + Coprocessor.PRIORITY_USER);
178      // with configuration values
179    htd.setValue("COPROCESSOR$2", jarFileOnHDFS2.toString() + "|" + cpName2 +
180      "|" + Coprocessor.PRIORITY_USER + "|k1=v1,k2=v2,k3=v3");
181    Admin admin = TEST_UTIL.getAdmin();
182    if (admin.tableExists(tableName)) {
183      if (admin.isTableEnabled(tableName)) {
184        admin.disableTable(tableName);
185      }
186      admin.deleteTable(tableName);
187    }
188    CoprocessorClassLoader.clearCache();
189    byte[] startKey = {10, 63};
190    byte[] endKey = {12, 43};
191    admin.createTable(htd, startKey, endKey, 4);
192    waitForTable(htd.getTableName());
193
194    // verify that the coprocessors were loaded
195    boolean foundTableRegion=false;
196    boolean found1 = true, found2 = true, found2_k1 = true, found2_k2 = true, found2_k3 = true;
197    Map<Region, Set<ClassLoader>> regionsActiveClassLoaders = new HashMap<>();
198    MiniHBaseCluster hbase = TEST_UTIL.getHBaseCluster();
199    for (HRegion region:
200        hbase.getRegionServer(0).getOnlineRegionsLocalContext()) {
201      if (region.getRegionInfo().getRegionNameAsString().startsWith(tableName.getNameAsString())) {
202        foundTableRegion = true;
203        CoprocessorEnvironment env;
204        env = region.getCoprocessorHost().findCoprocessorEnvironment(cpName1);
205        found1 = found1 && (env != null);
206        env = region.getCoprocessorHost().findCoprocessorEnvironment(cpName2);
207        found2 = found2 && (env != null);
208        if (env != null) {
209          Configuration conf = env.getConfiguration();
210          found2_k1 = found2_k1 && (conf.get("k1") != null);
211          found2_k2 = found2_k2 && (conf.get("k2") != null);
212          found2_k3 = found2_k3 && (conf.get("k3") != null);
213        } else {
214          found2_k1 = found2_k2 = found2_k3 = false;
215        }
216        regionsActiveClassLoaders
217            .put(region, ((CoprocessorHost) region.getCoprocessorHost()).getExternalClassLoaders());
218      }
219    }
220
221    assertTrue("No region was found for table " + tableName, foundTableRegion);
222    assertTrue("Class " + cpName1 + " was missing on a region", found1);
223    assertTrue("Class " + cpName2 + " was missing on a region", found2);
224    assertTrue("Configuration key 'k1' was missing on a region", found2_k1);
225    assertTrue("Configuration key 'k2' was missing on a region", found2_k2);
226    assertTrue("Configuration key 'k3' was missing on a region", found2_k3);
227    // check if CP classloaders are cached
228    assertNotNull(jarFileOnHDFS1 + " was not cached",
229      CoprocessorClassLoader.getIfCached(pathOnHDFS1));
230    assertNotNull(jarFileOnHDFS2 + " was not cached",
231      CoprocessorClassLoader.getIfCached(pathOnHDFS2));
232    //two external jar used, should be one classloader per jar
233    assertEquals("The number of cached classloaders should be equal to the number" +
234      " of external jar files",
235      2, CoprocessorClassLoader.getAllCached().size());
236    //check if region active classloaders are shared across all RS regions
237    Set<ClassLoader> externalClassLoaders = new HashSet<>(
238      CoprocessorClassLoader.getAllCached());
239    for (Map.Entry<Region, Set<ClassLoader>> regionCP : regionsActiveClassLoaders.entrySet()) {
240      assertTrue("Some CP classloaders for region " + regionCP.getKey() + " are not cached."
241        + " ClassLoader Cache:" + externalClassLoaders
242        + " Region ClassLoaders:" + regionCP.getValue(),
243        externalClassLoaders.containsAll(regionCP.getValue()));
244    }
245  }
246
247  private String getLocalPath(File file) {
248    return new Path(file.toURI()).toString();
249  }
250
251  @Test
252  // HBASE-3516: Test CP Class loading from local file system
253  public void testClassLoadingFromLocalFS() throws Exception {
254    File jarFile = buildCoprocessorJar(cpName3);
255
256    // create a table that references the jar
257    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(cpName3));
258    htd.addFamily(new HColumnDescriptor("test"));
259    htd.setValue("COPROCESSOR$1", getLocalPath(jarFile) + "|" + cpName3 + "|" +
260      Coprocessor.PRIORITY_USER);
261    Admin admin = TEST_UTIL.getAdmin();
262    admin.createTable(htd);
263    waitForTable(htd.getTableName());
264
265    // verify that the coprocessor was loaded
266    boolean found = false;
267    MiniHBaseCluster hbase = TEST_UTIL.getHBaseCluster();
268    for (HRegion region: hbase.getRegionServer(0).getOnlineRegionsLocalContext()) {
269      if (region.getRegionInfo().getRegionNameAsString().startsWith(cpName3)) {
270        found = (region.getCoprocessorHost().findCoprocessor(cpName3) != null);
271      }
272    }
273    assertTrue("Class " + cpName3 + " was missing on a region", found);
274  }
275
276  @Test
277  // HBASE-6308: Test CP classloader is the CoprocessorClassLoader
278  public void testPrivateClassLoader() throws Exception {
279    File jarFile = buildCoprocessorJar(cpName4);
280
281    // create a table that references the jar
282    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(cpName4));
283    htd.addFamily(new HColumnDescriptor("test"));
284    htd.setValue("COPROCESSOR$1", getLocalPath(jarFile) + "|" + cpName4 + "|" +
285      Coprocessor.PRIORITY_USER);
286    Admin admin = TEST_UTIL.getAdmin();
287    admin.createTable(htd);
288    waitForTable(htd.getTableName());
289
290    // verify that the coprocessor was loaded correctly
291    boolean found = false;
292    MiniHBaseCluster hbase = TEST_UTIL.getHBaseCluster();
293    for (HRegion region: hbase.getRegionServer(0).getOnlineRegionsLocalContext()) {
294      if (region.getRegionInfo().getRegionNameAsString().startsWith(cpName4)) {
295        Coprocessor cp = region.getCoprocessorHost().findCoprocessor(cpName4);
296        if (cp != null) {
297          found = true;
298          assertEquals("Class " + cpName4 + " was not loaded by CoprocessorClassLoader",
299            cp.getClass().getClassLoader().getClass(), CoprocessorClassLoader.class);
300        }
301      }
302    }
303    assertTrue("Class " + cpName4 + " was missing on a region", found);
304  }
305
306  @Test
307  // HBase-3810: Registering a Coprocessor at HTableDescriptor should be
308  // less strict
309  public void testHBase3810() throws Exception {
310    // allowed value pattern: [path] | class name | [priority] | [key values]
311
312    File jarFile1 = buildCoprocessorJar(cpName1);
313    File jarFile2 = buildCoprocessorJar(cpName2);
314    File jarFile5 = buildCoprocessorJar(cpName5);
315    File jarFile6 = buildCoprocessorJar(cpName6);
316
317    String cpKey1 = "COPROCESSOR$1";
318    String cpKey2 = " Coprocessor$2 ";
319    String cpKey3 = " coprocessor$03 ";
320
321    String cpValue1 = getLocalPath(jarFile1) + "|" + cpName1 + "|" +
322        Coprocessor.PRIORITY_USER;
323    String cpValue2 = getLocalPath(jarFile2) + " | " + cpName2 + " | ";
324    // load from default class loader
325    String cpValue3 =
326        " | org.apache.hadoop.hbase.coprocessor.SimpleRegionObserver | | k=v ";
327
328    // create a table that references the jar
329    HTableDescriptor htd = new HTableDescriptor(tableName);
330    htd.addFamily(new HColumnDescriptor("test"));
331
332    // add 3 coprocessors by setting htd attributes directly.
333    htd.setValue(cpKey1, cpValue1);
334    htd.setValue(cpKey2, cpValue2);
335    htd.setValue(cpKey3, cpValue3);
336
337    // add 2 coprocessor by using new htd.setCoprocessor() api
338    htd.addCoprocessor(cpName5, new Path(getLocalPath(jarFile5)),
339        Coprocessor.PRIORITY_USER, null);
340    Map<String, String> kvs = new HashMap<>();
341    kvs.put("k1", "v1");
342    kvs.put("k2", "v2");
343    kvs.put("k3", "v3");
344    htd.addCoprocessor(cpName6, new Path(getLocalPath(jarFile6)),
345        Coprocessor.PRIORITY_USER, kvs);
346
347    Admin admin = TEST_UTIL.getAdmin();
348    if (admin.tableExists(tableName)) {
349      if (admin.isTableEnabled(tableName)) {
350        admin.disableTable(tableName);
351      }
352      admin.deleteTable(tableName);
353    }
354    admin.createTable(htd);
355    waitForTable(htd.getTableName());
356
357    // verify that the coprocessor was loaded
358    boolean found_2 = false, found_1 = false, found_3 = false,
359        found_5 = false, found_6 = false;
360    boolean found6_k1 = false, found6_k2 = false, found6_k3 = false,
361        found6_k4 = false;
362
363    MiniHBaseCluster hbase = TEST_UTIL.getHBaseCluster();
364    for (HRegion region: hbase.getRegionServer(0).getOnlineRegionsLocalContext()) {
365      if (region.getRegionInfo().getRegionNameAsString().startsWith(tableName.getNameAsString())) {
366        found_1 = found_1 ||
367            (region.getCoprocessorHost().findCoprocessor(cpName1) != null);
368        found_2 = found_2 ||
369            (region.getCoprocessorHost().findCoprocessor(cpName2) != null);
370        found_3 = found_3 ||
371            (region.getCoprocessorHost().findCoprocessor("SimpleRegionObserver")
372                != null);
373        found_5 = found_5 ||
374            (region.getCoprocessorHost().findCoprocessor(cpName5) != null);
375
376        CoprocessorEnvironment env =
377            region.getCoprocessorHost().findCoprocessorEnvironment(cpName6);
378        if (env != null) {
379          found_6 = true;
380          Configuration conf = env.getConfiguration();
381          found6_k1 = conf.get("k1") != null;
382          found6_k2 = conf.get("k2") != null;
383          found6_k3 = conf.get("k3") != null;
384        }
385      }
386    }
387
388    assertTrue("Class " + cpName1 + " was missing on a region", found_1);
389    assertTrue("Class " + cpName2 + " was missing on a region", found_2);
390    assertTrue("Class SimpleRegionObserver was missing on a region", found_3);
391    assertTrue("Class " + cpName5 + " was missing on a region", found_5);
392    assertTrue("Class " + cpName6 + " was missing on a region", found_6);
393
394    assertTrue("Configuration key 'k1' was missing on a region", found6_k1);
395    assertTrue("Configuration key 'k2' was missing on a region", found6_k2);
396    assertTrue("Configuration key 'k3' was missing on a region", found6_k3);
397    assertFalse("Configuration key 'k4' wasn't configured", found6_k4);
398  }
399
400  @Test
401  public void testClassLoadingFromLibDirInJar() throws Exception {
402    loadingClassFromLibDirInJar("/lib/");
403  }
404
405  @Test
406  public void testClassLoadingFromRelativeLibDirInJar() throws Exception {
407    loadingClassFromLibDirInJar("lib/");
408  }
409
410  void loadingClassFromLibDirInJar(String libPrefix) throws Exception {
411    FileSystem fs = cluster.getFileSystem();
412
413    File innerJarFile1 = buildCoprocessorJar(cpName1);
414    File innerJarFile2 = buildCoprocessorJar(cpName2);
415    File outerJarFile = new File(TEST_UTIL.getDataTestDir().toString(), "outer.jar");
416
417    ClassLoaderTestHelper.addJarFilesToJar(
418      outerJarFile, libPrefix, innerJarFile1, innerJarFile2);
419
420    // copy the jars into dfs
421    fs.copyFromLocalFile(new Path(outerJarFile.getPath()),
422      new Path(fs.getUri().toString() + Path.SEPARATOR));
423    String jarFileOnHDFS = fs.getUri().toString() + Path.SEPARATOR +
424      outerJarFile.getName();
425    assertTrue("Copy jar file to HDFS failed.",
426      fs.exists(new Path(jarFileOnHDFS)));
427    LOG.info("Copied jar file to HDFS: " + jarFileOnHDFS);
428
429    // create a table that references the coprocessors
430    HTableDescriptor htd = new HTableDescriptor(tableName);
431    htd.addFamily(new HColumnDescriptor("test"));
432      // without configuration values
433    htd.setValue("COPROCESSOR$1", jarFileOnHDFS.toString() + "|" + cpName1 +
434      "|" + Coprocessor.PRIORITY_USER);
435      // with configuration values
436    htd.setValue("COPROCESSOR$2", jarFileOnHDFS.toString() + "|" + cpName2 +
437      "|" + Coprocessor.PRIORITY_USER + "|k1=v1,k2=v2,k3=v3");
438    Admin admin = TEST_UTIL.getAdmin();
439    if (admin.tableExists(tableName)) {
440      if (admin.isTableEnabled(tableName)) {
441        admin.disableTable(tableName);
442      }
443      admin.deleteTable(tableName);
444    }
445    admin.createTable(htd);
446    waitForTable(htd.getTableName());
447
448    // verify that the coprocessors were loaded
449    boolean found1 = false, found2 = false, found2_k1 = false,
450        found2_k2 = false, found2_k3 = false;
451    MiniHBaseCluster hbase = TEST_UTIL.getHBaseCluster();
452    for (HRegion region: hbase.getRegionServer(0).getOnlineRegionsLocalContext()) {
453      if (region.getRegionInfo().getRegionNameAsString().startsWith(tableName.getNameAsString())) {
454        CoprocessorEnvironment env;
455        env = region.getCoprocessorHost().findCoprocessorEnvironment(cpName1);
456        if (env != null) {
457          found1 = true;
458        }
459        env = region.getCoprocessorHost().findCoprocessorEnvironment(cpName2);
460        if (env != null) {
461          found2 = true;
462          Configuration conf = env.getConfiguration();
463          found2_k1 = conf.get("k1") != null;
464          found2_k2 = conf.get("k2") != null;
465          found2_k3 = conf.get("k3") != null;
466        }
467      }
468    }
469    assertTrue("Class " + cpName1 + " was missing on a region", found1);
470    assertTrue("Class " + cpName2 + " was missing on a region", found2);
471    assertTrue("Configuration key 'k1' was missing on a region", found2_k1);
472    assertTrue("Configuration key 'k2' was missing on a region", found2_k2);
473    assertTrue("Configuration key 'k3' was missing on a region", found2_k3);
474  }
475
476  @Test
477  public void testRegionServerCoprocessorsReported() throws Exception {
478    // This was a test for HBASE-4070.
479    // We are removing coprocessors from region load in HBASE-5258.
480    // Therefore, this test now only checks system coprocessors.
481    assertAllRegionServers(null);
482  }
483
484  /**
485   * return the subset of all regionservers
486   * (actually returns set of ServerLoads)
487   * which host some region in a given table.
488   * used by assertAllRegionServers() below to
489   * test reporting of loaded coprocessors.
490   * @param tableName : given table.
491   * @return subset of all servers.
492   */
493  Map<ServerName, ServerMetrics> serversForTable(String tableName) {
494    Map<ServerName, ServerMetrics> serverLoadHashMap = new HashMap<>();
495    for(Map.Entry<ServerName, ServerMetrics> server:
496        TEST_UTIL.getMiniHBaseCluster().getMaster().getServerManager().
497            getOnlineServers().entrySet()) {
498      for(Map.Entry<byte[], RegionMetrics> region:
499          server.getValue().getRegionMetrics().entrySet()) {
500        if (region.getValue().getNameAsString().equals(tableName)) {
501          // this server hosts a region of tableName: add this server..
502          serverLoadHashMap.put(server.getKey(),server.getValue());
503          // .. and skip the rest of the regions that it hosts.
504          break;
505        }
506      }
507    }
508    return serverLoadHashMap;
509  }
510
511  void assertAllRegionServers(String tableName) throws InterruptedException {
512    Map<ServerName, ServerMetrics> servers;
513    boolean success = false;
514    String[] expectedCoprocessors = regionServerSystemCoprocessors;
515    if (tableName == null) {
516      // if no tableName specified, use all servers.
517      servers = TEST_UTIL.getMiniHBaseCluster().getMaster().getServerManager().getOnlineServers();
518    } else {
519      servers = serversForTable(tableName);
520    }
521    for (int i = 0; i < 5; i++) {
522      boolean any_failed = false;
523      for(Map.Entry<ServerName, ServerMetrics> server: servers.entrySet()) {
524        String[] actualCoprocessors =
525          server.getValue().getCoprocessorNames().stream().toArray(size -> new String[size]);
526        if (!Arrays.equals(actualCoprocessors, expectedCoprocessors)) {
527          LOG.debug("failed comparison: actual: " +
528              Arrays.toString(actualCoprocessors) +
529              " ; expected: " + Arrays.toString(expectedCoprocessors));
530          any_failed = true;
531          expectedCoprocessors = switchExpectedCoprocessors(expectedCoprocessors);
532          break;
533        }
534        expectedCoprocessors = switchExpectedCoprocessors(expectedCoprocessors);
535      }
536      if (any_failed == false) {
537        success = true;
538        break;
539      }
540      LOG.debug("retrying after failed comparison: " + i);
541      Thread.sleep(1000);
542    }
543    assertTrue(success);
544  }
545
546  private String[] switchExpectedCoprocessors(String[] expectedCoprocessors) {
547    if (Arrays.equals(regionServerSystemCoprocessors, expectedCoprocessors)) {
548      expectedCoprocessors = masterRegionServerSystemCoprocessors;
549    } else {
550      expectedCoprocessors = regionServerSystemCoprocessors;
551    }
552    return expectedCoprocessors;
553  }
554
555  @Test
556  public void testMasterCoprocessorsReported() {
557    // HBASE 4070: Improve region server metrics to report loaded coprocessors
558    // to master: verify that the master is reporting the correct set of
559    // loaded coprocessors.
560    final String loadedMasterCoprocessorsVerify =
561        "[" + masterCoprocessor.getSimpleName() + "]";
562    String loadedMasterCoprocessors =
563        java.util.Arrays.toString(
564            TEST_UTIL.getHBaseCluster().getMaster().getMasterCoprocessors());
565    assertEquals(loadedMasterCoprocessorsVerify, loadedMasterCoprocessors);
566  }
567
568  private void waitForTable(TableName name) throws InterruptedException, IOException {
569    // First wait until all regions are online
570    TEST_UTIL.waitTableEnabled(name);
571    // Now wait a bit longer for the coprocessor hosts to load the CPs
572    Thread.sleep(1000);
573  }
574
575}
576