/*
 * 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.mapreduce;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.WALPlayer.WALKeyValueMapper;
import org.apache.hadoop.hbase.regionserver.TestRecoveredEdits;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.MapReduceTests;
import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.CommonFSUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.LauncherSecurityManager;
import org.apache.hadoop.hbase.wal.WAL;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.hbase.wal.WALKey;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.util.ToolRunner;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * Basic test for the WALPlayer M/R tool
 */
@Tag(MapReduceTests.TAG)
@Tag(LargeTests.TAG)
public class TestWALPlayer {

  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static MiniHBaseCluster cluster;
  private static Path rootDir;
  private static Path walRootDir;
  private static FileSystem fs;
  private static FileSystem logFs;
  private static Configuration conf;

  @BeforeAll
  public static void beforeClass() throws Exception {
    conf = TEST_UTIL.getConfiguration();
    rootDir = TEST_UTIL.createRootDir();
    walRootDir = TEST_UTIL.createWALRootDir();
    fs = CommonFSUtils.getRootDirFileSystem(conf);
    logFs = CommonFSUtils.getWALFileSystem(conf);
    cluster = TEST_UTIL.startMiniCluster();
  }

  @AfterAll
  public static void afterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
    fs.delete(rootDir, true);
    logFs.delete(walRootDir, true);
  }

  /**
   * Test that WALPlayer can replay recovered.edits files.
   */
  @Test
  public void testPlayingRecoveredEdit() throws Exception {
    TableName tn = TableName.valueOf(TestRecoveredEdits.RECOVEREDEDITS_TABLENAME);
    TEST_UTIL.createTable(tn, TestRecoveredEdits.RECOVEREDEDITS_COLUMNFAMILY);
    // Copy testing recovered.edits file that is over under hbase-server test resources
    // up into a dir in our little hdfs cluster here.
    String hbaseServerTestResourcesEdits =
      System.getProperty("test.build.classes") + "/../../../hbase-server/src/test/resources/"
        + TestRecoveredEdits.RECOVEREDEDITS_PATH.getName();
    assertTrue(new File(hbaseServerTestResourcesEdits).exists());
    FileSystem dfs = TEST_UTIL.getDFSCluster().getFileSystem();
    // Target dir.
    Path targetDir = new Path("edits").makeQualified(dfs.getUri(), dfs.getHomeDirectory());
    assertTrue(dfs.mkdirs(targetDir));
    dfs.copyFromLocalFile(new Path(hbaseServerTestResourcesEdits), targetDir);
    assertEquals(0,
      ToolRunner.run(new WALPlayer(this.conf), new String[] { targetDir.toString() }));
    // I don't know how many edits are in this file for this table... so just check more than 1.
    assertTrue(TEST_UTIL.countRows(tn) > 0);
  }

  /**
   * Tests that when you write multiple cells with the same timestamp they are properly sorted by
   * their sequenceId in WALPlayer/CellSortReducer so that the correct one wins when querying from
   * the resulting bulkloaded HFiles. See HBASE-27649
   */
  @Test
  public void testWALPlayerBulkLoadWithOverriddenTimestamps(TestInfo testInfo) throws Exception {
    final TableName tableName = TableName.valueOf(testInfo.getTestMethod().get().getName() + "1");
    final byte[] family = Bytes.toBytes("family");
    final byte[] column1 = Bytes.toBytes("c1");
    final byte[] column2 = Bytes.toBytes("c2");
    final byte[] row = Bytes.toBytes("row");
    Table table = TEST_UTIL.createTable(tableName, family);

    long now = EnvironmentEdgeManager.currentTime();
    // put a row into the first table
    Put p = new Put(row);
    p.addColumn(family, column1, now, column1);
    p.addColumn(family, column2, now, column2);

    table.put(p);

    byte[] lastVal = null;

    for (int i = 0; i < 50; i++) {
      lastVal = Bytes.toBytes(ThreadLocalRandom.current().nextLong());
      p = new Put(row);
      p.addColumn(family, column1, now, lastVal);

      table.put(p);

      // wal rolling is necessary to trigger the bug. otherwise no sorting
      // needs to occur in the reducer because it's all sorted and coming from a single file.
      if (i % 10 == 0) {
        WAL log = cluster.getRegionServer(0).getWAL(null);
        log.rollWriter();
      }
    }

    WAL log = cluster.getRegionServer(0).getWAL(null);
    log.rollWriter();
    String walInputDir = new Path(cluster.getMaster().getMasterFileSystem().getWALRootDir(),
      HConstants.HREGION_LOGDIR_NAME).toString();

    Configuration configuration = new Configuration(TEST_UTIL.getConfiguration());
    String outPath = "/tmp/" + testInfo.getTestMethod().get().getName();
    configuration.set(WALPlayer.BULK_OUTPUT_CONF_KEY, outPath);

    WALPlayer player = new WALPlayer(configuration);
    assertEquals(0, ToolRunner.run(configuration, player,
      new String[] { walInputDir, tableName.getNameAsString() }));

    Get g = new Get(row);
    Result result = table.get(g);
    byte[] value = CellUtil.cloneValue(result.getColumnLatestCell(family, column1));
    assertThat(Bytes.toStringBinary(value), equalTo(Bytes.toStringBinary(lastVal)));

    table = TEST_UTIL.truncateTable(tableName);
    g = new Get(row);
    result = table.get(g);
    assertThat(result.listCells(), nullValue());

    BulkLoadHFiles.create(configuration).bulkLoad(tableName, new Path(outPath));

    g = new Get(row);
    result = table.get(g);
    value = CellUtil.cloneValue(result.getColumnLatestCell(family, column1));

    assertThat(result.listCells(), notNullValue());
    assertThat(Bytes.toStringBinary(value), equalTo(Bytes.toStringBinary(lastVal)));
  }

  /**
   * Simple end-to-end test
   */
  @Test
  public void testWALPlayer(TestInfo testInfo) throws Exception {
    final TableName tableName1 = TableName.valueOf(testInfo.getTestMethod().get().getName() + "1");
    final TableName tableName2 = TableName.valueOf(testInfo.getTestMethod().get().getName() + "2");
    final byte[] FAMILY = Bytes.toBytes("family");
    final byte[] COLUMN1 = Bytes.toBytes("c1");
    final byte[] COLUMN2 = Bytes.toBytes("c2");
    final byte[] ROW = Bytes.toBytes("row");
    Table t1 = TEST_UTIL.createTable(tableName1, FAMILY);
    Table t2 = TEST_UTIL.createTable(tableName2, FAMILY);

    // put a row into the first table
    Put p = new Put(ROW);
    p.addColumn(FAMILY, COLUMN1, COLUMN1);
    p.addColumn(FAMILY, COLUMN2, COLUMN2);
    t1.put(p);
    // delete one column
    Delete d = new Delete(ROW);
    d.addColumns(FAMILY, COLUMN1);
    t1.delete(d);

    // replay the WAL, map table 1 to table 2
    WAL log = cluster.getRegionServer(0).getWAL(null);
    log.rollWriter();
    String walInputDir = new Path(cluster.getMaster().getMasterFileSystem().getWALRootDir(),
      HConstants.HREGION_LOGDIR_NAME).toString();

    Configuration configuration = TEST_UTIL.getConfiguration();
    WALPlayer player = new WALPlayer(configuration);
    String optionName = "_test_.name";
    configuration.set(optionName, "1000");
    player.setupTime(configuration, optionName);
    assertEquals(1000, configuration.getLong(optionName, 0));
    assertEquals(0, ToolRunner.run(configuration, player,
      new String[] { walInputDir, tableName1.getNameAsString(), tableName2.getNameAsString() }));

    // verify the WAL was player into table 2
    Get g = new Get(ROW);
    Result r = t2.get(g);
    assertEquals(1, r.size());
    assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN2));
  }

  /**
   * Test WALKeyValueMapper setup and map
   */
  @Test
  public void testWALKeyValueMapper() throws Exception {
    testWALKeyValueMapper(WALPlayer.TABLES_KEY);
  }

  @Test
  public void testWALKeyValueMapperWithDeprecatedConfig() throws Exception {
    testWALKeyValueMapper("hlog.input.tables");
  }

  private void testWALKeyValueMapper(final String tableConfigKey) throws Exception {
    Configuration configuration = new Configuration();
    configuration.set(tableConfigKey, "table");
    WALKeyValueMapper mapper = new WALKeyValueMapper();
    WALKey key = mock(WALKey.class);
    when(key.getTableName()).thenReturn(TableName.valueOf("table"));
    @SuppressWarnings("unchecked")
    Mapper<WALKey, WALEdit, ImmutableBytesWritable, KeyValue>.Context context = mock(Context.class);
    when(context.getConfiguration()).thenReturn(configuration);

    WALEdit value = mock(WALEdit.class);
    ArrayList<Cell> values = new ArrayList<>();
    KeyValue kv1 = new KeyValue(Bytes.toBytes("row"), Bytes.toBytes("family"), null);

    values.add(kv1);
    when(value.getCells()).thenReturn(values);
    mapper.setup(context);

    doAnswer(new Answer<Void>() {

      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        ImmutableBytesWritable writer = invocation.getArgument(0);
        KeyValue key = invocation.getArgument(1);
        assertEquals("row", Bytes.toString(writer.get()));
        assertEquals("row", Bytes.toString(CellUtil.cloneRow(key)));
        return null;
      }
    }).when(context).write(any(), any());

    mapper.map(key, value, context);

  }

  /**
   * Test main method
   */
  @Test
  public void testMainMethod() throws Exception {

    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
      System.setErr(new PrintStream(data));
      try {
        WALPlayer.main(args);
        fail("should be SecurityException");
      } catch (SecurityException e) {
        assertEquals(-1, newSecurityManager.getExitCode());
        assertTrue(data.toString().contains("ERROR: Wrong number of arguments:"));
        assertTrue(data.toString()
          .contains("Usage: WALPlayer [options] <WAL inputdir>" + " [<tables> <tableMappings>]"));
        assertTrue(data.toString().contains("-Dwal.bulk.output=/path/for/output"));
      }

    } finally {
      System.setErr(oldPrintStream);
      System.setSecurityManager(SECURITY_MANAGER);
    }

  }

}
