/**
 * 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.hdfs.server.datanode;

import java.nio.channels.FileChannel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.DF;
import org.apache.hadoop.fs.DU;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.DU.NamespaceSliceDU;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.HardLink;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.FSDataset.ActiveFile;
import org.apache.hadoop.hdfs.server.datanode.metrics.FSDatasetMBean;
import org.apache.hadoop.hdfs.server.protocol.BlockFlags;
import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryInfo;
import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol;
import org.apache.hadoop.hdfs.util.LightWeightHashSet;
import org.apache.hadoop.metrics.util.MBeanUtil;
import org.apache.hadoop.util.DataChecksum;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.VersionInfo;
import org.apache.hadoop.util.DiskChecker;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;

/**************************************************
 * FSDataset manages a set of data blocks.  Each block
 * has a unique name and an extent on disk.
 *
 ***************************************************/
public class FSDataset implements FSConstants, FSDatasetInterface {
  
  static String[] getFileNames(File[] files) {
    String[] fileNames = new String[files.length];
    for (int i = 0; i < files.length; i++) {
      fileNames[i] = files[i].getName();
    }
    return fileNames;
  }

  /**
   * A NamespaceSlice represents a portion of a namespace stored on a volume.  
   * Taken together, all BNamespaceSlices sharing a namespaceID across a 
   * cluster represent a single namespace.
   */
  class NamespaceSlice {
    private final int namespaceId;
    private final FSVolume volume; // volume to which this namespaceSlice belongs to
    private final FSDir dataDir; // StorageDirectory/current/nsid/current
    private final File detachDir; // directory store Finalized replica
    private final File rbwDir ; // directory store RBW replica
    private final File tmpDir; // directory store Temporary replica
    private final NamespaceSliceDU dfsUsage;

    /**
     * 
     * @param namespaceId
     * @param volume {@link FSVolume} to which this NamespaceSlice belongs to
     * @param nsDir directory corresponding to the NameSpaceSlice
     * @param conf
     * @throws IOException
     */
    NamespaceSlice(int namespaceId, FSVolume volume, File nsDir, Configuration conf, boolean supportAppends)
        throws IOException {
      this.namespaceId = namespaceId;
      this.volume = volume;
      File nsDirCur = new File(nsDir, DataStorage.STORAGE_DIR_CURRENT); 
      File dataDirFile = new File(nsDirCur, DataStorage.STORAGE_DIR_FINALIZED);
      this.dataDir = new FSDir(namespaceId, dataDirFile, volume);
            
      this.detachDir = new File(nsDir, "detach");
      if (detachDir.exists()) {
        recoverDetachedBlocks(dataDirFile, detachDir);
      }

      // Files that were being written when the datanode was last shutdown
      // are now moved back to the data directory. It is possible that
      // in the future, we might want to do some sort of datanode-local
      // recovery for these blocks. For example, crc validation.
      //
      this.tmpDir = new File(nsDir, "tmp");
      if (tmpDir.exists()) {
        FileUtil.fullyDelete(tmpDir);
      }
      
      this.rbwDir = new File(nsDirCur, DataStorage.STORAGE_DIR_RBW);
      // Files that were being written when the datanode was last shutdown
      // should not be deleted.
      if (rbwDir.exists()) {
        if (supportAppends) {
          recoverBlocksBeingWritten(rbwDir);
        } else {
          // rename tmpDir to prepare delete
          File toDeleteDir = new File(tmpDir.getParent(),
          DELETE_FILE_EXT + tmpDir.getName());
          if (tmpDir.renameTo(toDeleteDir)) {
            // asyncly delete the renamed directory
            asyncDiskService.deleteAsyncFile(volume, toDeleteDir);
          } else {
            // rename failed, let's synchronously delete the directory
            FileUtil.fullyDelete(tmpDir);