<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.hbase.client.replication;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.ReplicationPeerNotFoundException;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfigBuilder;
import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
import org.apache.hadoop.hbase.replication.ReplicationQueueStorage;
import org.apache.hadoop.hbase.replication.ReplicationStorageFactory;
import org.apache.hadoop.hbase.replication.TestReplicationEndpoint.InterClusterReplicationEndpointForTest;
import org.apache.hadoop.hbase.replication.TestReplicationEndpoint.ReplicationEndpointForTest;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;

/**
 * Unit testing of ReplicationAdmin
 */
@Category({MediumTests.class, ClientTests.class})
public class TestReplicationAdmin {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestReplicationAdmin.class);

  private final static HBaseTestingUtility TEST_UTIL =
      new HBaseTestingUtility();

  private final String ID_ONE = "1";
  private final String KEY_ONE = "127.0.0.1:2181:/hbase";
  private final String ID_SECOND = "2";
  private final String KEY_SECOND = "127.0.0.1:2181:/hbase2";

  private static ReplicationAdmin admin;
  private static Admin hbaseAdmin;

  @Rule
  public TestName name = new TestName();

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
    TEST_UTIL.startMiniCluster();
    admin = new ReplicationAdmin(TEST_UTIL.getConfiguration());
    hbaseAdmin = TEST_UTIL.getAdmin();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    if (admin != null) {
      admin.close();
    }
    TEST_UTIL.shutdownMiniCluster();
  }

  @After
  public void tearDown() throws Exception {
    for (ReplicationPeerDescription desc : hbaseAdmin.listReplicationPeers()) {
      hbaseAdmin.removeReplicationPeer(desc.getPeerId());
    }
    ReplicationQueueStorage queueStorage = ReplicationStorageFactory
        .getReplicationQueueStorage(TEST_UTIL.getZooKeeperWatcher(), TEST_UTIL.getConfiguration());
    for (ServerName serverName : queueStorage.getListOfReplicators()) {
      for (String queue : queueStorage.getAllQueues(serverName)) {
        queueStorage.removeQueue(serverName, queue);
      }
      queueStorage.removeReplicatorIfQueueIsEmpty(serverName);
    }
  }

  @Test
  public void testAddInvalidPeer() {
    ReplicationPeerConfigBuilder builder = ReplicationPeerConfig.newBuilder();
    builder.setClusterKey(KEY_ONE);
    try {
      String invalidPeerId = "1-2";
      hbaseAdmin.addReplicationPeer(invalidPeerId, builder.build());
      fail("Should fail as the peer id: " + invalidPeerId + " is invalid");
    } catch (Exception e) {
      // OK
    }

    try {
      String invalidClusterKey = "2181:/hbase";
      builder.setClusterKey(invalidClusterKey);
      hbaseAdmin.addReplicationPeer(ID_ONE, builder.build());
      fail("Should fail as the peer cluster key: " + invalidClusterKey + " is invalid");
    } catch (Exception e) {
      // OK
    }
  }<commit_msg>HBASE-19544 Add UTs for testing concurrent modifications on replication peer<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.hbase.client.replication;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.ReplicationPeerNotFoundException;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfigBuilder;
import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
import org.apache.hadoop.hbase.replication.ReplicationQueueStorage;
import org.apache.hadoop.hbase.replication.ReplicationStorageFactory;
import org.apache.hadoop.hbase.replication.TestReplicationEndpoint.InterClusterReplicationEndpointForTest;
import org.apache.hadoop.hbase.replication.TestReplicationEndpoint.ReplicationEndpointForTest;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Unit testing of ReplicationAdmin
 */
