/**
 * 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 static org.junit.Assert.*;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.AppendTestUtil;
import org.apache.hadoop.hdfs.MiniAvatarCluster;
import org.apache.hadoop.hdfs.TestFileCreation;
import org.apache.hadoop.hdfs.MiniAvatarCluster.NameNodeInfo;
import org.apache.hadoop.hdfs.server.namenode.AvatarNode;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestAvatarDataNodeMultipleRegistrations {
  private static final Log LOG = 
    LogFactory.getLog(TestAvatarDataNodeMultipleRegistrations.class);
  Configuration conf;
  boolean simulatedStorage = false;
  static final long seed = 0xDEADBEEFL;
  static final int blockSize = 8192;
  static final int numBlocks = 2;
  static final int fileSize = numBlocks * blockSize + 1;
  
  @BeforeClass
  public static void setUpClass() throws Exception {
    MiniAvatarCluster.createAndStartZooKeeper();
  }

  @Before
  public void setUp() throws Exception {
    conf = new Configuration();
    // populate repl queues on standby (in safe mode)
    conf.setFloat("dfs.namenode.replqueue.threshold-pct", 0f);
    conf.setLong("fs.avatar.standbyfs.initinterval", 1000);
    conf.setLong("fs.avatar.standbyfs.checkinterval", 1000);
  }

  /**
   * start multiple NNs and single DN and verifies per BP registrations and
   * handshakes.
   * 
   * @throws IOException
   */
  @Test
  public void test2NNRegistration() 
      throws IOException, ConfigException, InterruptedException{
    MiniAvatarCluster cluster = new MiniAvatarCluster(conf, 1, true, null, null, 2, true); 
    try {
      NameNodeInfo nn1 = cluster.getNameNode(0);
      NameNodeInfo nn2 = cluster.getNameNode(1);
      AvatarNode nn1zero = nn1.avatars.get(0).avatar;
      AvatarNode nn1one = nn1.avatars.get(1).avatar;
      AvatarNode nn2zero = nn2.avatars.get(0).avatar;
      AvatarNode nn2one = nn2.avatars.get(1).avatar;
      assertNotNull("cannot create nn1 avatar 0", nn1zero);
      assertNotNull("cannot create nn1 avatar 1", nn1one);
      assertNotNull("cannot create nn2 avatar 0", nn2zero);
      assertNotNull("cannot create nn2 avatar 1", nn2one);
      
      int ns1zero = nn1zero.getNamespaceID();
      int ns1one = nn1one.getNamespaceID();
      assertEquals("namespace ids for namenode 1 should be the same",
          ns1zero, ns1one);
      int ns2zero = nn2zero.getNamespaceID();
      int ns2one = nn2one.getNamespaceID();
      assertEquals("namespace ids for namenode 2 should be the same",
          ns2zero, ns2one);
      int lv1zero = nn1zero.getFSImage().getLayoutVersion();
      int lv1one = nn1one.getFSImage().getLayoutVersion();
      int lv2zero = nn2zero.getFSImage().getLayoutVersion();
      int lv2one = nn2one.getFSImage().getLayoutVersion();
      assertNotSame("namespace ids should be different", ns1zero, ns2zero);
      LOG.info("nn1zero: lv=" + lv1zero + ";uri=" + nn1zero.getNameNodeAddress());
      LOG.info("nn1one: lv=" + lv1one + ";uri=" + nn1one.getNameNodeAddress());
      LOG.info("nn2zero: lv=" + lv2zero + ";uri=" + nn2zero.getNameNodeAddress());
      LOG.info("nn2one: lv=" + lv2one + ";uri=" + nn2one.getNameNodeAddress());

      // check number of volumes in fsdataset
      AvatarDataNode dn = cluster.getDataNodes().get(0);
      
      for (NamespaceService nsos : dn.getAllNamespaceServices()) {
        LOG.info("reg: nsid =" + nsos.getNamespaceId() + "; name="
            + nsos.getNsRegistration().name + "; sid="
            + nsos.getNsRegistration().storageID + "; nna="
            + nsos.getNNSocketAddress());
      }

      NamespaceService nsos1 = dn.getAllNamespaceServices()[0];
      NamespaceService nsos2 = dn.getAllNamespaceServices()[1];

      // The order of bpos is not guaranteed, so fix the order
      if (nsos1.getNNSocketAddress().equals(nn2zero.getNameNodeDNAddress())) {
        NamespaceService tmp = nsos1;
        nsos1 = nsos2;
        nsos2 = tmp;
      }

      assertEquals("wrong nn address", nsos1.getNNSocketAddress(),
          nn1zero.getNameNodeDNAddress());
      assertEquals("wrong nn address", nsos2.getNNSocketAddress(),
          nn2zero.getNameNodeDNAddress());
      assertEquals("wrong nsid", nsos1.getNamespaceId(), ns1zero);
      assertEquals("wrong nsid", nsos2.getNamespaceId(), ns2zero);
    } finally {
      cluster.shutDown();
    }
  }

  /**
   * starts single nn and single dn and verifies registration and hand