How to Perform Particle Swarm Optimization Algorithm Using Containercloudsim?
Share
Condition for Perform Particle Swarm Optimization Algorithm Using Containercloudsim
Description: This implementation integrates Particle Swarm Optimization (PSO) algorithm with ContainerCloudSim to intelligently optimize container-to-virtual machine allocation in cloud computing environments. The PSO algorithm functions as an intelligent resource management system that dynamically determines the optimal placement of containers across available VMs by considering multiple critical factors including load balancing, resource utilization efficiency, power consumption minimization, and migration costs. Through a swarm intelligence approach, multiple candidate solutions (particles) collaboratively explore the solution space, continuously updating their positions based on personal best experiences and global best knowledge from the swarm.
The fitness function comprehensively evaluates each allocation strategy by calculating CPU, RAM, and bandwidth utilization variances across VMs to ensure balanced workload distribution, while simultaneously optimizing for energy efficiency and minimizing potential migration overhead. This bio-inspired optimization technique enables the cloud infrastructure to automatically adapt to changing workloads and resource demands, resulting in significantly improved performance metrics, reduced operational costs, and enhanced overall system reliability compared to traditional static allocation methods. The seamless integration with ContainerCloudSim provides researchers and cloud administrators with a powerful tool for simulating and analyzing optimized container deployment strategies in complex, multi-tenant cloud environments.
Sample Code
1. SourceCode1:
package ParticleSwarm;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PsoSolution {
private List allocation; // containerId -> vmId mapping
private List velocity;
private double fitness;
private double personalBestFitness;
private List personalBestAllocation;
private static Random random = new Random();
public PsoSolution(int numberOfContainers, int numberOfVms) {
this.allocation = new ArrayList<>();
this.velocity = new ArrayList<>();
this.personalBestAllocation = new ArrayList<>();
// Initialize random allocation and velocity
for (int i = 0; i < numberOfContainers; i++) {
int vmId = random.nextInt(numberOfVms);
allocation.add(vmId);
personalBestAllocation.add(vmId);
velocity.add(random.nextDouble() * 2 - 1); // Random velocity between -1 and 1
}
this.fitness = Double.MAX_VALUE;
this.personalBestFitness = Double.MAX_VALUE;
}
public PsoSolution(List allocation, List velocity) {
this.allocation = new ArrayList<>(allocation);
this.velocity = new ArrayList<>(velocity);
this.personalBestAllocation = new ArrayList<>(allocation);
this.fitness = Double.MAX_VALUE;
this.personalBestFitness = Double.MAX_VALUE;
}
// Getters and setters
public List getAllocation() {
return allocation;
}
public List getVelocity() {
return velocity;
}
public double getFitness() {
return fitness;
}
public void setFitness(double fitness) {
this.fitness = fitness;
if (fitness < personalBestFitness) {
personalBestFitness = fitness;
personalBestAllocation = new ArrayList<>(allocation);
}
}
public double getPersonalBestFitness() {
return personalBestFitness;
}
public List getPersonalBestAllocation() {
return personalBestAllocation;
}
public PsoSolution copy() {
return new PsoSolution(new ArrayList<>(allocation), new ArrayList<>(velocity));
}
}
2. SourceCode2:
package ParticleSwarm;
import org.cloudbus.cloudsim.container.core.ContainerCloudlet;
import org.cloudbus.cloudsim.container.core.Container;
import org.cloudbus.cloudsim.container.core.ContainerVm;
import org.cloudbus.cloudsim.container.core.ContainerHost;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Particle Swarm Optimization for container allocation in cloud environment
*/
public class PsoAlgorithm {
private int swarmSize;
private int maxIterations;
private double inertiaWeight;
private double cognitiveWeight;
private double socialWeight;
private double maxVelocity;
private List swarm;
private PsoSolution globalBest;
private Random random;
// Problem parameters
private List containers;
private List vms;
private List hosts;
private List cloudlets;
public PsoAlgorithm(int swarmSize, int maxIterations, double inertiaWeight,
double cognitiveWeight, double socialWeight, double maxVelocity) {
this.swarmSize = swarmSize;
this.maxIterations = maxIterations;
this.inertiaWeight = inertiaWeight;
this.cognitiveWeight = cognitiveWeight;
this.socialWeight = socialWeight;
this.maxVelocity = maxVelocity;
this.random = new Random();
}
public void initialize(List containers, List vms,
List hosts, List cloudlets) {
this.containers = containers;
this.vms = vms;
this.hosts = hosts;
this.cloudlets = cloudlets;
// Initialize swarm
swarm = new ArrayList<>();
for (int i = 0; i < swarmSize; i++) {
swarm.add(new PsoSolution(containers.size(), vms.size()));
}
globalBest = null;
}
public void run() {
System.out.println(" Starting PSO optimization...");
System.out.printf("Configuration: %d particles, %d iterations%n", swarmSize, maxIterations);
System.out.printf("Weights: inertia=%.3f, cognitive=%.3f, social=%.3f%n",
inertiaWeight, cognitiveWeight, socialWeight);
for (int iteration = 0; iteration < maxIterations; iteration++) {
// Evaluate fitness for each particle
for (PsoSolution particle : swarm) {
double fitness = evaluateFitness(particle);
particle.setFitness(fitness);
// Update global best
if (globalBest == null || fitness < globalBest.getFitness()) {
globalBest = particle.copy();
if (iteration % 10 == 0) {
printDetailedProgress(iteration, globalBest);
}
}
}
// Update velocities and positions
for (PsoSolution particle : swarm) {
updateParticle(particle);
}
}
}
public void printDetailedProgress(int iteration, PsoSolution globalBest) {
System.out.printf("Iteration %d:%n", iteration);
// Print top 5 container allocations
System.out.print(" Sample Allocations: ");
for (int i = 0; i < Math.min(5, globalBest.getAllocation().size()); i++) {
System.out.printf("C%d->VM%d ", i, globalBest.getAllocation().get(i));
}
System.out.println();
}
private double evaluateFitness(PsoSolution solution) {
double totalFitness = 0.0;
// 1. Load balancing fitness (minimize variance in VM utilization)
totalFitness += calculateLoadBalancingFitness(solution);
// 2. Resource utilization fitness (maximize overall utilization)
totalFitness += calculateResourceUtilizationFitness(solution);
// 3. Power consumption fitness (minimize power usage)
totalFitness += calculatePowerFitness(solution);
// 4. Migration cost fitness (minimize unnecessary migrations)
totalFitness += calculateMigrationFitness(solution);
return totalFitness;
}
private double calculateLoadBalancingFitness(PsoSolution solution) {
double[] vmCpuLoad = new double[vms.size()];
double[] vmRamLoad = new double[vms.size()];
double[] vmBwLoad = new double[vms.size()];
// Calculate load on each VM
for (int containerIdx = 0; containerIdx < containers.size(); containerIdx++) {
int vmIdx = solution.getAllocation().get(containerIdx);
Container container = containers.get(containerIdx);
// Find corresponding cloudlet for this container
ContainerCloudlet cloudlet = findCloudletForContainer(container.getId());
if (cloudlet != null) {
vmCpuLoad[vmIdx] += cloudlet.getCloudletLength() / vms.get(vmIdx).getMips();
vmRamLoad[vmIdx] += container.getRam();
vmBwLoad[vmIdx] += container.getBw();
}
}
// Calculate variance (we want to minimize variance for load balancing)
double cpuVariance = calculateVariance(vmCpuLoad);
double ramVariance = calculateVariance(vmRamLoad);
double bwVariance = calculateVariance(vmBwLoad);
return 0.4 * cpuVariance + 0.3 * ramVariance + 0.3 * bwVariance;
}
private double calculateResourceUtilizationFitness(PsoSolution solution) {
double totalUtilization = 0.0;
int count = 0;
for (int vmIdx = 0; vmIdx < vms.size(); vmIdx++) {
double vmUtilization = calculateVmUtilization(vmIdx, solution);
totalUtilization += vmUtilization;
count++;
}
// We want to maximize utilization, so return inverse
return 1.0 / (totalUtilization / count + 0.001); // Avoid division by zero
}
private double calculatePowerFitness(PsoSolution solution) {
double totalPower = 0.0;
for (int vmIdx = 0; vmIdx < vms.size(); vmIdx++) {
double utilization = calculateVmUtilization(vmIdx, solution);
// Simple linear power model: power = idle_power + utilization * (max_power - idle_power)
double power = 100 + utilization * 200; // Example values
totalPower += power;
}
return totalPower;
}
private double calculateMigrationFitness(PsoSolution solution) {
// This would compare with current allocation to estimate migration cost
// For simplicity, we'll return a small constant
return 0.1;
}
private double calculateVmUtilization(int vmIdx, PsoSolution solution) {
double totalMipsRequired = 0.0;
for (int containerIdx = 0; containerIdx < containers.size(); containerIdx++) {
if (solution.getAllocation().get(containerIdx) == vmIdx) {
Container container = containers.get(containerIdx);
ContainerCloudlet cloudlet = findCloudletForContainer(container.getId());
if (cloudlet != null) {
totalMipsRequired += cloudlet.getCloudletLength();
}
}
}
double vmMipsCapacity = vms.get(vmIdx).getMips() * vms.get(vmIdx).getNumberOfPes();
return Math.min(totalMipsRequired / vmMipsCapacity, 1.0);
}
private ContainerCloudlet findCloudletForContainer(int containerId) {
for (ContainerCloudlet cloudlet : cloudlets) {
if (cloudlet.getContainerId() == containerId) {
return cloudlet;
}
}
return null;
}
private double calculateVariance(double[] values) {
double mean = 0.0;
for (double value : values) {
mean += value;
}
mean /= values.length;
double variance = 0.0;
for (double value : values) {
variance += Math.pow(value - mean, 2);
}
return variance / values.length;
}
private void updateParticle(PsoSolution particle) {
List currentAllocation = particle.getAllocation();
List currentVelocity = particle.getVelocity();
List personalBest = particle.getPersonalBestAllocation();
List globalBestAllocation = globalBest.getAllocation();
for (int i = 0; i < currentAllocation.size(); i++) {
// Update velocity
double currentVel = currentVelocity.get(i);
double cognitiveComponent = cognitiveWeight * random.nextDouble()
* (personalBest.get(i) - currentAllocation.get(i));
double socialComponent = socialWeight * random.nextDouble()
* (globalBestAllocation.get(i) - currentAllocation.get(i));
double newVelocity = inertiaWeight * currentVel + cognitiveComponent + socialComponent;
// Apply velocity limits
newVelocity = Math.max(-maxVelocity, Math.min(maxVelocity, newVelocity));
currentVelocity.set(i, newVelocity);
// Update position (allocation)
int newVm = currentAllocation.get(i) + (int) Math.round(newVelocity);
// Ensure the VM index is valid
newVm = Math.max(0, Math.min(vms.size() - 1, newVm));
currentAllocation.set(i, newVm);
}
}
public PsoSolution getBestSolution() {
return globalBest;
}
public void printBestSolution() {
System.out.println("\n=== PSO Best Solution ===");
System.out.println("Fitness: " + globalBest.getFitness());
System.out.println("Container to VM Allocation:");
for (int i = 0; i < containers.size(); i++) {
System.out.printf("Container %d -> VM %d%n",
containers.get(i).getId(), globalBest.getAllocation().get(i));
}
// Print VM utilization
System.out.println("\nVM Utilization in Best Solution:");
for (int vmIdx = 0; vmIdx < vms.size(); vmIdx++) {
double utilization = calculateVmUtilization(vmIdx, globalBest);
System.out.printf("VM %d: %.2f%% utilization%n", vmIdx, utilization * 100);
}
}
}
3. SourceCode3:
package ParticleSwarm;
import org.cloudbus.cloudsim.container.core.*;
import java.util.ArrayList;
import java.util.List;
public class PsoContainerDatacenterBroker extends ContainerDatacenterBroker {
private PsoAlgorithm pso;
private boolean psoEnabled;
private List containers;
private List vms;
private List hosts;
private List cloudlets;
public PsoContainerDatacenterBroker(String name, int overBookingFactor) throws Exception {
super(name, overBookingFactor);
this.psoEnabled = true;
this.containers = new ArrayList<>();
this.vms = new ArrayList<>();
this.hosts = new ArrayList<>();
this.cloudlets = new ArrayList<>();
// Initialize PSO with parameters
int swarmSize = 30;
int maxIterations = 100;
double inertiaWeight = 0.729;
double cognitiveWeight = 1.49445;
double socialWeight = 1.49445;
double maxVelocity = 4.0;
this.pso = new PsoAlgorithm(swarmSize, maxIterations, inertiaWeight,
cognitiveWeight, socialWeight, maxVelocity);
}
@Override
public void submitContainerList(List< extends Container> list) {
super.submitContainerList(list);
this.containers.addAll(list);
if (psoEnabled && !vms.isEmpty() && !hosts.isEmpty() && !cloudlets.isEmpty()) {
runPsoOptimization();
}
}
@Override
public void submitVmList(List< extends ContainerVm> list) {
super.submitVmList(list);
this.vms.addAll(list);
if (psoEnabled && !containers.isEmpty() && !hosts.isEmpty() && !cloudlets.isEmpty()) {
runPsoOptimization();
}
}
@Override
public void submitCloudletList(List< extends ContainerCloudlet> list) {
super.submitCloudletList(list);
this.cloudlets.addAll(list);
if (psoEnabled && !containers.isEmpty() && !vms.isEmpty() && !hosts.isEmpty()) {
runPsoOptimization();
}
}
public void setHostList(List hostList) {
this.hosts = hostList;
if (psoEnabled && !containers.isEmpty() && !vms.isEmpty() && !cloudlets.isEmpty()) {
runPsoOptimization();
}
}
private void runPsoOptimization() {
System.out.println("Running PSO optimization for resource allocation...");
// Initialize PSO with current system state
pso.initialize(containers, vms, hosts, cloudlets);
// Run PSO optimization
pso.run();
// Get best solution and apply it
PsoSolution bestSolution = pso.getBestSolution();
applyPsoSolution(bestSolution);
// Print results
pso.printBestSolution();
}
private void applyPsoSolution(PsoSolution solution) {
List allocation = solution.getAllocation();
// Apply the container-to-VM allocation
for (int containerIdx = 0; containerIdx < containers.size(); containerIdx++) {
Container container = containers.get(containerIdx);
int vmIdx = allocation.get(containerIdx);
ContainerVm vm = vms.get(vmIdx);
// Set the container to be allocated to the specified VM
// This would typically involve modifying the allocation policy
System.out.printf("PSO Allocation: Container %d -> VM %d%n",
container.getId(), vm.getId());
}
}
public void setPsoEnabled(boolean enabled) {
this.psoEnabled = enabled;
}
public PsoAlgorithm getPsoAlgorithm() {
return pso;
}
}
4. SourceCode4:
package ParticleSwarm;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModelNull;
import org.cloudbus.cloudsim.container.containerProvisioners.ContainerBwProvisionerSimple;
import org.cloudbus.cloudsim.container.containerProvisioners.ContainerPe;
import org.cloudbus.cloudsim.container.containerProvisioners.ContainerRamProvisionerSimple;
import org.cloudbus.cloudsim.container.containerProvisioners.ContainerPeProvisionerSimple;
import org.cloudbus.cloudsim.container.containerVmProvisioners.ContainerVmBwProvisionerSimple;
import org.cloudbus.cloudsim.container.containerVmProvisioners.ContainerVmPe;
import org.cloudbus.cloudsim.container.containerVmProvisioners.ContainerVmPeProvisionerSimple;
import org.cloudbus.cloudsim.container.containerVmProvisioners.ContainerVmRamProvisionerSimple;
import org.cloudbus.cloudsim.container.core.*;
import org.cloudbus.cloudsim.container.hostSelectionPolicies.HostSelectionPolicy;
import org.cloudbus.cloudsim.container.hostSelectionPolicies.HostSelectionPolicyFirstFit;
import org.cloudbus.cloudsim.container.resourceAllocatorMigrationEnabled .PowerContainerVmAllocationPolicyMigrationAbstractHostSelection;
import org.cloudbus.cloudsim.container.resourceAllocators.ContainerAllocationPolicy;
import org.cloudbus.cloudsim.container.resourceAllocators.ContainerVmAllocationPolicy;
import org.cloudbus.cloudsim.container.resourceAllocators.PowerContainerAllocationPolicySimple;
import org.cloudbus.cloudsim.container.schedulers.ContainerCloudletSchedulerDynamicWorkload;
import org.cloudbus.cloudsim.container.schedulers.ContainerSchedulerTimeSharedOverSubscription;
import org.cloudbus.cloudsim.container.schedulers.ContainerVmSchedulerTimeSharedOverSubscription;
import org.cloudbus.cloudsim.container.utils.IDs;
import org.cloudbus.cloudsim.container.vmSelectionPolicies.PowerContainerVmSelectionPolicy;
import org.cloudbus.cloudsim.container.vmSelectionPolicies .PowerContainerVmSelectionPolicyMaximumUsage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.container.core.PowerContainer;
import org.cloudbus.cloudsim.container.core.Container;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.examples.container.ConstantsExamples;
import org.cloudbus.cloudsim.examples.container.UtilizationModelPlanetLabInMemoryExtended;
/**
* A simple example showing how to create a data center with one host, one VM,
* one container and run one cloudlet on it.
*/
public class ContainerCloudsimpso {
/**
* The cloudlet list.
*/
private static List cloudletList;
/**
* The vmlist.
*/
private static List vmList;
/**
* The vmlist.
*/
private static List containerList;
/**
* The hostList.
*/
private static List hostList;
/**
* Creates main() to run this example.
*
* @param args the args
*/
public static void main(String[] args) {
Log.printLine("Starting Particle Swarm Optimization...");
try {
/**
* number of cloud Users
*/
int num_user = 1;
/**
* The fields of calender have been initialized with the current
* date and time.
*/
Calendar calendar = Calendar.getInstance();
/**
* Deactivating the event tracing
*/
boolean trace_flag = false;
/**
* 1- Like CloudSim the first step is initializing the CloudSim
* Package before creating any entities.
*
*/
CloudSim.init(num_user, calendar, trace_flag);
/**
* 2- Defining the container allocation Policy. This policy
* determines how Containers are allocated to VMs in the data
* center.
*
*/
ContainerAllocationPolicy containerAllocationPolicy = new PowerContainerAllocationPolicySimple();
/**
* 3- Defining the VM selection Policy. This policy determines which
* VMs should be selected for migration when a host is identified as
* over-loaded.
*
*/
PowerContainerVmSelectionPolicy vmSelectionPolicy = new PowerContainerVmSelectionPolicyMaximumUsage();
/**
* 4- Defining the host selection Policy. This policy determines
* which hosts should be selected as migration destination.
*
*/
HostSelectionPolicy hostSelectionPolicy = new HostSelectionPolicyFirstFit();
/**
* 5- Defining the thresholds for selecting the under-utilized and
* over-utilized hosts.
*/
double overUtilizationThreshold = 0.80;
double underUtilizationThreshold = 0.70;
/**
* 6- The host list is created considering the number of hosts, and
* host types which are specified in the {@link ConstantsExamples}.
*/
hostList = new ArrayList();
hostList = createHostList(ConstantsExamples.NUMBER_HOSTS);
cloudletList = new ArrayList();
vmList = new ArrayList();
/**
* 7- The container allocation policy which defines the allocation
* of VMs to containers.
*/
ContainerVmAllocationPolicy vmAllocationPolicy = new PowerContainerVmAllocationPolicyMigrationAbstractHostSelection(hostList, vmSelectionPolicy,
hostSelectionPolicy, overUtilizationThreshold, underUtilizationThreshold);
/**
* 8- The overbooking factor for allocating containers to VMs. This
* factor is used by the broker for the allocation process.
*/
int overBookingFactor = 80;
PsoContainerDatacenterBroker broker = createPsoBroker(overBookingFactor);
int brokerId = broker.getId();
broker.setHostList(hostList);
/**
* 9- Creating the cloudlet, container and VM lists for submitting
* to the broker.
*/
cloudletList = createContainerCloudletList(brokerId, ConstantsExamples.NUMBER_CLOUDLETS);
containerList = createContainerList(brokerId, ConstantsExamples.NUMBER_CLOUDLETS);
vmList = createVmList(brokerId, ConstantsExamples.NUMBER_VMS);
/**
* 10- The address for logging the statistics of the VMs, containers
* in the data center.
*/
String logAddress = "~/Results";
@SuppressWarnings("unused")
PowerContainerDatacenter e = (PowerContainerDatacenter) createDatacenter("datacenter",
PowerContainerDatacenterCM.class, hostList, vmAllocationPolicy, containerAllocationPolicy,
getExperimentName("ContainerCloudSimExample-1", String.valueOf(overBookingFactor)),
ConstantsExamples.SCHEDULING_INTERVAL, logAddress,
ConstantsExamples.VM_STARTTUP_DELAY, ConstantsExamples.CONTAINER_STARTTUP_DELAY);
/**
* 11- Submitting the cloudlet's , container's , and VM's lists to
* the broker.
*/
broker.submitCloudletList(cloudletList.subList(0, containerList.size()));
broker.submitContainerList(containerList);
broker.submitVmList(vmList);
/**
* 12- Determining the simulation termination time according to the
* cloudlet's workload.
*/
CloudSim.terminateSimulation(86400.00);
/**
* 13- Starting the simualtion.
*/
CloudSim.startSimulation();
/**
* 14- Stopping the simualtion.
*/
CloudSim.stopSimulation();
/**
* 15- Printing the results when the simulation is finished.
*/
List newList = broker.getCloudletReceivedList();
printCloudletList(newList);
Log.printLine("ContainerCloudSimExample1 finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
private static PsoContainerDatacenterBroker createPsoBroker(int overBookingFactor) {
PsoContainerDatacenterBroker broker = null;
try {
broker = new PsoContainerDatacenterBroker("PSO_Broker", overBookingFactor);
} catch (Exception var2) {
var2.printStackTrace();
System.exit(0);
}
return broker;
}
/**
* It creates a specific name for the experiment which is used for creating
* the Log address folder.
*/
private static String getExperimentName(String... args) {
StringBuilder experimentName = new StringBuilder();
for (int i = 0; i < args.length; ++i) {
if (!args[i].isEmpty()) {
if (i != 0) {
experimentName.append("_");
}
experimentName.append(args[i]);
}
}
return experimentName.toString();
}
/**
* Creates the broker.
*
* @param overBookingFactor
* @return the datacenter broker
*/
private static ContainerDatacenterBroker createBroker(int overBookingFactor) {
ContainerDatacenterBroker broker = null;
try {
broker = new ContainerDatacenterBroker("Broker", overBookingFactor);
} catch (Exception var2) {
var2.printStackTrace();
System.exit(0);
}
return broker;
}
/**
* Prints the Cloudlet objects.
*
* @param list list of Cloudlets
*/
private static void printCloudletList(List list) {
int size = list.size();
ContainerCloudlet cloudlet;
String indent = " ";
Log.printLine();
Log.printLine("========== OUTPUT ==========");
Log.printLine("Cloudlet ID" + indent + "Container ID" + indent + "STATUS" + indent
+ "Data center ID" + indent + "VM ID" + indent + "Time" + indent
+ "Start Time" + indent + "Finish Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
Log.print(indent + cloudlet.getCloudletId() + indent);
// Print Container ID
Log.print(cloudlet.getContainerId() + indent);
if (cloudlet.getCloudletStatusString().equals("Success")) {
Log.print("SUCCESS");
Log.printLine(indent + indent + cloudlet.getResourceId()
+ indent + indent + indent + cloudlet.getVmId()
+ indent + indent
+ dft.format(cloudlet.getActualCPUTime()) + indent
+ indent + dft.format(cloudlet.getExecStartTime())
+ indent + indent
+ dft.format(cloudlet.getFinishTime()));
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Create the Virtual machines and add them to the list
*
* @param brokerId
* @param containerVmsNumber
*/
private static ArrayList createVmList(int brokerId, int containerVmsNumber) {
ArrayList containerVms = new ArrayList();
for (int i = 0; i < containerVmsNumber; ++i) {
ArrayList peList = new ArrayList();
int vmType = i / (int) Math.ceil((double) containerVmsNumber / 4.0D);
for (int j = 0; j < ConstantsExamples.VM_PES[vmType]; ++j) {
peList.add(new ContainerPe(j,
new ContainerPeProvisionerSimple((double) ConstantsExamples.VM_MIPS[vmType])));
}
containerVms.add(new PowerContainerVm(IDs.pollId(ContainerVm.class), brokerId,
(double) ConstantsExamples.VM_MIPS[vmType], (float) ConstantsExamples.VM_RAM[vmType],
ConstantsExamples.VM_BW, ConstantsExamples.VM_SIZE, "Xen",
new ContainerSchedulerTimeSharedOverSubscription(peList),
new ContainerRamProvisionerSimple(ConstantsExamples.VM_RAM[vmType]),
new ContainerBwProvisionerSimple(ConstantsExamples.VM_BW),
peList, ConstantsExamples.SCHEDULING_INTERVAL));
}
return containerVms;
}
/**
* Create the host list considering the specs listed in the
* {@link ConstantsExamples}.
*
* @param hostsNumber
* @return
*/
public static List createHostList(int hostsNumber) {
ArrayList hostList = new ArrayList();
for (int i = 0; i < hostsNumber; ++i) {
int hostType = i / (int) Math.ceil((double) hostsNumber / 3.0D);
ArrayList peList = new ArrayList();
for (int j = 0; j < ConstantsExamples.HOST_PES[hostType]; ++j) {
peList.add(new ContainerVmPe(j,
new ContainerVmPeProvisionerSimple((double) ConstantsExamples.HOST_MIPS[hostType])));
}
hostList.add(new PowerContainerHostUtilizationHistory(IDs.pollId(ContainerHost.class),
new ContainerVmRamProvisionerSimple(ConstantsExamples.HOST_RAM[hostType]),
new ContainerVmBwProvisionerSimple(1000000L), 1000000L, peList,
new ContainerVmSchedulerTimeSharedOverSubscription(peList),
ConstantsExamples.HOST_POWER[hostType]));
}
return hostList;
}
/**
* Create the data center
*
* @param name
* @param datacenterClass
* @param hostList
* @param vmAllocationPolicy
* @param containerAllocationPolicy
* @param experimentName
* @param logAddress
* @return
* @throws Exception
*/
public static ContainerDatacenter createDatacenter(String name, Class< extends ContainerDatacenter> datacenterClass,
List hostList,
ContainerVmAllocationPolicy vmAllocationPolicy,
ContainerAllocationPolicy containerAllocationPolicy,
String experimentName, double schedulingInterval, String logAddress, double VMStartupDelay,
double ContainerStartupDelay) throws Exception {
String arch = "x86";
String os = "Linux";
String vmm = "Xen";
double time_zone = 10.0D;
double cost = 3.0D;
double costPerMem = 0.05D;
double costPerStorage = 0.001D;
double costPerBw = 0.0D;
ContainerDatacenterCharacteristics characteristics = new ContainerDatacenterCharacteristics(arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage,
costPerBw);
ContainerDatacenter datacenter = new PowerContainerDatacenterCM(name, characteristics, vmAllocationPolicy,
containerAllocationPolicy, new LinkedList(), schedulingInterval, experimentName, logAddress,
VMStartupDelay, ContainerStartupDelay);
return datacenter;
}
/**
* create the containers for hosting the cloudlets and binding them
* together.
*
* @param brokerId
* @param containersNumber
* @return
*/
public static List createContainerList(int brokerId, int containersNumber) {
ArrayList containers = new ArrayList();
for (int i = 0; i < containersNumber; ++i) {
int containerType = i / (int) Math.ceil((double) containersNumber / 3.0D);
containers.add(new PowerContainer(IDs.pollId(Container.class), brokerId, ( double) ConstantsExamples.CONTAINER_MIPS[containerType], ConstantsExamples.CONTAINER_PES[containerType], ConstantsExamples.CONTAINER_RAM[containerType], ConstantsExamples.CONTAINER_BW, 0L, "Xen",
new ContainerCloudletSchedulerDynamicWorkload( ConstantsExamples.CONTAINER_MIPS[containerType], ConstantsExamples.CONTAINER_PES[containerType]), ConstantsExamples.SCHEDULING_INTERVAL));
}
return containers;
}
/**
* Creating the cloudlet list that are going to run on containers
*
* @param brokerId
* @param numberOfCloudlets
* @return
* @throws FileNotFoundException
*/
public static List createContainerCloudletList(int brokerId, int numberOfCloudlets)
throws FileNotFoundException {
String inputFolderName = "/home/soft13/soft13/Project 2019/Cloudsim-4.0-examples/src/workload/planetlab";
// String inputFolderName = "/home/soft13/soft13/Project 2025/containercloudsim/ContainerCloudsim/dax/CyberShake/CyberShake_30.xml";
ArrayList cloudletList = new ArrayList();
long fileSize = 300L;
long outputSize = 300L;
UtilizationModelNull utilizationModelNull = new UtilizationModelNull();
java.io.File inputFolder1 = new java.io.File(inputFolderName);
java.io.File[] files1 = inputFolder1.listFiles();
int createdCloudlets = 0;
for (java.io.File aFiles1 : files1) {
java.io.File inputFolder = new java.io.File(aFiles1.toString());
java.io.File[] files = inputFolder.listFiles();
for (int i = 0; i < files.length; ++i) {
if (createdCloudlets < numberOfCloudlets) {
ContainerCloudlet cloudlet = null;
try {
cloudlet = new ContainerCloudlet(IDs.pollId(ContainerCloudlet.class), ConstantsExamples.CLOUDLET_LENGTH, 1,
fileSize, outputSize,
new UtilizationModelPlanetLabInMemoryExtended(files[i].getAbsolutePath(), 300.0D),
utilizationModelNull, utilizationModelNull);
} catch (Exception var13) {
var13.printStackTrace();
System.exit(0);
}
cloudlet.setUserId(brokerId);
cloudletList.add(cloudlet);
createdCloudlets += 1;
} else {
return cloudletList;
}
}
}
return cloudletList;
}
}