@Category({MediumTests.class, ClientTests.class})
public class TestReplicationAdmin {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestReplicationAdmin.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestReplicationAdmin.class);

  private final static HBaseTestingUtility TEST_UTIL =
      new HBaseTestingUtility();

  private final String ID_ONE = "1";
  private final String KEY_ONE = "127.0.0.1:2181:/hbase";
  private final String ID_SECOND = "2";
  private final String KEY_SECOND = "127.0.0.1:2181:/hbase2";

  private static ReplicationAdmin admin;
  private static Admin hbaseAdmin;

  @Rule
  public TestName name = new TestName();

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
    TEST_UTIL.startMiniCluster();
    admin = new ReplicationAdmin(TEST_UTIL.getConfiguration());
    hbaseAdmin = TEST_UTIL.getAdmin();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    if (admin != null) {
      admin.close();
    }
    TEST_UTIL.shutdownMiniCluster();
  }

  @After
  public void tearDown() throws Exception {
    for (ReplicationPeerDescription desc : hbaseAdmin.listReplicationPeers()) {
      hbaseAdmin.removeReplicationPeer(desc.getPeerId());
    }
    ReplicationQueueStorage queueStorage = ReplicationStorageFactory
        .getReplicationQueueStorage(TEST_UTIL.getZooKeeperWatcher(), TEST_UTIL.getConfiguration());
    for (ServerName serverName : queueStorage.getListOfReplicators()) {
      for (String queue : queueStorage.getAllQueues(serverName)) {
        queueStorage.removeQueue(serverName, queue);
      }
      queueStorage.removeReplicatorIfQueueIsEmpty(serverName);
    }
  }

  @Test
  public void testConcurrentPeerOperations() throws Exception {
    int threadNum = 5;
    AtomicLong successCount = new AtomicLong(0);

    // Test concurrent add peer operation
    Thread[] addPeers = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
      addPeers[i] = new Thread(() -> {
        try {
          hbaseAdmin.addReplicationPeer(ID_ONE,
            ReplicationPeerConfig.newBuilder().setClusterKey(KEY_ONE).build());
          successCount.incrementAndGet();
        } catch (Exception e) {
          LOG.debug("Got exception when add replication peer", e);
        }
      });
      addPeers[i].start();
    }
    for (Thread addPeer : addPeers) {
      addPeer.join();
    }
    assertEquals(1, successCount.get());

    // Test concurrent remove peer operation
    successCount.set(0);
    Thread[] removePeers = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
      removePeers[i] = new Thread(() -> {
        try {
          hbaseAdmin.removeReplicationPeer(ID_ONE);
          successCount.incrementAndGet();
        } catch (Exception e) {
          LOG.debug("Got exception when remove replication peer", e);
        }
      });
      removePeers[i].start();
    }
    for (Thread removePeer : removePeers) {
      removePeer.join();
    }
    assertEquals(1, successCount.get());

    // Test concurrent add peer operation again
    successCount.set(0);
    addPeers = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
      addPeers[i] = new Thread(() -> {
        try {
          hbaseAdmin.addReplicationPeer(ID_ONE,
            ReplicationPeerConfig.newBuilder().setClusterKey(KEY_ONE).build());
          successCount.incrementAndGet();
        } catch (Exception e) {
          LOG.debug("Got exception when add replication peer", e);
        }
      });
      addPeers[i].start();
    }
    for (Thread addPeer : addPeers) {
      addPeer.join();
    }
    assertEquals(1, successCount.get());
  }

  @Test
  public void testAddInvalidPeer() {
    ReplicationPeerConfigBuilder builder = ReplicationPeerConfig.newBuilder();
    builder.setClusterKey(KEY_ONE);
    try {
      String invalidPeerId = "1-2";
      hbaseAdmin.addReplicationPeer(invalidPeerId, builder.build());
      fail("Should fail as the peer id: " + invalidPeerId + " is invalid");
    } catch (Exception e) {
      // OK
    }

    try {
      String invalidClusterKey = "2181:/hbase";
      builder.setClusterKey(invalidClusterKey);
      hbaseAdmin.addReplicationPeer(ID_ONE, builder.build());
      fail("Should fail as the peer cluster key: " + invalidClusterKey + " is invalid");
    } catch (Exception e) {
      // OK
    }
  }
{'fraction_non_alphanumeric': 0.09878479027832222, 'fraction_numerical': 0.006664053312426499, 'mean_word_length': 4.127009646302251, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4906836', 'n_tokens_mistral': 3704, 'n_tokens_neox': 3630, 'n_words': 882}