package cloud.cluster.sim.clustersimulator;

import cloud.cluster.sim.clustersimulator.dto.Vm;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * Simulate failures for VMs. The lower is up time in SLA the higher the chance for a Vm to fail.
 */
@Component
public class FailureInjector {

    private static final int NUMBER_OF_DAYS_FOR_SLA = 30;
    private static final int NUMBER_OF_SECONDS_IN_DAY = 86400;          // 24 hours * 60 minutes * 60 seconds

    /**
     * Simulate failures for all the machines in the cluster.
     *
     * @param clusterManager ClusterManager for which failures will be simulated.
     * @return ClusterManager after failure simulation.
     */
    public void injectFailure(ClusterManager clusterManager) {
        for (int i = 0; i < clusterManager.getClusterSize(); i++) {
            Vm vm = clusterManager.getCluster().getVms().get(i);
            if (testVmFarFailure(vm.getMicroDataCenter().getSla())) {
                clusterManager.failVm(i);
            }
        }
    }

    /**
     * Test a particular VM in the cluster for failure.
     *
     * @param sla specifying the up time for a VM.
     * @return boolean value indicating the the machine has failed or not.
     */
    private boolean testVmFarFailure(double sla) {
        int seconds;
        long secondsOffline;

        seconds = NUMBER_OF_DAYS_FOR_SLA * NUMBER_OF_SECONDS_IN_DAY;
        secondsOffline = (long) (seconds *  (100 - sla)) / 100;

        Random random = new Random();
        int randomInt = random.nextInt(seconds);
        long numberOfRestart = secondsOffline / 60;

        if (randomInt <= secondsOffline) {
            return true;
        }
        return false;
    }

}

@@ -481,16 +481,161 @@
 seconds%0A
+    private static final int NUMBER_OF_OUTAGES = 98;%0A%0A    private int totalNumberOfSeconds = NUMBER_OF_DAYS_FOR_SLA * NUMBER_OF_SECONDS_IN_DAY;%0A%0A
 %0A    /**
@@ -1457,29 +1457,63 @@
     
-int second
+long downtime;%0A        double mttr, failure
 s;%0A
+%0A
         
 long
@@ -1512,161 +1512,150 @@
     
-long secondsOffline;%0A%0A        seconds = NUMBER_OF_DAYS_FOR_SLA * NUMBER_OF_SECONDS_IN_DAY;%0A        secondsOffline = (long) (seconds *  (100 - sla)) / 100
+downtime = (long) (totalNumberOfSeconds *  (100 - sla)) / 100;%0A        mttr = downtime / NUMBER_OF_OUTAGES;%0A        failures = downtime / mttr
 ;%0A%0A 
@@ -1734,68 +1734,29 @@
 Int(
-seconds);%0A        long numberOfRestart = secondsOffline / 60
+totalNumberOfSeconds)
 ;%0A%0A 
@@ -1783,22 +1783,16 @@
  %3C= 
-secondsOffline
+failures
 ) %7B%0A

Update failure injection. The mean time to resolve an outage is configurable.