/*
 * Copyright (c) 2014-2018 Aurélien Broszniowski
 *
 * Licensed 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 io.rainfall;

import io.rainfall.configuration.DistributedConfig;
import io.rainfall.configuration.ReportingConfig;
import io.rainfall.utils.distributed.RainfallServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.concurrent.CyclicBarrier;

/**
 * @author Aurelien Broszniowski
 */
public class RainfallMaster {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  private final DistributedConfig distributedConfig;
  private final ReportingConfig reportingConfig;
  private final File reportPath;
  private volatile RainfallServer rainfallServer = null;

  public RainfallMaster(final DistributedConfig distributedConfig, ReportingConfig reportingConfig, final File reportPath) {
    this.distributedConfig = distributedConfig;
    this.reportingConfig = reportingConfig;
    this.reportPath = reportPath;
  }

  public static <E extends Enum<E>> RainfallMaster master(final DistributedConfig distributedConfig, final ReportingConfig<E> reportingConfig) {
    return new RainfallMaster(distributedConfig, reportingConfig, new File("Rainfall-master-report"));
  }

  public static <E extends Enum<E>> RainfallMaster master(final DistributedConfig distributedConfig,
                                                          final ReportingConfig<E> reportingConfig, final File reportPath) {
    return new RainfallMaster(distributedConfig, reportingConfig, reportPath);
  }

  public RainfallMaster start() throws TestException {
    try {
      logger.debug("[Rainfall server] Check if configuration server hostname is current host.");
      if (!Arrays.toString(InetAddress.getByName("localhost").getAddress()).equalsIgnoreCase(
          Arrays.toString(distributedConfig.getMasterAddress().getAddress().getAddress()))) {
        logger.debug("[Rainfall server] Current host is NOT the server host, so we return to start the client");
        return this;
      }
    } catch (UnknownHostException e) {
      throw new TestException("Can not run multi-clients test.", e);
    }

    ServerSocket serverSocket;
    try {
      serverSocket = new ServerSocket(distributedConfig.getMasterAddress().getPort());
    } catch (IOException e) {
      //      if (e.getMessage().startsWith()) {
      logger.debug("[Rainfall server] already started");
      return this;
    }

    logger.debug("[Rainfall server] Current host is the server host, so we start the Rainfall server");
    rainfallServer = new RainfallServer(distributedConfig, reportingConfig, reportPath, serverSocket);
    rainfallServer.start();
    return this;
  }

  public void stop() throws TestException {
    if (rainfallServer != null) {
      try {
        rainfallServer.shutdown();
        rainfallServer.join();
      } catch (InterruptedException e) {
        throw new TestException("Rainfall cluster client interrupted", e);
      }
    }
    if (rainfallServer != null) {
      TestException testException = rainfallServer.getTestException().get();
      if (testException != null) {
        throw testException;
      }
    }
  }

  public CyclicBarrier getBarrier(final String barrierName, final int parties) {
    throw new UnsupportedOperationException("clustered cyclic barrier is not implemented");
  }
}

@@ -921,16 +921,50 @@
 ddress;%0A
+import java.net.NetworkInterface;%0A
 import j
@@ -1001,26 +1001,21 @@
 ava.net.
-UnknownHos
+Socke
 tExcepti
@@ -1035,22 +1035,27 @@
 va.util.
-Arrays
+Enumeration
 ;%0Aimport
@@ -1170,24 +1170,31 @@
 %0A%0A  private 
+static 
 final Logger
@@ -1231,23 +1231,28 @@
 ger(
-this.getC
+RainfallMaster.c
 lass
-()
 );%0A%0A
@@ -2338,399 +2338,37 @@
     
-logger.debug(%22%5BRainfall server%5D Check if configuration server hostname is current host.%22);%0A      if (!Arrays.toString(InetAddress.getByName(%22localhost%22).getAddress()).equalsIgnoreCase(%0A          Arrays.toString(distributedConfig.getMasterAddress().getAddress().getAddress()))) %7B%0A        logger.debug(%22%5BRainfall server%5D Current host is NOT the server host, so we return to start the client%22);
+if (!isCurrentHostMaster()) %7B
 %0A   
@@ -2410,18 +2410,13 @@
 ch (
-UnknownHos
+Socke
 tExc
@@ -2665,57 +2665,8 @@
 ) %7B%0A
-      //      if (e.getMessage().startsWith()) %7B%0A
     
@@ -2997,24 +2997,979 @@
  this;%0A  %7D%0A%0A
+  private boolean isCurrentHostMaster() throws SocketException %7B%0A    InetAddress masterAddress = distributedConfig.getMasterAddress().getAddress();%0A%0A    Enumeration%3CNetworkInterface%3E networkInterfaces = NetworkInterface.getNetworkInterfaces();%0A    while (networkInterfaces.hasMoreElements()) %7B%0A      NetworkInterface networkInterface = networkInterfaces.nextElement();%0A%0A      Enumeration%3CInetAddress%3E inetAddresses = networkInterface.getInetAddresses();%0A      while (inetAddresses.hasMoreElements()) %7B%0A        InetAddress inetAddress = inetAddresses.nextElement();%0A        logger.debug(%22%5BRainfall server%5D Check if current NIC (%7B%7D) has the IP from rainfall master host (%7B%7D).%22,%0A            inetAddress, masterAddress);%0A        if (inetAddress.equals(masterAddress)) %7B%0A          logger.debug(%22%5BRainfall server%5D Current NIC IP is the rainfall master IP, we attempt to start the master.%22);%0A          return true;%0A        %7D%0A      %7D%0A    %7D%0A    return false;%0A  %7D%0A%0A
   public voi

fix rainfall master ip resolution