This commit is contained in:
2021-04-06 00:45:28 +02:00
commit 17fabc368e
836 changed files with 3042963 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,251 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.List;
/**
* CloudletScheduler is an abstract class that represents the policy of scheduling performed by a
* virtual machine. So, classes extending this must execute Cloudlets. Also, the interface for
* cloudlet management is also implemented in this class.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public abstract class CloudletScheduler {
/** The previous time. */
private double previousTime;
/** The current mips share. */
private List<Double> currentMipsShare;
/**
* Creates a new CloudletScheduler object. This method must be invoked before starting the
* actual simulation.
*
* @pre $none
* @post $none
*/
public CloudletScheduler() {
setPreviousTime(0.0);
}
/**
* Updates the processing of cloudlets running under management of this scheduler.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each processor available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is no
* next events
* @pre currentTime >= 0
* @post $none
*/
public abstract double updateVmProcessing(double currentTime, List<Double> mipsShare);
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param gl the submited cloudlet
* @param fileTransferTime time required to move the required files from the SAN to the VM
* @return expected finish time of this cloudlet, or 0 if it is in a waiting queue
* @pre gl != null
* @post $none
*/
public abstract double cloudletSubmit(Cloudlet gl, double fileTransferTime);
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param gl the submited cloudlet
* @return expected finish time of this cloudlet, or 0 if it is in a waiting queue
* @pre gl != null
* @post $none
*/
public abstract double cloudletSubmit(Cloudlet gl);
/**
* Cancels execution of a cloudlet.
*
* @param clId ID of the cloudlet being cancealed
* @return the canceled cloudlet, $null if not found
* @pre $none
* @post $none
*/
public abstract Cloudlet cloudletCancel(int clId);
/**
* Pauses execution of a cloudlet.
*
* @param clId ID of the cloudlet being paused
* @return $true if cloudlet paused, $false otherwise
* @pre $none
* @post $none
*/
public abstract boolean cloudletPause(int clId);
/**
* Resumes execution of a paused cloudlet.
*
* @param clId ID of the cloudlet being resumed
* @return expected finish time of the cloudlet, 0.0 if queued
* @pre $none
* @post $none
*/
public abstract double cloudletResume(int clId);
/**
* Processes a finished cloudlet.
*
* @param rcl finished cloudlet
* @pre rgl != $null
* @post $none
*/
public abstract void cloudletFinish(ResCloudlet rcl);
/**
* Gets the status of a cloudlet.
*
* @param clId ID of the cloudlet
* @return status of the cloudlet, -1 if cloudlet not found
* @pre $none
* @post $none
*/
public abstract int getCloudletStatus(int clId);
/**
* Informs about completion of some cloudlet in the VM managed by this scheduler.
*
* @return $true if there is at least one finished cloudlet; $false otherwise
* @pre $none
* @post $none
*/
public abstract boolean isFinishedCloudlets();
/**
* Returns the next cloudlet in the finished list, $null if this list is empty.
*
* @return a finished cloudlet
* @pre $none
* @post $none
*/
public abstract Cloudlet getNextFinishedCloudlet();
/**
* Returns the number of cloudlets runnning in the virtual machine.
*
* @return number of cloudlets runnning
* @pre $none
* @post $none
*/
public abstract int runningCloudlets();
/**
* Returns one cloudlet to migrate to another vm.
*
* @return one running cloudlet
* @pre $none
* @post $none
*/
public abstract Cloudlet migrateCloudlet();
/**
* Get utilization created by all cloudlets.
*
* @param time the time
* @return total utilization
*/
public abstract double getTotalUtilizationOfCpu(double time);
/**
* Gets the current requested mips.
*
* @return the current mips
*/
public abstract List<Double> getCurrentRequestedMips();
/**
* Gets the total current mips for the Cloudlet.
*
* @param rcl the rcl
* @param mipsShare the mips share
* @return the total current mips
*/
public abstract double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare);
/**
* Gets the total current requested mips for cloudlet.
*
* @param rcl the rcl
* @param time the time
* @return the total current requested mips for cloudlet
*/
public abstract double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time);
/**
* Gets the total current allocated mips for cloudlet.
*
* @param rcl the rcl
* @param time the time
* @return the total current allocated mips for cloudlet
*/
public abstract double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time);
/**
* Gets the current requested ram.
*
* @return the current requested ram
*/
public abstract double getCurrentRequestedUtilizationOfRam();
/**
* Gets the current requested bw.
*
* @return the current requested bw
*/
public abstract double getCurrentRequestedUtilizationOfBw();
/**
* Gets the previous time.
*
* @return the previous time
*/
public double getPreviousTime() {
return previousTime;
}
/**
* Sets the previous time.
*
* @param previousTime the new previous time
*/
protected void setPreviousTime(double previousTime) {
this.previousTime = previousTime;
}
/**
* Sets the current mips share.
*
* @param currentMipsShare the new current mips share
*/
protected void setCurrentMipsShare(List<Double> currentMipsShare) {
this.currentMipsShare = currentMipsShare;
}
/**
* Gets the current mips share.
*
* @return the current mips share
*/
public List<Double> getCurrentMipsShare() {
return currentMipsShare;
}
}

View File

@@ -0,0 +1,398 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.entities.Tuple;
/**
* CloudletSchedulerDynamicWorkload implements a policy of scheduling performed by a virtual machine
* assuming that there is just one cloudlet which is working as an online service.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class CloudletSchedulerDynamicWorkload extends CloudletSchedulerTimeShared {
/** The mips. */
private double mips;
/** The number of PEs. */
private int numberOfPes;
/** The total mips. */
private double totalMips;
/** The under allocated mips. */
private Map<String, Double> underAllocatedMips;
/** The cache previous time. */
private double cachePreviousTime;
/** The cache current requested mips. */
private List<Double> cacheCurrentRequestedMips;
/**
* Instantiates a new vM scheduler time shared.
*
* @param mips the mips
* @param numberOfPes the pes number
*/
public CloudletSchedulerDynamicWorkload(double mips, int numberOfPes) {
super();
setMips(mips);
setNumberOfPes(numberOfPes);
setTotalMips(getNumberOfPes() * getMips());
setUnderAllocatedMips(new HashMap<String, Double>());
setCachePreviousTime(-1);
}
/**
* Updates the processing of cloudlets running under management of this scheduler.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each Pe available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is
* no next events
* @pre currentTime >= 0
* @post $none
*/
@Override
public double updateVmProcessing(double currentTime, List<Double> mipsShare) {
setCurrentMipsShare(mipsShare);
double timeSpan = currentTime - getPreviousTime();
double nextEvent = Double.MAX_VALUE;
List<ResCloudlet> cloudletsToFinish = new ArrayList<ResCloudlet>();
for (ResCloudlet rcl : getCloudletExecList()) {
rcl.updateCloudletFinishedSoFar((long) (timeSpan
* getTotalCurrentAllocatedMipsForCloudlet(rcl, getPreviousTime()) * Consts.MILLION));
if (rcl.getRemainingCloudletLength() == 0) { // finished: remove from the list
System.out.println("Tuple "+((Tuple)rcl.getCloudlet()).getActualTupleId()+" is finished at time "+CloudSim.clock());
cloudletsToFinish.add(rcl);
continue;
} else { // not finish: estimate the finish time
double estimatedFinishTime = getEstimatedFinishTime(rcl, currentTime);
if (estimatedFinishTime - currentTime < CloudSim.getMinTimeBetweenEvents()) {
estimatedFinishTime = currentTime + CloudSim.getMinTimeBetweenEvents();
}
if (estimatedFinishTime < nextEvent) {
nextEvent = estimatedFinishTime;
}
}
}
for (ResCloudlet rgl : cloudletsToFinish) {
getCloudletExecList().remove(rgl);
cloudletFinish(rgl);
}
setPreviousTime(currentTime);
if (getCloudletExecList().isEmpty()) {
return 0;
}
return nextEvent;
}
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param cl the cl
* @return predicted completion time
* @pre _gl != null
* @post $none
*/
@Override
public double cloudletSubmit(Cloudlet cl) {
return cloudletSubmit(cl, 0);
}
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param cl the cl
* @param fileTransferTime the file transfer time
* @return predicted completion time
* @pre _gl != null
* @post $none
*/
@Override
public double cloudletSubmit(Cloudlet cl, double fileTransferTime) {
ResCloudlet rcl = new ResCloudlet(cl);
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < cl.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
return getEstimatedFinishTime(rcl, getPreviousTime());
}
/**
* Processes a finished cloudlet.
*
* @param rcl finished cloudlet
* @pre rgl != $null
* @post $none
*/
@Override
public void cloudletFinish(ResCloudlet rcl) {
rcl.setCloudletStatus(Cloudlet.SUCCESS);
rcl.finalizeCloudlet();
getCloudletFinishedList().add(rcl);
}
/**
* Get utilization created by all cloudlets.
*
* @param time the time
* @return total utilization
*/
@Override
public double getTotalUtilizationOfCpu(double time) {
double totalUtilization = 0;
for (ResCloudlet rcl : getCloudletExecList()) {
totalUtilization += rcl.getCloudlet().getUtilizationOfCpu(time);
}
return totalUtilization;
}
/**
* Gets the current mips.
*
* @return the current mips
*/
@Override
public List<Double> getCurrentRequestedMips() {
if (getCachePreviousTime() == getPreviousTime()) {
return getCacheCurrentRequestedMips();
}
List<Double> currentMips = new ArrayList<Double>();
double totalMips = getTotalUtilizationOfCpu(getPreviousTime()) * getTotalMips();
double mipsForPe = totalMips / getNumberOfPes();
for (int i = 0; i < getNumberOfPes(); i++) {
currentMips.add(mipsForPe);
}
setCachePreviousTime(getPreviousTime());
setCacheCurrentRequestedMips(currentMips);
return currentMips;
}
/**
* Gets the current mips.
*
* @param rcl the rcl
* @param time the time
* @return the current mips
*/
@Override
public double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time) {
return rcl.getCloudlet().getUtilizationOfCpu(time) * getTotalMips();
}
/**
* Gets the total current mips for the clouddlet.
*
* @param rcl the rcl
* @param mipsShare the mips share
* @return the total current mips
*/
@Override
public double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare) {
double totalCurrentMips = 0.0;
if (mipsShare != null) {
int neededPEs = rcl.getNumberOfPes();
for (double mips : mipsShare) {
totalCurrentMips += mips;
neededPEs--;
if (neededPEs <= 0) {
break;
}
}
}
return totalCurrentMips;
}
/**
* Gets the current mips.
*
* @param rcl the rcl
* @param time the time
* @return the current mips
*/
@Override
public double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time) {
double totalCurrentRequestedMips = getTotalCurrentRequestedMipsForCloudlet(rcl, time);
double totalCurrentAvailableMips = getTotalCurrentAvailableMipsForCloudlet(rcl, getCurrentMipsShare());
if (totalCurrentRequestedMips > totalCurrentAvailableMips) {
return totalCurrentAvailableMips;
}
return totalCurrentRequestedMips;
}
/**
* Update under allocated mips for cloudlet.
*
* @param rcl the rgl
* @param mips the mips
*/
public void updateUnderAllocatedMipsForCloudlet(ResCloudlet rcl, double mips) {
if (getUnderAllocatedMips().containsKey(rcl.getUid())) {
mips += getUnderAllocatedMips().get(rcl.getUid());
}
getUnderAllocatedMips().put(rcl.getUid(), mips);
}
/**
* Get estimated cloudlet completion time.
*
* @param rcl the rcl
* @param time the time
* @return the estimated finish time
*/
public double getEstimatedFinishTime(ResCloudlet rcl, double time) {
return time
+ ((rcl.getRemainingCloudletLength()) / getTotalCurrentAllocatedMipsForCloudlet(rcl, time));
}
/**
* Gets the total current mips.
*
* @return the total current mips
*/
public int getTotalCurrentMips() {
int totalCurrentMips = 0;
for (double mips : getCurrentMipsShare()) {
totalCurrentMips += mips;
}
return totalCurrentMips;
}
/**
* Sets the total mips.
*
* @param mips the new total mips
*/
public void setTotalMips(double mips) {
totalMips = mips;
}
/**
* Gets the total mips.
*
* @return the total mips
*/
public double getTotalMips() {
return totalMips;
}
/**
* Sets the pes number.
*
* @param pesNumber the new pes number
*/
public void setNumberOfPes(int pesNumber) {
numberOfPes = pesNumber;
}
/**
* Gets the pes number.
*
* @return the pes number
*/
public int getNumberOfPes() {
return numberOfPes;
}
/**
* Sets the mips.
*
* @param mips the new mips
*/
public void setMips(double mips) {
this.mips = mips;
}
/**
* Gets the mips.
*
* @return the mips
*/
public double getMips() {
return mips;
}
/**
* Sets the under allocated mips.
*
* @param underAllocatedMips the under allocated mips
*/
public void setUnderAllocatedMips(Map<String, Double> underAllocatedMips) {
this.underAllocatedMips = underAllocatedMips;
}
/**
* Gets the under allocated mips.
*
* @return the under allocated mips
*/
public Map<String, Double> getUnderAllocatedMips() {
return underAllocatedMips;
}
/**
* Gets the cache previous time.
*
* @return the cache previous time
*/
protected double getCachePreviousTime() {
return cachePreviousTime;
}
/**
* Sets the cache previous time.
*
* @param cachePreviousTime the new cache previous time
*/
protected void setCachePreviousTime(double cachePreviousTime) {
this.cachePreviousTime = cachePreviousTime;
}
/**
* Gets the cache current requested mips.
*
* @return the cache current requested mips
*/
protected List<Double> getCacheCurrentRequestedMips() {
return cacheCurrentRequestedMips;
}
/**
* Sets the cache current requested mips.
*
* @param cacheCurrentRequestedMips the new cache current requested mips
*/
protected void setCacheCurrentRequestedMips(List<Double> cacheCurrentRequestedMips) {
this.cacheCurrentRequestedMips = cacheCurrentRequestedMips;
}
}

View File

@@ -0,0 +1,668 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* CloudletSchedulerSpaceShared implements a policy of scheduling performed by a virtual machine. It
* consider that there will be only one cloudlet per VM. Other cloudlets will be in a waiting list.
* We consider that file transfer from cloudlets waiting happens before cloudlet execution. I.e.,
* even though cloudlets must wait for CPU, data transfer happens as soon as cloudlets are
* submitted.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class CloudletSchedulerSpaceShared extends CloudletScheduler {
/** The cloudlet waiting list. */
private List<? extends ResCloudlet> cloudletWaitingList;
/** The cloudlet exec list. */
private List<? extends ResCloudlet> cloudletExecList;
/** The cloudlet paused list. */
private List<? extends ResCloudlet> cloudletPausedList;
/** The cloudlet finished list. */
private List<? extends ResCloudlet> cloudletFinishedList;
/** The current CPUs. */
protected int currentCpus;
/** The used PEs. */
protected int usedPes;
/**
* Creates a new CloudletSchedulerSpaceShared object. This method must be invoked before
* starting the actual simulation.
*
* @pre $none
* @post $none
*/
public CloudletSchedulerSpaceShared() {
super();
cloudletWaitingList = new ArrayList<ResCloudlet>();
cloudletExecList = new ArrayList<ResCloudlet>();
cloudletPausedList = new ArrayList<ResCloudlet>();
cloudletFinishedList = new ArrayList<ResCloudlet>();
usedPes = 0;
currentCpus = 0;
}
/**
* Updates the processing of cloudlets running under management of this scheduler.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each processor available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is
* no next events
* @pre currentTime >= 0
* @post $none
*/
@Override
public double updateVmProcessing(double currentTime, List<Double> mipsShare) {
setCurrentMipsShare(mipsShare);
double timeSpam = currentTime - getPreviousTime(); // time since last update
double capacity = 0.0;
int cpus = 0;
for (Double mips : mipsShare) { // count the CPUs available to the VMM
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus; // average capacity of each cpu
// each machine in the exec list has the same amount of cpu
for (ResCloudlet rcl : getCloudletExecList()) {
rcl.updateCloudletFinishedSoFar((long) (capacity * timeSpam * rcl.getNumberOfPes() * Consts.MILLION));
}
// no more cloudlets in this scheduler
if (getCloudletExecList().size() == 0 && getCloudletWaitingList().size() == 0) {
setPreviousTime(currentTime);
return 0.0;
}
// update each cloudlet
int finished = 0;
List<ResCloudlet> toRemove = new ArrayList<ResCloudlet>();
for (ResCloudlet rcl : getCloudletExecList()) {
// finished anyway, rounding issue...
if (rcl.getRemainingCloudletLength() == 0) {
toRemove.add(rcl);
cloudletFinish(rcl);
finished++;
}
}
getCloudletExecList().removeAll(toRemove);
// for each finished cloudlet, add a new one from the waiting list
if (!getCloudletWaitingList().isEmpty()) {
for (int i = 0; i < finished; i++) {
toRemove.clear();
for (ResCloudlet rcl : getCloudletWaitingList()) {
if ((currentCpus - usedPes) >= rcl.getNumberOfPes()) {
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int k = 0; k < rcl.getNumberOfPes(); k++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
usedPes += rcl.getNumberOfPes();
toRemove.add(rcl);
break;
}
}
getCloudletWaitingList().removeAll(toRemove);
}
}
// estimate finish time of cloudlets in the execution queue
double nextEvent = Double.MAX_VALUE;
for (ResCloudlet rcl : getCloudletExecList()) {
double remainingLength = rcl.getRemainingCloudletLength();
double estimatedFinishTime = currentTime + (remainingLength / (capacity * rcl.getNumberOfPes()));
if (estimatedFinishTime - currentTime < CloudSim.getMinTimeBetweenEvents()) {
estimatedFinishTime = currentTime + CloudSim.getMinTimeBetweenEvents();
}
if (estimatedFinishTime < nextEvent) {
nextEvent = estimatedFinishTime;
}
}
setPreviousTime(currentTime);
return nextEvent;
}
/**
* Cancels execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being cancealed
* @return the canceled cloudlet, $null if not found
* @pre $none
* @post $none
*/
@Override
public Cloudlet cloudletCancel(int cloudletId) {
// First, looks in the finished queue
for (ResCloudlet rcl : getCloudletFinishedList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletFinishedList().remove(rcl);
return rcl.getCloudlet();
}
}
// Then searches in the exec list
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletExecList().remove(rcl);
if (rcl.getRemainingCloudletLength() == 0) {
cloudletFinish(rcl);
} else {
rcl.setCloudletStatus(Cloudlet.CANCELED);
}
return rcl.getCloudlet();
}
}
// Now, looks in the paused queue
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletPausedList().remove(rcl);
return rcl.getCloudlet();
}
}
// Finally, looks in the waiting list
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
rcl.setCloudletStatus(Cloudlet.CANCELED);
getCloudletWaitingList().remove(rcl);
return rcl.getCloudlet();
}
}
return null;
}
/**
* Pauses execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being paused
* @return $true if cloudlet paused, $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean cloudletPause(int cloudletId) {
boolean found = false;
int position = 0;
// first, looks for the cloudlet in the exec list
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
// moves to the paused list
ResCloudlet rgl = getCloudletExecList().remove(position);
if (rgl.getRemainingCloudletLength() == 0) {
cloudletFinish(rgl);
} else {
rgl.setCloudletStatus(Cloudlet.PAUSED);
getCloudletPausedList().add(rgl);
}
return true;
}
// now, look for the cloudlet in the waiting list
position = 0;
found = false;
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
// moves to the paused list
ResCloudlet rgl = getCloudletWaitingList().remove(position);
if (rgl.getRemainingCloudletLength() == 0) {
cloudletFinish(rgl);
} else {
rgl.setCloudletStatus(Cloudlet.PAUSED);
getCloudletPausedList().add(rgl);
}
return true;
}
return false;
}
/**
* Processes a finished cloudlet.
*
* @param rcl finished cloudlet
* @pre rgl != $null
* @post $none
*/
@Override
public void cloudletFinish(ResCloudlet rcl) {
rcl.setCloudletStatus(Cloudlet.SUCCESS);
rcl.finalizeCloudlet();
getCloudletFinishedList().add(rcl);
usedPes -= rcl.getNumberOfPes();
}
/**
* Resumes execution of a paused cloudlet.
*
* @param cloudletId ID of the cloudlet being resumed
* @return $true if the cloudlet was resumed, $false otherwise
* @pre $none
* @post $none
*/
@Override
public double cloudletResume(int cloudletId) {
boolean found = false;
int position = 0;
// look for the cloudlet in the paused list
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
ResCloudlet rcl = getCloudletPausedList().remove(position);
// it can go to the exec list
if ((currentCpus - usedPes) >= rcl.getNumberOfPes()) {
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < rcl.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
long size = rcl.getRemainingCloudletLength();
size *= rcl.getNumberOfPes();
rcl.getCloudlet().setCloudletLength(size);
getCloudletExecList().add(rcl);
usedPes += rcl.getNumberOfPes();
// calculate the expected time for cloudlet completion
double capacity = 0.0;
int cpus = 0;
for (Double mips : getCurrentMipsShare()) {
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus;
long remainingLength = rcl.getRemainingCloudletLength();
double estimatedFinishTime = CloudSim.clock()
+ (remainingLength / (capacity * rcl.getNumberOfPes()));
return estimatedFinishTime;
} else {// no enough free PEs: go to the waiting queue
rcl.setCloudletStatus(Cloudlet.QUEUED);
long size = rcl.getRemainingCloudletLength();
size *= rcl.getNumberOfPes();
rcl.getCloudlet().setCloudletLength(size);
getCloudletWaitingList().add(rcl);
return 0.0;
}
}
// not found in the paused list: either it is in in the queue, executing or not exist
return 0.0;
}
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param cloudlet the submited cloudlet
* @param fileTransferTime time required to move the required files from the SAN to the VM
* @return expected finish time of this cloudlet, or 0 if it is in the waiting queue
* @pre gl != null
* @post $none
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet, double fileTransferTime) {
// it can go to the exec list
if ((currentCpus - usedPes) >= cloudlet.getNumberOfPes()) {
ResCloudlet rcl = new ResCloudlet(cloudlet);
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < cloudlet.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
usedPes += cloudlet.getNumberOfPes();
} else {// no enough free PEs: go to the waiting queue
ResCloudlet rcl = new ResCloudlet(cloudlet);
rcl.setCloudletStatus(Cloudlet.QUEUED);
getCloudletWaitingList().add(rcl);
return 0.0;
}
// calculate the expected time for cloudlet completion
double capacity = 0.0;
int cpus = 0;
for (Double mips : getCurrentMipsShare()) {
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus;
// use the current capacity to estimate the extra amount of
// time to file transferring. It must be added to the cloudlet length
double extraSize = capacity * fileTransferTime;
long length = cloudlet.getCloudletLength();
length += extraSize;
cloudlet.setCloudletLength(length);
return cloudlet.getCloudletLength() / capacity;
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#cloudletSubmit(cloudsim.Cloudlet)
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet) {
return cloudletSubmit(cloudlet, 0.0);
}
/**
* Gets the status of a cloudlet.
*
* @param cloudletId ID of the cloudlet
* @return status of the cloudlet, -1 if cloudlet not found
* @pre $none
* @post $none
*/
@Override
public int getCloudletStatus(int cloudletId) {
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
return -1;
}
/**
* Get utilization created by all cloudlets.
*
* @param time the time
* @return total utilization
*/
@Override
public double getTotalUtilizationOfCpu(double time) {
double totalUtilization = 0;
for (ResCloudlet gl : getCloudletExecList()) {
totalUtilization += gl.getCloudlet().getUtilizationOfCpu(time);
}
return totalUtilization;
}
/**
* Informs about completion of some cloudlet in the VM managed by this scheduler.
*
* @return $true if there is at least one finished cloudlet; $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean isFinishedCloudlets() {
return getCloudletFinishedList().size() > 0;
}
/**
* Returns the next cloudlet in the finished list, $null if this list is empty.
*
* @return a finished cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet getNextFinishedCloudlet() {
if (getCloudletFinishedList().size() > 0) {
return getCloudletFinishedList().remove(0).getCloudlet();
}
return null;
}
/**
* Returns the number of cloudlets runnning in the virtual machine.
*
* @return number of cloudlets runnning
* @pre $none
* @post $none
*/
@Override
public int runningCloudlets() {
return getCloudletExecList().size();
}
/**
* Returns one cloudlet to migrate to another vm.
*
* @return one running cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet migrateCloudlet() {
ResCloudlet rcl = getCloudletExecList().remove(0);
rcl.finalizeCloudlet();
Cloudlet cl = rcl.getCloudlet();
usedPes -= cl.getNumberOfPes();
return cl;
}
/**
* Gets the cloudlet waiting list.
*
* @param <T> the generic type
* @return the cloudlet waiting list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletWaitingList() {
return (List<T>) cloudletWaitingList;
}
/**
* Cloudlet waiting list.
*
* @param <T> the generic type
* @param cloudletWaitingList the cloudlet waiting list
*/
protected <T extends ResCloudlet> void cloudletWaitingList(List<T> cloudletWaitingList) {
this.cloudletWaitingList = cloudletWaitingList;
}
/**
* Gets the cloudlet exec list.
*
* @param <T> the generic type
* @return the cloudlet exec list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletExecList() {
return (List<T>) cloudletExecList;
}
/**
* Sets the cloudlet exec list.
*
* @param <T> the generic type
* @param cloudletExecList the new cloudlet exec list
*/
protected <T extends ResCloudlet> void setCloudletExecList(List<T> cloudletExecList) {
this.cloudletExecList = cloudletExecList;
}
/**
* Gets the cloudlet paused list.
*
* @param <T> the generic type
* @return the cloudlet paused list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletPausedList() {
return (List<T>) cloudletPausedList;
}
/**
* Sets the cloudlet paused list.
*
* @param <T> the generic type
* @param cloudletPausedList the new cloudlet paused list
*/
protected <T extends ResCloudlet> void setCloudletPausedList(List<T> cloudletPausedList) {
this.cloudletPausedList = cloudletPausedList;
}
/**
* Gets the cloudlet finished list.
*
* @param <T> the generic type
* @return the cloudlet finished list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletFinishedList() {
return (List<T>) cloudletFinishedList;
}
/**
* Sets the cloudlet finished list.
*
* @param <T> the generic type
* @param cloudletFinishedList the new cloudlet finished list
*/
protected <T extends ResCloudlet> void setCloudletFinishedList(List<T> cloudletFinishedList) {
this.cloudletFinishedList = cloudletFinishedList;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.CloudletScheduler#getCurrentRequestedMips()
*/
@Override
public List<Double> getCurrentRequestedMips() {
List<Double> mipsShare = new ArrayList<Double>();
if (getCurrentMipsShare() != null) {
for (Double mips : getCurrentMipsShare()) {
mipsShare.add(mips);
}
}
return mipsShare;
}
/*
* (non-Javadoc)
* @see
* org.cloudbus.cloudsim.CloudletScheduler#getTotalCurrentAvailableMipsForCloudlet(org.cloudbus
* .cloudsim.ResCloudlet, java.util.List)
*/
@Override
public double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare) {
double capacity = 0.0;
int cpus = 0;
for (Double mips : mipsShare) { // count the cpus available to the vmm
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus; // average capacity of each cpu
return capacity;
}
/*
* (non-Javadoc)
* @see
* org.cloudbus.cloudsim.CloudletScheduler#getTotalCurrentAllocatedMipsForCloudlet(org.cloudbus
* .cloudsim.ResCloudlet, double)
*/
@Override
public double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time) {
// TODO Auto-generated method stub
return 0.0;
}
/*
* (non-Javadoc)
* @see
* org.cloudbus.cloudsim.CloudletScheduler#getTotalCurrentRequestedMipsForCloudlet(org.cloudbus
* .cloudsim.ResCloudlet, double)
*/
@Override
public double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time) {
// TODO Auto-generated method stub
return 0.0;
}
@Override
public double getCurrentRequestedUtilizationOfRam() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getCurrentRequestedUtilizationOfBw() {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -0,0 +1,545 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.entities.Tuple;
/**
* CloudletSchedulerTimeShared implements a policy of scheduling performed by a virtual machine.
* Cloudlets execute time-shared in VM.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class CloudletSchedulerTimeShared extends CloudletScheduler {
/** The cloudlet exec list. */
private List<? extends ResCloudlet> cloudletExecList;
/** The cloudlet paused list. */
private List<? extends ResCloudlet> cloudletPausedList;
/** The cloudlet finished list. */
private List<? extends ResCloudlet> cloudletFinishedList;
/** The current cp us. */
protected int currentCPUs;
/**
* Creates a new CloudletSchedulerTimeShared object. This method must be invoked before starting
* the actual simulation.
*
* @pre $none
* @post $none
*/
public CloudletSchedulerTimeShared() {
super();
cloudletExecList = new ArrayList<ResCloudlet>();
cloudletPausedList = new ArrayList<ResCloudlet>();
cloudletFinishedList = new ArrayList<ResCloudlet>();
currentCPUs = 0;
}
/**
* Updates the processing of cloudlets running under management of this scheduler.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each processor available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is
* no next events
* @pre currentTime >= 0
* @post $none
*/
@Override
public double updateVmProcessing(double currentTime, List<Double> mipsShare) {
setCurrentMipsShare(mipsShare);
double timeSpam = currentTime - getPreviousTime();
for (ResCloudlet rcl : getCloudletExecList()) {
rcl.updateCloudletFinishedSoFar((long) (getCapacity(mipsShare) * timeSpam * rcl.getNumberOfPes() * Consts.MILLION));
//System.out.println(getTotalCurrentAllocatedMipsForCloudlet(rcl, getPreviousTime()));
//OLA System.out.println(CloudSim.clock()+ " : Remaining length of tuple ID "+((Tuple)rcl.getCloudlet()).getActualTupleId()+" = "+rcl.getRemainingCloudletLength());
}
if (getCloudletExecList().size() == 0) {
setPreviousTime(currentTime);
return 0.0;
}
// check finished cloudlets
double nextEvent = Double.MAX_VALUE;
List<ResCloudlet> toRemove = new ArrayList<ResCloudlet>();
for (ResCloudlet rcl : getCloudletExecList()) {
long remainingLength = rcl.getRemainingCloudletLength();
if (remainingLength == 0) {// finished: remove from the list
toRemove.add(rcl);
cloudletFinish(rcl);
continue;
}
}
getCloudletExecList().removeAll(toRemove);
// estimate finish time of cloudlets
for (ResCloudlet rcl : getCloudletExecList()) {
double estimatedFinishTime = currentTime
+ (rcl.getRemainingCloudletLength() / (getCapacity(mipsShare) * rcl.getNumberOfPes()));
if (estimatedFinishTime - currentTime < CloudSim.getMinTimeBetweenEvents()) {
estimatedFinishTime = currentTime + CloudSim.getMinTimeBetweenEvents();
}
if (estimatedFinishTime < nextEvent) {
nextEvent = estimatedFinishTime;
}
}
setPreviousTime(currentTime);
return nextEvent;
}
/**
* Gets the capacity.
*
* @param mipsShare the mips share
* @return the capacity
*/
protected double getCapacity(List<Double> mipsShare) {
double capacity = 0.0;
int cpus = 0;
for (Double mips : mipsShare) {
capacity += mips;
if (mips > 0.0) {
cpus++;
}
}
currentCPUs = cpus;
int pesInUse = 0;
for (ResCloudlet rcl : getCloudletExecList()) {
pesInUse += rcl.getNumberOfPes();
}
if (pesInUse > currentCPUs) {
capacity /= pesInUse;
} else {
capacity /= currentCPUs;
}
return capacity;
}
/**
* Cancels execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being cancealed
* @return the canceled cloudlet, $null if not found
* @pre $none
* @post $none
*/
@Override
public Cloudlet cloudletCancel(int cloudletId) {
boolean found = false;
int position = 0;
// First, looks in the finished queue
found = false;
for (ResCloudlet rcl : getCloudletFinishedList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
return getCloudletFinishedList().remove(position).getCloudlet();
}
// Then searches in the exec list
position=0;
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
ResCloudlet rcl = getCloudletExecList().remove(position);
if (rcl.getRemainingCloudletLength() == 0) {
cloudletFinish(rcl);
} else {
rcl.setCloudletStatus(Cloudlet.CANCELED);
}
return rcl.getCloudlet();
}
// Now, looks in the paused queue
found = false;
position=0;
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
rcl.setCloudletStatus(Cloudlet.CANCELED);
break;
}
position++;
}
if (found) {
return getCloudletPausedList().remove(position).getCloudlet();
}
return null;
}
/**
* Pauses execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being paused
* @return $true if cloudlet paused, $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean cloudletPause(int cloudletId) {
boolean found = false;
int position = 0;
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
// remove cloudlet from the exec list and put it in the paused list
ResCloudlet rcl = getCloudletExecList().remove(position);
if (rcl.getRemainingCloudletLength() == 0) {
cloudletFinish(rcl);
} else {
rcl.setCloudletStatus(Cloudlet.PAUSED);
getCloudletPausedList().add(rcl);
}
return true;
}
return false;
}
/**
* Processes a finished cloudlet.
*
* @param rcl finished cloudlet
* @pre rgl != $null
* @post $none
*/
@Override
public void cloudletFinish(ResCloudlet rcl) {
rcl.setCloudletStatus(Cloudlet.SUCCESS);
rcl.finalizeCloudlet();
getCloudletFinishedList().add(rcl);
}
/**
* Resumes execution of a paused cloudlet.
*
* @param cloudletId ID of the cloudlet being resumed
* @return expected finish time of the cloudlet, 0.0 if queued
* @pre $none
* @post $none
*/
@Override
public double cloudletResume(int cloudletId) {
boolean found = false;
int position = 0;
// look for the cloudlet in the paused list
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
ResCloudlet rgl = getCloudletPausedList().remove(position);
rgl.setCloudletStatus(Cloudlet.INEXEC);
getCloudletExecList().add(rgl);
// calculate the expected time for cloudlet completion
// first: how many PEs do we have?
double remainingLength = rgl.getRemainingCloudletLength();
double estimatedFinishTime = CloudSim.clock()
+ (remainingLength / (getCapacity(getCurrentMipsShare()) * rgl.getNumberOfPes()));
return estimatedFinishTime;
}
return 0.0;
}
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param cloudlet the submited cloudlet
* @param fileTransferTime time required to move the required files from the SAN to the VM
* @return expected finish time of this cloudlet
* @pre gl != null
* @post $none
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet, double fileTransferTime) {
ResCloudlet rcl = new ResCloudlet(cloudlet);
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < cloudlet.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
// use the current capacity to estimate the extra amount of
// time to file transferring. It must be added to the cloudlet length
double extraSize = getCapacity(getCurrentMipsShare()) * fileTransferTime;
long length = (long) (cloudlet.getCloudletLength() + extraSize);
cloudlet.setCloudletLength(length);
return cloudlet.getCloudletLength() / getCapacity(getCurrentMipsShare());
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#cloudletSubmit(cloudsim.Cloudlet)
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet) {
return cloudletSubmit(cloudlet, 0.0);
}
/**
* Gets the status of a cloudlet.
*
* @param cloudletId ID of the cloudlet
* @return status of the cloudlet, -1 if cloudlet not found
* @pre $none
* @post $none
*/
@Override
public int getCloudletStatus(int cloudletId) {
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
return -1;
}
/**
* Get utilization created by all cloudlets.
*
* @param time the time
* @return total utilization
*/
@Override
public double getTotalUtilizationOfCpu(double time) {
double totalUtilization = 0;
for (ResCloudlet gl : getCloudletExecList()) {
totalUtilization += gl.getCloudlet().getUtilizationOfCpu(time);
}
return totalUtilization;
}
/**
* Informs about completion of some cloudlet in the VM managed by this scheduler.
*
* @return $true if there is at least one finished cloudlet; $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean isFinishedCloudlets() {
return getCloudletFinishedList().size() > 0;
}
/**
* Returns the next cloudlet in the finished list, $null if this list is empty.
*
* @return a finished cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet getNextFinishedCloudlet() {
if (getCloudletFinishedList().size() > 0) {
return getCloudletFinishedList().remove(0).getCloudlet();
}
return null;
}
/**
* Returns the number of cloudlets runnning in the virtual machine.
*
* @return number of cloudlets runnning
* @pre $none
* @post $none
*/
@Override
public int runningCloudlets() {
return getCloudletExecList().size();
}
/**
* Returns one cloudlet to migrate to another vm.
*
* @return one running cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet migrateCloudlet() {
ResCloudlet rgl = getCloudletExecList().remove(0);
rgl.finalizeCloudlet();
return rgl.getCloudlet();
}
/**
* Gets the cloudlet exec list.
*
* @param <T> the generic type
* @return the cloudlet exec list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletExecList() {
return (List<T>) cloudletExecList;
}
/**
* Sets the cloudlet exec list.
*
* @param <T> the generic type
* @param cloudletExecList the new cloudlet exec list
*/
protected <T extends ResCloudlet> void setCloudletExecList(List<T> cloudletExecList) {
this.cloudletExecList = cloudletExecList;
}
/**
* Gets the cloudlet paused list.
*
* @param <T> the generic type
* @return the cloudlet paused list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletPausedList() {
return (List<T>) cloudletPausedList;
}
/**
* Sets the cloudlet paused list.
*
* @param <T> the generic type
* @param cloudletPausedList the new cloudlet paused list
*/
protected <T extends ResCloudlet> void setCloudletPausedList(List<T> cloudletPausedList) {
this.cloudletPausedList = cloudletPausedList;
}
/**
* Gets the cloudlet finished list.
*
* @param <T> the generic type
* @return the cloudlet finished list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletFinishedList() {
return (List<T>) cloudletFinishedList;
}
/**
* Sets the cloudlet finished list.
*
* @param <T> the generic type
* @param cloudletFinishedList the new cloudlet finished list
*/
protected <T extends ResCloudlet> void setCloudletFinishedList(List<T> cloudletFinishedList) {
this.cloudletFinishedList = cloudletFinishedList;
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#getCurrentRequestedMips()
*/
@Override
public List<Double> getCurrentRequestedMips() {
List<Double> mipsShare = new ArrayList<Double>();
return mipsShare;
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#getTotalCurrentAvailableMipsForCloudlet(cloudsim.ResCloudlet,
* java.util.List)
*/
@Override
public double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare) {
return getCapacity(getCurrentMipsShare());
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#getTotalCurrentAllocatedMipsForCloudlet(cloudsim.ResCloudlet,
* double)
*/
@Override
public double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time) {
return 0.0;
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#getTotalCurrentRequestedMipsForCloudlet(cloudsim.ResCloudlet,
* double)
*/
@Override
public double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time) {
// TODO Auto-generated method stub
return 0.0;
}
@Override
public double getCurrentRequestedUtilizationOfRam() {
double ram = 0;
for (ResCloudlet cloudlet : cloudletExecList) {
ram += cloudlet.getCloudlet().getUtilizationOfRam(CloudSim.clock());
}
return ram;
}
@Override
public double getCurrentRequestedUtilizationOfBw() {
double bw = 0;
for (ResCloudlet cloudlet : cloudletExecList) {
bw += cloudlet.getCloudlet().getUtilizationOfBw(CloudSim.clock());
}
return bw;
}
}

View File

@@ -0,0 +1,18 @@
package org.cloudbus.cloudsim;
/**
*
* Defines common constants, used throughout cloudsim.
*
* @author nikolay.grozev
*
*/
public final class Consts {
/**
* Suppreses intantiation.
*/
private Consts(){}
public static int MILLION = 1000000;
}

View File

@@ -0,0 +1,475 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* This class contains additional tags for the DataCloud functionalities, such as file information
* retrieval, file transfers, and storage info.
*
* @author Uros Cibej
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public final class DataCloudTags {
// to prevent a conflict with the existing CloudSimTags values
private static final int BASE = 400; // for other general tags
private static final int RM_BASE = 500; // for Replica Manager tags
private static final int CTLG_BASE = 600; // for catalogue tags
// ////////// GENERAL TAGS
/** Default Maximum Transmission Unit (MTU) of a link in bytes */
public static final int DEFAULT_MTU = 1500;
/** The default packet size (in byte) for sending events to other entity. */
public static final int PKT_SIZE = DEFAULT_MTU * 100; // in bytes
/** The default storage size (10 GByte) */
public static final int DEFAULT_STORAGE_SIZE = 10000000; // 10 GB in bytes
/** Registers a Replica Catalogue (RC) entity to a Data GIS */
public static final int REGISTER_REPLICA_CTLG = BASE + 1;
/**
* Denotes a list of all Replica Catalogue (RC) entities that are listed in this regional Data
* GIS entity. This tag should be called from a user to Data GIS.
*/
public static final int INQUIRY_LOCAL_RC_LIST = BASE + 2;
/**
* Denotes a list of Replica Catalogue (RC) entities that are listed in other regional Data GIS
* entities. This tag should be called from a user to Data GIS.
*/
public static final int INQUIRY_GLOBAL_RC_LIST = BASE + 3;
/**
* Denotes a list of Replica Catalogue IDs. This tag should be called from a Regional Data GIS
* to another
*/
public static final int INQUIRY_RC_LIST = BASE + 4;
/**
* Denotes a result regarding to a list of Replica Catalogue IDs. This tag should be called from
* a Regional Data GIS to a sender Regional Data GIS.
*/
public static final int INQUIRY_RC_RESULT = BASE + 5;
/**
* Denotes the submission of a DataCloudlet. This tag is normally used between user and
* DataCloudResource entity.
*/
public static final int DATAcloudlet_SUBMIT = BASE + 6;
// ////////// REPLICA MANAGER TAGS
// ***********************User <--> RM******************************//
/**
* Requests for a file that is stored on the local storage(s).<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #FILE_DELIVERY}.
*/
public static final int FILE_REQUEST = RM_BASE + 1;
/**
* Sends the file to the requester. The format of the reply is File or null if error happens
*/
public static final int FILE_DELIVERY = RM_BASE + 2;
// /////////////////////////////////////////////////////////////////////
/**
* Requests for a master file to be added to the local storage(s).<br>
* The format of this request is Object[2] = {File obj, Integer senderID}.<br>
* The reply tag name is {@link #FILE_ADD_MASTER_RESULT}.
*/
public static final int FILE_ADD_MASTER = RM_BASE + 10;
/**
* Sends the result of adding a master file back to sender.<br>
* The format of the reply is Object[3] = {String lfn, Integer uniqueID, Integer resultID}.<br>
* NOTE: The result id is in the form of FILE_ADD_XXXX where XXXX means the error/success
* message
*/
public static final int FILE_ADD_MASTER_RESULT = RM_BASE + 11;
/**
* Requests for a replica file to be added from the local storage(s).<br>
* The format of this request is Object[2] = {File obj, Integer senderID}.<br>
* The reply tag name is {@link #FILE_ADD_REPLICA_RESULT}.
*/
public static final int FILE_ADD_REPLICA = RM_BASE + 12;
/**
* Sends the result of adding a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of FILE_ADD_XXXX where XXXX means the error/success
* message
*/
public static final int FILE_ADD_REPLICA_RESULT = RM_BASE + 13;
/** Denotes that file addition is successful */
public static final int FILE_ADD_SUCCESSFUL = RM_BASE + 20;
/** Denotes that file addition is failed because the storage is full */
public static final int FILE_ADD_ERROR_STORAGE_FULL = RM_BASE + 21;
/** Denotes that file addition is failed because the given file is empty */
public static final int FILE_ADD_ERROR_EMPTY = RM_BASE + 22;
/**
* Denotes that file addition is failed because the file already exists in the catalogue and it
* is read-only file
*/
public static final int FILE_ADD_ERROR_EXIST_READ_ONLY = RM_BASE + 23;
/** Denotes that file addition is failed due to an unknown error */
public static final int FILE_ADD_ERROR = RM_BASE + 24;
/**
* Denotes that file addition is failed because access/permission denied or not authorized
*/
public static final int FILE_ADD_ERROR_ACCESS_DENIED = RM_BASE + 25;
// /////////////////////////////////////////////////////////////////////
/**
* Requests for a master file to be deleted from the local storage(s).<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #FILE_DELETE_MASTER_RESULT}.
*/
public static final int FILE_DELETE_MASTER = RM_BASE + 30;
/**
* Sends the result of deleting a master file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of FILE_DELETE_XXXX where XXXX means the error/success
* message
*/
public static final int FILE_DELETE_MASTER_RESULT = RM_BASE + 31;
/**
* Requests for a replica file to be deleted from the local storage(s).<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #FILE_DELETE_REPLICA_RESULT}.
*/
public static final int FILE_DELETE_REPLICA = RM_BASE + 32;
/**
* Sends the result of deleting a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of FILE_DELETE_XXXX where XXXX means the error/success
* message
*/
public static final int FILE_DELETE_REPLICA_RESULT = RM_BASE + 33;
/** Denotes that file deletion is successful */
public static final int FILE_DELETE_SUCCESSFUL = RM_BASE + 40;
/** Denotes that file deletion is failed due to an unknown error */
public static final int FILE_DELETE_ERROR = RM_BASE + 41;
/** Denotes that file deletion is failed because it is a read-only file */
public static final int FILE_DELETE_ERROR_READ_ONLY = RM_BASE + 42;
/**
* Denotes that file deletion is failed because the file does not exist in the storage nor
* catalogue
*/
public static final int FILE_DELETE_ERROR_DOESNT_EXIST = RM_BASE + 43;
/**
* Denotes that file deletion is failed because it is currently used by others
*/
public static final int FILE_DELETE_ERROR_IN_USE = RM_BASE + 44;
/**
* Denotes that file deletion is failed because access/permission denied or not authorized
*/
public static final int FILE_DELETE_ERROR_ACCESS_DENIED = RM_BASE + 45;
// /////////////////////////////////////////////////////////////////////
/**
* Requests for a file to be modified from the local storage(s).<br>
* The format of this request is Object[2] = {File obj, Integer senderID}.<br>
* The reply tag name is {@link #FILE_MODIFY_RESULT}.
*/
public static final int FILE_MODIFY = RM_BASE + 50;
/**
* Sends the result of deleting a file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of FILE_MODIFY_XXXX where XXXX means the error/success
* message
*/
public static final int FILE_MODIFY_RESULT = RM_BASE + 51;
/** Denotes that file modification is successful */
public static final int FILE_MODIFY_SUCCESSFUL = RM_BASE + 60;
/** Denotes that file modification is failed due to an unknown error */
public static final int FILE_MODIFY_ERROR = RM_BASE + 61;
/**
* Denotes that file modification is failed because it is a read-only file
*/
public static final int FILE_MODIFY_ERROR_READ_ONLY = RM_BASE + 62;
/**
* Denotes that file modification is failed because the file does not exist
*/
public static final int FILE_MODIFY_ERROR_DOESNT_EXIST = RM_BASE + 63;
/**
* Denotes that file modification is failed because the file is currently used by others
*/
public static final int FILE_MODIFY_ERROR_IN_USE = RM_BASE + 64;
/**
* Denotes that file modification is failed because access/permission denied or not authorized
*/
public static final int FILE_MODIFY_ERROR_ACCESS_DENIED = RM_BASE + 65;
// ////////// REPLICA CATALOGUE TAGS
// ***********************User<-->RC******************************//
/**
* Denotes the request for a location of a replica file.<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #CTLG_REPLICA_DELIVERY}.<br>
* NOTE: This request only ask for one location only not all.
*/
public static final int CTLG_GET_REPLICA = CTLG_BASE + 1;
/**
* Sends the result for a location of a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resourceID}.<br>
* NOTE: The resourceID could be <tt>-1</tt> if not found.
*/
public static final int CTLG_REPLICA_DELIVERY = CTLG_BASE + 2;
/**
* Denotes the request for all locations of a replica file.<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #CTLG_REPLICA_LIST_DELIVERY}.
*/
public static final int CTLG_GET_REPLICA_LIST = CTLG_BASE + 3;
/**
* Sends the result for all locations of a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, List locationList}.<br>
* NOTE: The locationList could be <tt>null</tt> if not found.
*/
public static final int CTLG_REPLICA_LIST_DELIVERY = CTLG_BASE + 4;
/**
* Denotes the request to get the attribute of a file.<br>
* The format of this request is Object[2] = {String lfn, Integer senderID}.<br>
* The reply tag name is {@link #CTLG_FILE_ATTR_DELIVERY}.
*/
public static final int CTLG_GET_FILE_ATTR = CTLG_BASE + 5;
/**
* Sends the result for a file attribute back to sender.<br>
* The format of the reply is {FileAttribute fileAttr}.<br>
* NOTE: The fileAttr could be <tt>null</tt> if not found.
*/
public static final int CTLG_FILE_ATTR_DELIVERY = CTLG_BASE + 6;
/**
* Denotes the request to get a list of file attributes based on the given filter.<br>
* The format of this request is Object[2] = {Filter filter, Integer senderID}.<br>
* The reply tag name is {@link #CTLG_FILTER_DELIVERY}.
*/
public static final int CTLG_FILTER = CTLG_BASE + 7;
/**
* Sends the result for a list of file attributes back to sender.<br>
* The format of the reply is {List attrList}.<br>
* NOTE: The attrList could be <tt>null</tt> if not found.
*/
public static final int CTLG_FILTER_DELIVERY = CTLG_BASE + 8;
// ***********************RM<-->RC******************************//
/**
* Denotes the request to register / add a master file to the Replica Catalogue.<br>
* The format of this request is Object[3] = {String filename, FileAttribute attr, Integer
* resID}.<br>
* The reply tag name is {@link #CTLG_ADD_MASTER_RESULT}.
*/
public static final int CTLG_ADD_MASTER = CTLG_BASE + 10;
/**
* Sends the result of registering a master file back to sender.<br>
* The format of the reply is Object[3] = {String filename, Integer uniqueID, Integer resultID}.<br>
* NOTE: The result id is in the form of CTLG_ADD_MASTER_XXXX where XXXX means the error/success
* message
*/
public static final int CTLG_ADD_MASTER_RESULT = CTLG_BASE + 11;
/** Denotes that master file addition is successful */
public static final int CTLG_ADD_MASTER_SUCCESSFUL = CTLG_BASE + 12;
/** Denotes that master file addition is failed due to an unknown error */
public static final int CTLG_ADD_MASTER_ERROR = CTLG_BASE + 13;
/**
* Denotes that master file addition is failed due to the catalogue is full
*/
public static final int CTLG_ADD_MASTER_ERROR_FULL = CTLG_BASE + 14;
// /////////////////////////////////////////////////////////////////////
/**
* Denotes the request to de-register / delete a master file from the Replica Catalogue.<br>
* The format of this request is Object[2] = {String lfn, Integer resourceID}.<br>
* The reply tag name is {@link #CTLG_DELETE_MASTER_RESULT}.
*/
public static final int CTLG_DELETE_MASTER = CTLG_BASE + 20;
/**
* Sends the result of de-registering a master file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of CTLG_DELETE_MASTER_XXXX where XXXX means the
* error/success message
*/
public static final int CTLG_DELETE_MASTER_RESULT = CTLG_BASE + 21;
/** Denotes that master file deletion is successful */
public static final int CTLG_DELETE_MASTER_SUCCESSFUL = CTLG_BASE + 22;
/** Denotes that master file deletion is failed due to an unknown error */
public static final int CTLG_DELETE_MASTER_ERROR = CTLG_BASE + 23;
/**
* Denotes that master file deletion is failed because the file does not exist in the catalogue
*/
public static final int CTLG_DELETE_MASTER_DOESNT_EXIST = CTLG_BASE + 24;
/**
* Denotes that master file deletion is failed because replica files are still in the catalogue.
* All replicas need to be deleted first.
*/
public static final int CTLG_DELETE_MASTER_REPLICAS_EXIST = CTLG_BASE + 25;
// /////////////////////////////////////////////////////////////////////
/**
* Denotes the request to register / add a replica file to the Replica Catalogue.<br>
* The format of this request is Object[2] = {String lfn, Integer resourceID}.<br>
* The reply tag name is {@link #CTLG_ADD_REPLICA_RESULT}.
*/
public static final int CTLG_ADD_REPLICA = CTLG_BASE + 30;
/**
* Sends the result of registering a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of CTLG_ADD_REPLICA_XXXX where XXXX means the
* error/success message
*/
public static final int CTLG_ADD_REPLICA_RESULT = CTLG_BASE + 31;
/** Denotes that replica file addition is successful */
public static final int CTLG_ADD_REPLICA_SUCCESSFUL = CTLG_BASE + 32;
/** Denotes that replica file addition is failed due to an unknown error */
public static final int CTLG_ADD_REPLICA_ERROR = CTLG_BASE + 33;
/**
* Denotes that replica file addition is failed because the given file name does not exist in
* the catalogue
*/
public static final int CTLG_ADD_REPLICA_ERROR_DOESNT_EXIST = CTLG_BASE + 34;
/**
* Denotes that replica file addition is failed due to the catalogue is full
*/
public static final int CTLG_ADD_REPLICA_ERROR_FULL = CTLG_BASE + 35;
// /////////////////////////////////////////////////////////////////////
/**
* Denotes the request to de-register / delete a replica file from the Replica Catalogue.<br>
* The format of this request is Object[2] = {String lfn, Integer resourceID}.<br>
* The reply tag name is {@link #CTLG_DELETE_REPLICA_RESULT}.
*/
public static final int CTLG_DELETE_REPLICA = CTLG_BASE + 40;
/**
* Sends the result of de-registering a replica file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of CTLG_DELETE_REPLICA_XXXX where XXXX means the
* error/success message
*/
public static final int CTLG_DELETE_REPLICA_RESULT = CTLG_BASE + 41;
/** Denotes that replica file deletion is successful */
public static final int CTLG_DELETE_REPLICA_SUCCESSFUL = CTLG_BASE + 42;
/** Denotes that replica file deletion is failed due to an unknown error */
public static final int CTLG_DELETE_REPLICA_ERROR = CTLG_BASE + 43;
/**
* Denotes that replica file deletion is failed because the file does not exist in the catalogue
*/
public static final int CTLG_DELETE_REPLICA_ERROR_DOESNT_EXIST = CTLG_BASE + 44;
// /////////////////////////////////////////////////////////////////////
/**
* Denotes the request to modify an existing master file information stored in the Replica
* Catalogue.<br>
* The format of this request is Object[3] = {String filename, FileAttribute attr, Integer
* resID}.<br>
* The reply tag name is {@link #CTLG_MODIFY_MASTER_RESULT}.
*/
public static final int CTLG_MODIFY_MASTER = CTLG_BASE + 50;
/**
* Sends the result of modifying a master file back to sender.<br>
* The format of the reply is Object[2] = {String lfn, Integer resultID}.<br>
* NOTE: The result id is in the form of CTLG_MODIFY_MASTER_XXXX where XXXX means the
* error/success message
*/
public static final int CTLG_MODIFY_MASTER_RESULT = CTLG_BASE + 51;
/** Denotes that master file deletion is successful */
public static final int CTLG_MODIFY_MASTER_SUCCESSFUL = CTLG_BASE + 52;
/**
* Denotes that master file modification is failed due to an unknown error
*/
public static final int CTLG_MODIFY_MASTER_ERROR = CTLG_BASE + 53;
/**
* Denotes that master file modification is failed because the file does not exist in the
* catalogue
*/
public static final int CTLG_MODIFY_MASTER_ERROR_DOESNT_EXIST = CTLG_BASE + 54;
/**
* Denotes that master file modification is failed because the file attribute is set to a
* read-only
*/
public static final int CTLG_MODIFY_MASTER_ERROR_READ_ONLY = CTLG_BASE + 55;
// /////////////////////////////////////////////////////////////////////
/** Private Constructor */
private DataCloudTags() {
throw new UnsupportedOperationException("DataCloudTags cannot be instantiated");
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,655 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.lists.CloudletList;
import org.cloudbus.cloudsim.lists.VmList;
/**
* DatacentreBroker represents a broker acting on behalf of a user. It hides VM management, as vm
* creation, sumbission of cloudlets to this VMs and destruction of VMs.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class DatacenterBroker extends SimEntity {
/** The vm list. */
protected List<? extends Vm> vmList;
/** The vms created list. */
protected List<? extends Vm> vmsCreatedList;
/** The cloudlet list. */
protected List<? extends Cloudlet> cloudletList;
/** The cloudlet submitted list. */
protected List<? extends Cloudlet> cloudletSubmittedList;
/** The cloudlet received list. */
protected List<? extends Cloudlet> cloudletReceivedList;
/** The cloudlets submitted. */
protected int cloudletsSubmitted;
/** The vms requested. */
protected int vmsRequested;
/** The vms acks. */
protected int vmsAcks;
/** The vms destroyed. */
protected int vmsDestroyed;
/** The datacenter ids list. */
protected List<Integer> datacenterIdsList;
/** The datacenter requested ids list. */
protected List<Integer> datacenterRequestedIdsList;
/** The vms to datacenters map. */
protected Map<Integer, Integer> vmsToDatacentersMap;
/** The datacenter characteristics list. */
protected Map<Integer, DatacenterCharacteristics> datacenterCharacteristicsList;
/**
* Created a new DatacenterBroker object.
*
* @param name name to be associated with this entity (as required by Sim_entity class from
* simjava package)
* @throws Exception the exception
* @pre name != null
* @post $none
*/
public DatacenterBroker(String name) throws Exception {
super(name);
setVmList(new ArrayList<Vm>());
setVmsCreatedList(new ArrayList<Vm>());
setCloudletList(new ArrayList<Cloudlet>());
setCloudletSubmittedList(new ArrayList<Cloudlet>());
setCloudletReceivedList(new ArrayList<Cloudlet>());
cloudletsSubmitted = 0;
setVmsRequested(0);
setVmsAcks(0);
setVmsDestroyed(0);
setDatacenterIdsList(new LinkedList<Integer>());
setDatacenterRequestedIdsList(new ArrayList<Integer>());
setVmsToDatacentersMap(new HashMap<Integer, Integer>());
setDatacenterCharacteristicsList(new HashMap<Integer, DatacenterCharacteristics>());
}
/**
* This method is used to send to the broker the list with virtual machines that must be
* created.
*
* @param list the list
* @pre list !=null
* @post $none
*/
public void submitVmList(List<? extends Vm> list) {
getVmList().addAll(list);
}
/**
* This method is used to send to the broker the list of cloudlets.
*
* @param list the list
* @pre list !=null
* @post $none
*/
public void submitCloudletList(List<? extends Cloudlet> list) {
getCloudletList().addAll(list);
}
/**
* Specifies that a given cloudlet must run in a specific virtual machine.
*
* @param cloudletId ID of the cloudlet being bount to a vm
* @param vmId the vm id
* @pre cloudletId > 0
* @pre id > 0
* @post $none
*/
public void bindCloudletToVm(int cloudletId, int vmId) {
CloudletList.getById(getCloudletList(), cloudletId).setVmId(vmId);
}
/**
* Processes events available for this Broker.
*
* @param ev a SimEvent object
* @pre ev != null
* @post $none
*/
@Override
public void processEvent(SimEvent ev) {
switch (ev.getTag()) {
// Resource characteristics request
case CloudSimTags.RESOURCE_CHARACTERISTICS_REQUEST:
processResourceCharacteristicsRequest(ev);
break;
// Resource characteristics answer
case CloudSimTags.RESOURCE_CHARACTERISTICS:
processResourceCharacteristics(ev);
break;
// VM Creation answer
case CloudSimTags.VM_CREATE_ACK:
processVmCreate(ev);
break;
// A finished cloudlet returned
case CloudSimTags.CLOUDLET_RETURN:
processCloudletReturn(ev);
break;
// if the simulation finishes
case CloudSimTags.END_OF_SIMULATION:
shutdownEntity();
break;
// other unknown tags are processed by this method
default:
processOtherEvent(ev);
break;
}
}
/**
* Process the return of a request for the characteristics of a PowerDatacenter.
*
* @param ev a SimEvent object
* @pre ev != $null
* @post $none
*/
protected void processResourceCharacteristics(SimEvent ev) {
DatacenterCharacteristics characteristics = (DatacenterCharacteristics) ev.getData();
getDatacenterCharacteristicsList().put(characteristics.getId(), characteristics);
if (getDatacenterCharacteristicsList().size() == getDatacenterIdsList().size()) {
setDatacenterRequestedIdsList(new ArrayList<Integer>());
createVmsInDatacenter(getDatacenterIdsList().get(0));
}
}
/**
* Process a request for the characteristics of a PowerDatacenter.
*
* @param ev a SimEvent object
* @pre ev != $null
* @post $none
*/
protected void processResourceCharacteristicsRequest(SimEvent ev) {
setDatacenterIdsList(CloudSim.getCloudResourceList());
setDatacenterCharacteristicsList(new HashMap<Integer, DatacenterCharacteristics>());
Log.printLine(CloudSim.clock() + ": " + getName() + ": Cloud Resource List received with "
+ getDatacenterIdsList().size() + " resource(s)");
for (Integer datacenterId : getDatacenterIdsList()) {
sendNow(datacenterId, CloudSimTags.RESOURCE_CHARACTERISTICS, getId());
}
}
/**
* Process the ack received due to a request for VM creation.
*
* @param ev a SimEvent object
* @pre ev != null
* @post $none
*/
protected void processVmCreate(SimEvent ev) {
int[] data = (int[]) ev.getData();
int datacenterId = data[0];
int vmId = data[1];
int result = data[2];
if (result == CloudSimTags.TRUE) {
getVmsToDatacentersMap().put(vmId, datacenterId);
getVmsCreatedList().add(VmList.getById(getVmList(), vmId));
Log.printLine(CloudSim.clock() + ": " + getName() + ": VM #" + vmId
+ " has been created in Datacenter #" + datacenterId + ", Host #"
+ VmList.getById(getVmsCreatedList(), vmId).getHost().getId());
} else {
Log.printLine(CloudSim.clock() + ": " + getName() + ": Creation of VM #" + vmId
+ " failed in Datacenter #" + datacenterId);
}
incrementVmsAcks();
// all the requested VMs have been created
if (getVmsCreatedList().size() == getVmList().size() - getVmsDestroyed()) {
submitCloudlets();
} else {
// all the acks received, but some VMs were not created
if (getVmsRequested() == getVmsAcks()) {
// find id of the next datacenter that has not been tried
for (int nextDatacenterId : getDatacenterIdsList()) {
if (!getDatacenterRequestedIdsList().contains(nextDatacenterId)) {
createVmsInDatacenter(nextDatacenterId);
return;
}
}
// all datacenters already queried
if (getVmsCreatedList().size() > 0) { // if some vm were created
submitCloudlets();
} else { // no vms created. abort
Log.printLine(CloudSim.clock() + ": " + getName()
+ ": none of the required VMs could be created. Aborting");
finishExecution();
}
}
}
}
/**
* Process a cloudlet return event.
*
* @param ev a SimEvent object
* @pre ev != $null
* @post $none
*/
protected void processCloudletReturn(SimEvent ev) {
Cloudlet cloudlet = (Cloudlet) ev.getData();
getCloudletReceivedList().add(cloudlet);
Log.printLine(CloudSim.clock() + ": " + getName() + ": Cloudlet " + cloudlet.getCloudletId()
+ " received");
cloudletsSubmitted--;
if (getCloudletList().size() == 0 && cloudletsSubmitted == 0) { // all cloudlets executed
Log.printLine(CloudSim.clock() + ": " + getName() + ": All Cloudlets executed. Finishing...");
clearDatacenters();
finishExecution();
} else { // some cloudlets haven't finished yet
if (getCloudletList().size() > 0 && cloudletsSubmitted == 0) {
// all the cloudlets sent finished. It means that some bount
// cloudlet is waiting its VM be created
clearDatacenters();
createVmsInDatacenter(0);
}
}
}
/**
* Overrides this method when making a new and different type of Broker. This method is called
* by {@link #body()} for incoming unknown tags.
*
* @param ev a SimEvent object
* @pre ev != null
* @post $none
*/
protected void processOtherEvent(SimEvent ev) {
if (ev == null) {
Log.printLine(getName() + ".processOtherEvent(): " + "Error - an event is null.");
return;
}
Log.printLine(getName() + ".processOtherEvent(): "
+ "Error - event unknown by this DatacenterBroker.");
}
/**
* Create the virtual machines in a datacenter.
*
* @param datacenterId Id of the chosen PowerDatacenter
* @pre $none
* @post $none
*/
protected void createVmsInDatacenter(int datacenterId) {
// send as much vms as possible for this datacenter before trying the next one
int requestedVms = 0;
String datacenterName = CloudSim.getEntityName(datacenterId);
for (Vm vm : getVmList()) {
if (!getVmsToDatacentersMap().containsKey(vm.getId())) {
Log.printLine(CloudSim.clock() + ": " + getName() + ": Trying to Create VM #" + vm.getId()
+ " in " + datacenterName);
sendNow(datacenterId, CloudSimTags.VM_CREATE_ACK, vm);
requestedVms++;
}
}
getDatacenterRequestedIdsList().add(datacenterId);
setVmsRequested(requestedVms);
setVmsAcks(0);
}
/**
* Submit cloudlets to the created VMs.
*
* @pre $none
* @post $none
*/
protected void submitCloudlets() {
int vmIndex = 0;
for (Cloudlet cloudlet : getCloudletList()) {
Vm vm;
// if user didn't bind this cloudlet and it has not been executed yet
if (cloudlet.getVmId() == -1) {
vm = getVmsCreatedList().get(vmIndex);
} else { // submit to the specific vm
vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
if (vm == null) { // vm was not created
Log.printLine(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet "
+ cloudlet.getCloudletId() + ": bount VM not available");
continue;
}
}
Log.printLine(CloudSim.clock() + ": " + getName() + ": Sending cloudlet "
+ cloudlet.getCloudletId() + " to VM #" + vm.getId());
cloudlet.setVmId(vm.getId());
sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
cloudletsSubmitted++;
vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
getCloudletSubmittedList().add(cloudlet);
}
// remove submitted cloudlets from waiting list
for (Cloudlet cloudlet : getCloudletSubmittedList()) {
getCloudletList().remove(cloudlet);
}
}
/**
* Destroy the virtual machines running in datacenters.
*
* @pre $none
* @post $none
*/
protected void clearDatacenters() {
for (Vm vm : getVmsCreatedList()) {
Log.printLine(CloudSim.clock() + ": " + getName() + ": Destroying VM #" + vm.getId());
sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.VM_DESTROY, vm);
}
getVmsCreatedList().clear();
}
/**
* Send an internal event communicating the end of the simulation.
*
* @pre $none
* @post $none
*/
protected void finishExecution() {
sendNow(getId(), CloudSimTags.END_OF_SIMULATION);
}
/*
* (non-Javadoc)
* @see cloudsim.core.SimEntity#shutdownEntity()
*/
@Override
public void shutdownEntity() {
Log.printLine(getName() + " is shutting down...");
}
/*
* (non-Javadoc)
* @see cloudsim.core.SimEntity#startEntity()
*/
@Override
public void startEntity() {
Log.printLine(getName() + " is starting...");
schedule(getId(), 0, CloudSimTags.RESOURCE_CHARACTERISTICS_REQUEST);
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Vm> List<T> getVmList() {
return (List<T>) vmList;
}
/**
* Sets the vm list.
*
* @param <T> the generic type
* @param vmList the new vm list
*/
protected <T extends Vm> void setVmList(List<T> vmList) {
this.vmList = vmList;
}
/**
* Gets the cloudlet list.
*
* @param <T> the generic type
* @return the cloudlet list
*/
@SuppressWarnings("unchecked")
public <T extends Cloudlet> List<T> getCloudletList() {
return (List<T>) cloudletList;
}
/**
* Sets the cloudlet list.
*
* @param <T> the generic type
* @param cloudletList the new cloudlet list
*/
protected <T extends Cloudlet> void setCloudletList(List<T> cloudletList) {
this.cloudletList = cloudletList;
}
/**
* Gets the cloudlet submitted list.
*
* @param <T> the generic type
* @return the cloudlet submitted list
*/
@SuppressWarnings("unchecked")
public <T extends Cloudlet> List<T> getCloudletSubmittedList() {
return (List<T>) cloudletSubmittedList;
}
/**
* Sets the cloudlet submitted list.
*
* @param <T> the generic type
* @param cloudletSubmittedList the new cloudlet submitted list
*/
protected <T extends Cloudlet> void setCloudletSubmittedList(List<T> cloudletSubmittedList) {
this.cloudletSubmittedList = cloudletSubmittedList;
}
/**
* Gets the cloudlet received list.
*
* @param <T> the generic type
* @return the cloudlet received list
*/
@SuppressWarnings("unchecked")
public <T extends Cloudlet> List<T> getCloudletReceivedList() {
return (List<T>) cloudletReceivedList;
}
/**
* Sets the cloudlet received list.
*
* @param <T> the generic type
* @param cloudletReceivedList the new cloudlet received list
*/
protected <T extends Cloudlet> void setCloudletReceivedList(List<T> cloudletReceivedList) {
this.cloudletReceivedList = cloudletReceivedList;
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Vm> List<T> getVmsCreatedList() {
return (List<T>) vmsCreatedList;
}
/**
* Sets the vm list.
*
* @param <T> the generic type
* @param vmsCreatedList the vms created list
*/
protected <T extends Vm> void setVmsCreatedList(List<T> vmsCreatedList) {
this.vmsCreatedList = vmsCreatedList;
}
/**
* Gets the vms requested.
*
* @return the vms requested
*/
protected int getVmsRequested() {
return vmsRequested;
}
/**
* Sets the vms requested.
*
* @param vmsRequested the new vms requested
*/
protected void setVmsRequested(int vmsRequested) {
this.vmsRequested = vmsRequested;
}
/**
* Gets the vms acks.
*
* @return the vms acks
*/
protected int getVmsAcks() {
return vmsAcks;
}
/**
* Sets the vms acks.
*
* @param vmsAcks the new vms acks
*/
protected void setVmsAcks(int vmsAcks) {
this.vmsAcks = vmsAcks;
}
/**
* Increment vms acks.
*/
protected void incrementVmsAcks() {
vmsAcks++;
}
/**
* Gets the vms destroyed.
*
* @return the vms destroyed
*/
protected int getVmsDestroyed() {
return vmsDestroyed;
}
/**
* Sets the vms destroyed.
*
* @param vmsDestroyed the new vms destroyed
*/
protected void setVmsDestroyed(int vmsDestroyed) {
this.vmsDestroyed = vmsDestroyed;
}
/**
* Gets the datacenter ids list.
*
* @return the datacenter ids list
*/
protected List<Integer> getDatacenterIdsList() {
return datacenterIdsList;
}
/**
* Sets the datacenter ids list.
*
* @param datacenterIdsList the new datacenter ids list
*/
protected void setDatacenterIdsList(List<Integer> datacenterIdsList) {
this.datacenterIdsList = datacenterIdsList;
}
/**
* Gets the vms to datacenters map.
*
* @return the vms to datacenters map
*/
protected Map<Integer, Integer> getVmsToDatacentersMap() {
return vmsToDatacentersMap;
}
/**
* Sets the vms to datacenters map.
*
* @param vmsToDatacentersMap the vms to datacenters map
*/
protected void setVmsToDatacentersMap(Map<Integer, Integer> vmsToDatacentersMap) {
this.vmsToDatacentersMap = vmsToDatacentersMap;
}
/**
* Gets the datacenter characteristics list.
*
* @return the datacenter characteristics list
*/
protected Map<Integer, DatacenterCharacteristics> getDatacenterCharacteristicsList() {
return datacenterCharacteristicsList;
}
/**
* Sets the datacenter characteristics list.
*
* @param datacenterCharacteristicsList the datacenter characteristics list
*/
protected void setDatacenterCharacteristicsList(
Map<Integer, DatacenterCharacteristics> datacenterCharacteristicsList) {
this.datacenterCharacteristicsList = datacenterCharacteristicsList;
}
/**
* Gets the datacenter requested ids list.
*
* @return the datacenter requested ids list
*/
protected List<Integer> getDatacenterRequestedIdsList() {
return datacenterRequestedIdsList;
}
/**
* Sets the datacenter requested ids list.
*
* @param datacenterRequestedIdsList the new datacenter requested ids list
*/
protected void setDatacenterRequestedIdsList(List<Integer> datacenterRequestedIdsList) {
this.datacenterRequestedIdsList = datacenterRequestedIdsList;
}
}

View File

@@ -0,0 +1,569 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.lists.HostList;
import org.cloudbus.cloudsim.lists.PeList;
/**
* DatacenterCharacteristics represents static properties of a resource such as resource
* architecture, Operating System (OS), management policy (time- or space-shared), cost and time
* zone at which the resource is located along resource configuration.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class DatacenterCharacteristics {
/** The resource id -- setup when Resource is created. */
private int id;
/** The architecture. */
private String architecture;
/** The os. */
private String os;
/** The host list. */
private List<? extends Host> hostList;
/** The time zone -- difference from GMT. */
private double timeZone;
/** Price/CPU-unit if unit = sec., then G$/CPU-sec. */
private double costPerSecond;
/** Resource Types -- allocation policy. */
private int allocationPolicy;
/** Time-shared system using Round-Robin algorithm. */
public static final int TIME_SHARED = 0;
/** Spaced-shared system using First Come First Serve (FCFS) algorithm. */
public static final int SPACE_SHARED = 1;
/** Assuming all PEs in all Machines have the same rating. */
public static final int OTHER_POLICY_SAME_RATING = 2;
/**
* Assuming all PEs in a Machine have the same rating. However, each Machine has different
* rating to each other.
*/
public static final int OTHER_POLICY_DIFFERENT_RATING = 3;
/** A resource that supports Advanced Reservation mechanisms. */
public static final int ADVANCE_RESERVATION = 4;
/** The vmm. */
private String vmm;
/** The cost per mem. */
private double costPerMem;
/** The cost per storage. */
private double costPerStorage;
/** The cost per bw. */
private double costPerBw;
/**
* Allocates a new DatacenterCharacteristics object. If the time zone is invalid, then by
* default, it will be GMT+0.
*
* @param architecture the architecture of a resource
* @param os the operating system used
* @param vmm the virtual machine monitor used
* @param hostList list of machines in a resource
* @param timeZone local time zone of a user that owns this reservation. Time zone should be of
* range [GMT-12 ... GMT+13]
* @param costPerSec the cost per sec to use this resource
* @param costPerMem the cost to use memory in this resource
* @param costPerStorage the cost to use storage in this resource
* @param costPerBw the cost per bw
* @pre architecture != null
* @pre OS != null
* @pre VMM != null
* @pre machineList != null
* @pre timeZone >= -12 && timeZone <= 13
* @pre costPerSec >= 0.0
* @pre costPerMem >= 0
* @pre costPerStorage >= 0
* @post $none
*/
public DatacenterCharacteristics(
String architecture,
String os,
String vmm,
List<? extends Host> hostList,
double timeZone,
double costPerSec,
double costPerMem,
double costPerStorage,
double costPerBw) {
setId(-1);
setArchitecture(architecture);
setOs(os);
setHostList(hostList);
setAllocationPolicy(allocationPolicy);
setCostPerSecond(costPerSec);
setTimeZone(0.0);
setVmm(vmm);
setCostPerMem(costPerMem);
setCostPerStorage(costPerStorage);
setCostPerBw(costPerBw);
}
/**
* Gets the name of a resource.
*
* @return the resource name
* @pre $none
* @post $result != null
*/
public String getResourceName() {
return CloudSim.getEntityName(getId());
}
/**
* Gets a Machine with at least one empty Pe.
*
* @return a Machine object or if not found
* @pre $none
* @post $none
*/
public Host getHostWithFreePe() {
return HostList.getHostWithFreePe(getHostList());
}
/**
* Gets a Machine with at least a given number of free Pe.
*
* @param peNumber the pe number
* @return a Machine object or if not found
* @pre $none
* @post $none
*/
public Host getHostWithFreePe(int peNumber) {
return HostList.getHostWithFreePe(getHostList(), peNumber);
}
/**
* Gets Millions Instructions Per Second (MIPS) Rating of a Processing Element (Pe). It is
* assumed all PEs' rating is same in a given machine.
*
* @return the MIPS Rating or if no PEs are exists.
* @pre $none
* @post $result >= -1
*/
public int getMipsOfOnePe() {
if (getHostList().size() == 0) {
return -1;
}
return PeList.getMips(getHostList().get(0).getPeList(), 0);
}
/**
* Gets Millions Instructions Per Second (MIPS) Rating of a Processing Element (Pe). It is
* essential to use this method when a resource is made up of heterogenous PEs/machines.
*
* @param id the machine ID
* @param peId the Pe ID
* @return the MIPS Rating or if no PEs are exists.
* @pre id >= 0
* @pre peID >= 0
* @post $result >= -1
*/
public int getMipsOfOnePe(int id, int peId) {
if (getHostList().size() == 0) {
return -1;
}
return PeList.getMips(HostList.getById(getHostList(), id).getPeList(), peId);
}
/**
* Gets the total MIPS rating, which is the sum of MIPS rating of all machines in a resource.
* <p>
* Total MIPS rating for:
* <ul>
* <li>TimeShared = 1 Rating of a Pe * Total number of PEs
* <li>Other policy same rating = same as TimeShared
* <li>SpaceShared = Sum of all PEs in all Machines
* <li>Other policy different rating = same as SpaceShared
* <li>Advance Reservation = 0 or unknown. You need to calculate this manually.
* </ul>
*
* @return the sum of MIPS ratings
* @pre $none
* @post $result >= 0
*/
public int getMips() {
int mips = 0;
switch (getAllocationPolicy()) {
// Assuming all PEs in all Machine have same rating.
case DatacenterCharacteristics.TIME_SHARED:
case DatacenterCharacteristics.OTHER_POLICY_SAME_RATING:
mips = getMipsOfOnePe() * HostList.getNumberOfPes(getHostList());
break;
// Assuming all PEs in a given Machine have the same rating.
// But different machines in a Cluster can have different rating
case DatacenterCharacteristics.SPACE_SHARED:
case DatacenterCharacteristics.OTHER_POLICY_DIFFERENT_RATING:
for (Host host : getHostList()) {
mips += host.getTotalMips();
}
break;
default:
break;
}
return mips;
}
/**
* Gets the CPU time given the specified parameters (only for TIME_SHARED). <tt>NOTE:</tt> The
* CPU time for SPACE_SHARED and ADVANCE_RESERVATION are not yet implemented.
*
* @param cloudletLength the length of a Cloudlet
* @param load the load of a Cloudlet
* @return the CPU time
* @pre cloudletLength >= 0.0
* @pre load >= 0.0
* @post $result >= 0.0
*/
public double getCpuTime(double cloudletLength, double load) {
double cpuTime = 0.0;
switch (getAllocationPolicy()) {
case DatacenterCharacteristics.TIME_SHARED:
cpuTime = cloudletLength / (getMipsOfOnePe() * (1.0 - load));
break;
default:
break;
}
return cpuTime;
}
/**
* Gets the total number of PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfPes() {
return HostList.getNumberOfPes(getHostList());
}
/**
* Gets the total number of <tt>FREE</tt> or non-busy PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfFreePes() {
return HostList.getNumberOfFreePes(getHostList());
}
/**
* Gets the total number of <tt>BUSY</tt> PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfBusyPes() {
return HostList.getNumberOfBusyPes(getHostList());
}
/**
* Sets the particular Pe status on a Machine.
*
* @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
* @param hostId Machine ID
* @param peId Pe id
* @return otherwise (Machine id or Pe id might not be exist)
* @pre machineID >= 0
* @pre peID >= 0
* @post $none
*/
public boolean setPeStatus(int status, int hostId, int peId) {
return HostList.setPeStatus(getHostList(), status, hostId, peId);
}
/**
* Gets the cost per Millions Instruction (MI) associated with a resource.
*
* @return the cost using a resource
* @pre $none
* @post $result >= 0.0
*/
public double getCostPerMi() {
return getCostPerSecond() / getMipsOfOnePe();
}
/**
* Gets the total number of machines.
*
* @return total number of machines this resource has.
*/
public int getNumberOfHosts() {
return getHostList().size();
}
/**
* Gets the current number of failed machines.
*
* @return current number of failed machines this resource has.
*/
public int getNumberOfFailedHosts() {
int numberOfFailedHosts = 0;
for (Host host : getHostList()) {
if (host.isFailed()) {
numberOfFailedHosts++;
}
}
return numberOfFailedHosts;
}
/**
* Checks whether all machines of this resource are working properly or not.
*
* @return if all machines are working, otherwise
*/
public boolean isWorking() {
boolean result = false;
if (getNumberOfFailedHosts() == 0) {
result = true;
}
return result;
}
/**
* Get the cost to use memory in this resource.
*
* @return the cost to use memory
*/
public double getCostPerMem() {
return costPerMem;
}
/**
* Sets cost to use memory.
*
* @param costPerMem cost to use memory
* @pre costPerMem >= 0
* @post $none
*/
public void setCostPerMem(double costPerMem) {
this.costPerMem = costPerMem;
}
/**
* Get the cost to use storage in this resource.
*
* @return the cost to use storage
*/
public double getCostPerStorage() {
return costPerStorage;
}
/**
* Sets cost to use storage.
*
* @param costPerStorage cost to use storage
* @pre costPerStorage >= 0
* @post $none
*/
public void setCostPerStorage(double costPerStorage) {
this.costPerStorage = costPerStorage;
}
/**
* Get the cost to use bandwidth in this resource.
*
* @return the cost to use bw
*/
public double getCostPerBw() {
return costPerBw;
}
/**
* Sets cost to use bw cost to use bw.
*
* @param costPerBw the cost per bw
* @pre costPerBw >= 0
* @post $none
*/
public void setCostPerBw(double costPerBw) {
this.costPerBw = costPerBw;
}
/**
* Gets the VMM in use in the datacenter.
*
* @return the VMM name
*/
public String getVmm() {
return vmm;
}
/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(int id) {
this.id = id;
}
/**
* Gets the architecture.
*
* @return the architecture
*/
protected String getArchitecture() {
return architecture;
}
/**
* Sets the architecture.
*
* @param architecture the new architecture
*/
protected void setArchitecture(String architecture) {
this.architecture = architecture;
}
/**
* Gets the os.
*
* @return the os
*/
protected String getOs() {
return os;
}
/**
* Sets the os.
*
* @param os the new os
*/
protected void setOs(String os) {
this.os = os;
}
/**
* Gets the host list.
*
* @param <T> the generic type
* @return the host list
*/
@SuppressWarnings("unchecked")
public <T extends Host> List<T> getHostList() {
return (List<T>) hostList;
}
/**
* Sets the host list.
*
* @param <T> the generic type
* @param hostList the new host list
*/
protected <T extends Host> void setHostList(List<T> hostList) {
this.hostList = hostList;
}
/**
* Gets the time zone.
*
* @return the time zone
*/
protected double getTimeZone() {
return timeZone;
}
/**
* Sets the time zone.
*
* @param timeZone the new time zone
*/
protected void setTimeZone(double timeZone) {
this.timeZone = timeZone;
}
/**
* Gets the cost per second.
*
* @return the cost per second
*/
public double getCostPerSecond() {
return costPerSecond;
}
/**
* Sets the cost per second.
*
* @param costPerSecond the new cost per second
*/
protected void setCostPerSecond(double costPerSecond) {
this.costPerSecond = costPerSecond;
}
/**
* Gets the allocation policy.
*
* @return the allocation policy
*/
protected int getAllocationPolicy() {
return allocationPolicy;
}
/**
* Sets the allocation policy.
*
* @param allocationPolicy the new allocation policy
*/
protected void setAllocationPolicy(int allocationPolicy) {
this.allocationPolicy = allocationPolicy;
}
/**
* Sets the vmm.
*
* @param vmm the new vmm
*/
protected void setVmm(String vmm) {
this.vmm = vmm;
}
}

View File

@@ -0,0 +1,417 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* A class for representing a physical file in a DataCloud environment
*
* @author Uros Cibej
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public class File {
private String name; // logical file name
private FileAttribute attribute; // a file attribute
// a transaction time for adding / getting /deleting this file
private double transactionTime;
/** Denotes that this file has not been registered to a Replica Catalogue */
public static final int NOT_REGISTERED = -1;
/** Denotes that the type of this file is unknown */
public static final int TYPE_UNKOWN = 0;
/** Denotes that the type of this file is a raw data */
public static final int TYPE_RAW_DATA = 1;
/** Denotes that the type of this file is a reconstructed data */
public static final int TYPE_RECONSTRUCTED_DATA = 2;
/** Denotes that the type of this file is a tag data */
public static final int TYPE_TAG_DATA = 3;
/**
* Creates a new DataCloud file with a given size (in MBytes). <br>
* NOTE: By default, a newly-created file is set to a <b>master</b> copy.
*
* @param fileName file name
* @param fileSize file size is in MBytes
* @throws ParameterException This happens when one of the following scenarios occur:
* <ul>
* <li>the file name is empty or <tt>null</tt>
* <li>the file size is zero or negative numbers
* </ul>
*/
public File(String fileName, int fileSize) throws ParameterException {
if (fileName == null || fileName.length() == 0) {
throw new ParameterException("File(): Error - invalid file name.");
}
if (fileSize <= 0) {
throw new ParameterException("File(): Error - size <= 0.");
}
name = fileName;
attribute = new FileAttribute(fileName, fileSize);
transactionTime = 0;
}
/**
* Copy constructor, i.e. cloning from a source file into this object, but this object is set to
* a <b>replica</b>
*
* @param file the source of a File object to copy
* @throws ParameterException This happens when the source file is <tt>null</tt>
*/
public File(File file) throws ParameterException {
if (file == null) {
throw new ParameterException("File(): Error - file is null.");
}
// copy the attributes into the file
FileAttribute fileAttr = file.getFileAttribute();
attribute.copyValue(fileAttr);
fileAttr.setMasterCopy(false); // set this file to replica
}
/**
* Clone this file but the clone file is set to a <b>replica</b>
*
* @return a clone of this file (as a replica) or <tt>null</tt> if an error occurs
*/
public File makeReplica() {
return makeCopy();
}
/**
* Clone this file and make the new file as a <b>master</b> copy as well
*
* @return a clone of this file (as a master copy) or <tt>null</tt> if an error occurs
*/
public File makeMasterCopy() {
File file = makeCopy();
if (file != null) {
file.setMasterCopy(true);
}
return file;
}
/**
* Makes a copy of this file
*
* @return a clone of this file (as a replica) or <tt>null</tt> if an error occurs
*/
private File makeCopy() {
File file = null;
try {
file = new File(name, attribute.getFileSize());
FileAttribute fileAttr = file.getFileAttribute();
attribute.copyValue(fileAttr);
fileAttr.setMasterCopy(false); // set this file to replica
} catch (Exception e) {
file = null;
}
return file;
}
/**
* Gets an attribute of this file
*
* @return a file attribute
*/
public FileAttribute getFileAttribute() {
return attribute;
}
/**
* Gets the size of this object (in byte).<br>
* NOTE: This object size is NOT the actual file size. Moreover, this size is used for
* transferring this object over a network.
*
* @return the object size (in byte)
*/
public int getAttributeSize() {
return attribute.getAttributeSize();
}
/**
* Sets the resource ID that stores this file
*
* @param resourceID a resource ID
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setResourceID(int resourceID) {
return attribute.setResourceID(resourceID);
}
/**
* Gets the resource ID that stores this file
*
* @return the resource ID
*/
public int getResourceID() {
return attribute.getResourceID();
}
/**
* Returns the file name
*
* @return the file name
*/
public String getName() {
return attribute.getName();
}
/**
* Sets the file name
*
* @param name the file name
*/
public void setName(String name) {
attribute.setName(name);
}
/**
* Sets the owner name of this file
*
* @param name the owner name
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setOwnerName(String name) {
return attribute.setOwnerName(name);
}
/**
* Gets the owner name of this file
*
* @return the owner name or <tt>null</tt> if empty
*/
public String getOwnerName() {
return attribute.getOwnerName();
}
/**
* Gets the file size (in MBytes)
*
* @return the file size (in MBytes)
*/
public int getSize() {
return attribute.getFileSize();
}
/**
* Gets the file size (in bytes)
*
* @return the file size (in bytes)
*/
public int getSizeInByte() {
return attribute.getFileSizeInByte();
}
/**
* Sets the file size (in MBytes)
*
* @param fileSize the file size (in MBytes)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setFileSize(int fileSize) {
return attribute.setFileSize(fileSize);
}
/**
* Sets the last update time of this file (in seconds)<br>
* NOTE: This time is relative to the start time. Preferably use
* {@link gridsim.CloudSim#clock()} method.
*
* @param time the last update time (in seconds)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setUpdateTime(double time) {
return attribute.setUpdateTime(time);
}
/**
* Gets the last update time (in seconds)
*
* @return the last update time (in seconds)
*/
public double getLastUpdateTime() {
return attribute.getLastUpdateTime();
}
/**
* Sets the file registration ID (published by a Replica Catalogue entity)
*
* @param id registration ID
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setRegistrationID(int id) {
return attribute.setRegistrationId(id);
}
/**
* Gets the file registration ID
*
* @return registration ID
*/
public int getRegistrationID() {
return attribute.getRegistrationID();
}
/**
* Sets the file type (e.g. raw, tag, etc)
*
* @param type a file type
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setType(int type) {
return attribute.setType(type);
}
/**
* Gets this file type
*
* @return file type
*/
public int getType() {
return attribute.getType();
}
/**
* Sets the checksum of this file
*
* @param checksum the checksum of this file
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setChecksum(int checksum) {
return attribute.setChecksum(checksum);
}
/**
* Gets the file checksum
*
* @return file checksum
*/
public int getChecksum() {
return attribute.getChecksum();
}
/**
* Sets the cost associated with this file
*
* @param cost cost of this file
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setCost(double cost) {
return attribute.setCost(cost);
}
/**
* Gets the cost associated with this file
*
* @return the cost of this file
*/
public double getCost() {
return attribute.getCost();
}
/**
* Gets the file creation time (in millisecond)
*
* @return the file creation time (in millisecond)
*/
public long getCreationTime() {
return attribute.getCreationTime();
}
/**
* Checks if this file already registered to a Replica Catalogue
*
* @return <tt>true</tt> if it is registered, <tt>false</tt> otherwise
*/
public boolean isRegistered() {
return attribute.isRegistered();
}
/**
* Marks this file as a master copy or replica
*
* @param masterCopy a flag denotes <tt>true</tt> for master copy or <tt>false</tt> for a
* replica
*/
public void setMasterCopy(boolean masterCopy) {
attribute.setMasterCopy(masterCopy);
}
/**
* Checks whether this file is a master copy or replica
*
* @return <tt>true</tt> if it is a master copy or <tt>false</tt> otherwise
*/
public boolean isMasterCopy() {
return attribute.isMasterCopy();
}
/**
* Marks this file as a read only or not
*
* @param readOnly a flag denotes <tt>true</tt> for read only or <tt>false</tt> for re-writeable
*/
public void setReadOnly(boolean readOnly) {
attribute.setReadOnly(readOnly);
}
/**
* Checks whether this file is a read only or not
*
* @return <tt>true</tt> if it is a read only or <tt>false</tt> otherwise
*/
public boolean isReadOnly() {
return attribute.isReadOnly();
}
/**
* Sets the current transaction time (in second) of this file. This transaction time can be
* related to the operation of adding / deleting / getting this file on a resource's storage.
*
* @param time the transaction time (in second)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @see gridsim.datagrid.storage.Storage#addFile(File)
* @see gridsim.datagrid.storage.Storage#addFile(List)
* @see gridsim.datagrid.storage.Storage#addReservedFile(File)
* @see gridsim.datagrid.storage.Storage#deleteFile(File)
* @see gridsim.datagrid.storage.Storage#deleteFile(String)
* @see gridsim.datagrid.storage.Storage#deleteFile(String, File)
* @see gridsim.datagrid.storage.Storage#getFile(String)
* @see gridsim.datagrid.storage.Storage#renameFile(File, String)
*/
public boolean setTransactionTime(double time) {
if (time < 0) {
return false;
}
transactionTime = time;
return true;
}
/**
* Gets the last transaction time of this file (in second).
*
* @return the transaction time (in second)
*/
public double getTransactionTime() {
return transactionTime;
}
}

View File

@@ -0,0 +1,435 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.Date;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* A class for storing related information regarding to a {@link gridsim.datagrid.File} entity.
*
* @author Uros Cibej
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public class FileAttribute {
private String name; // logical file name
private String ownerName; // owner name of this file
private int id; // file ID given by a Replica Catalogue
private int type; // file type, e.g. raw, reconstructed, etc
private int size; // file size in byte
private int checksum; // check sum
private double lastUpdateTime; // last updated time (sec) - relative
private long creationTime; // creation time (ms) - abosulte/relative
private double cost; // price of this file
private boolean masterCopy; // false if it is a replica
private boolean readOnly; // false if it can be rewritten
private int resourceId; // resource ID storing this file
/**
* Allocates a new FileAttribute class.
*
* @param fileName file name
* @param fileSize size of this file (in bytes)
* @throws ParameterException This happens when one of the following scenarios occur:
* <ul>
* <li>the file name is empty or <tt>null</tt>
* <li>the file size is zero or negative numbers
* </ul>
*/
public FileAttribute(String fileName, int fileSize) throws ParameterException {
// check for errors in the input
if (fileName == null || fileName.length() == 0) {
throw new ParameterException("FileAttribute(): Error - invalid file name.");
}
if (fileSize <= 0) {
throw new ParameterException("FileAttribute(): Error - size <= 0.");
}
size = fileSize;
name = fileName;
// set the file creation time. This is absolute time
Date date = CloudSim.getSimulationCalendar().getTime();
if (date == null) {
creationTime = 0;
} else {
creationTime = date.getTime();
}
ownerName = null;
id = File.NOT_REGISTERED;
checksum = 0;
type = File.TYPE_UNKOWN;
lastUpdateTime = 0;
cost = 0;
resourceId = -1;
masterCopy = true;
readOnly = false;
}
/**
* Copy the values of this object into another FileAttribute class
*
* @param attr a FileAttribute object (the destination)
* @return <tt>true</tt> if the copy operation is successful, <tt>false</tt> otherwise
*/
public boolean copyValue(FileAttribute attr) {
if (attr == null) {
return false;
}
attr.setFileSize(size);
attr.setResourceID(resourceId);
attr.setOwnerName(ownerName);
attr.setUpdateTime(lastUpdateTime);
attr.setRegistrationId(id);
attr.setType(type);
attr.setChecksum(checksum);
attr.setCost(cost);
attr.setMasterCopy(masterCopy);
attr.setReadOnly(readOnly);
attr.setName(name);
attr.setCreationTime(creationTime);
return true;
}
/**
* Sets the file creation time (in millisecond)
*
* @param creationTime the file creation time (in millisecond)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setCreationTime(long creationTime) {
if (creationTime <= 0) {
return false;
}
this.creationTime = creationTime;
return true;
}
/**
* Gets the file creation time (in millisecond)
*
* @return the file creation time (in millisecond)
*/
public long getCreationTime() {
return creationTime;
}
/**
* Sets the resource ID that stores this file
*
* @param resourceID a resource ID
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setResourceID(int resourceID) {
if (resourceID == -1) {
return false;
}
resourceId = resourceID;
return true;
}
/**
* Gets the resource ID that stores this file
*
* @return the resource ID
*/
public int getResourceID() {
return resourceId;
}
/**
* Sets the owner name of this file
*
* @param name the owner name
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setOwnerName(String name) {
if (name == null || name.length() == 0) {
return false;
}
ownerName = name;
return true;
}
/**
* Gets the owner name of this file
*
* @return the owner name or <tt>null</tt> if empty
*/
public String getOwnerName() {
return ownerName;
}
/**
* Gets the size of this object (in byte).<br>
* NOTE: This object size is NOT the actual file size. Moreover, this size is used for
* transferring this object over a network.
*
* @return the object size (in byte)
*/
public int getAttributeSize() {
int length = DataCloudTags.PKT_SIZE;
if (ownerName != null) {
length += ownerName.length();
}
if (name != null) {
length += name.length();
}
return length;
}
/**
* Sets the file size (in MBytes)
*
* @param fileSize the file size (in MBytes)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setFileSize(int fileSize) {
if (fileSize < 0) {
return false;
}
size = fileSize;
return true;
}
/**
* Gets the file size (in MBytes)
*
* @return the file size (in MBytes)
*/
public int getFileSize() {
return size;
}
/**
* Gets the file size (in bytes)
*
* @return the file size (in bytes)
*/
public int getFileSizeInByte() {
return size * Consts.MILLION; // 1e6
// return size * 1048576; // 1e6 - more accurate
}
/**
* Sets the last update time of this file (in seconds)<br>
* NOTE: This time is relative to the start time. Preferably use
* {@link gridsim.CloudSim#clock()} method.
*
* @param time the last update time (in seconds)
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setUpdateTime(double time) {
if (time <= 0 || time < lastUpdateTime) {
return false;
}
lastUpdateTime = time;
return true;
}
/**
* Gets the last update time (in seconds)
*
* @return the last update time (in seconds)
*/
public double getLastUpdateTime() {
return lastUpdateTime;
}
/**
* Sets the file registration ID (published by a Replica Catalogue entity)
*
* @param id registration ID
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setRegistrationId(int id) {
if (id < 0) {
return false;
}
this.id = id;
return true;
}
/**
* Gets the file registration ID
*
* @return registration ID
*/
public int getRegistrationID() {
return id;
}
/**
* Sets the file type (e.g. raw, tag, etc)
*
* @param type a file type
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setType(int type) {
if (type < 0) {
return false;
}
this.type = type;
return true;
}
/**
* Gets this file type
*
* @return file type
*/
public int getType() {
return type;
}
/**
* Sets the checksum of this file
*
* @param checksum the checksum of this file
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setChecksum(int checksum) {
if (checksum < 0) {
return false;
}
this.checksum = checksum;
return true;
}
/**
* Gets the file checksum
*
* @return file checksum
*/
public int getChecksum() {
return checksum;
}
/**
* Sets the cost associated with this file
*
* @param cost cost of this file
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setCost(double cost) {
if (cost < 0) {
return false;
}
this.cost = cost;
return true;
}
/**
* Gets the cost associated with this file
*
* @return the cost of this file
*/
public double getCost() {
return cost;
}
/**
* Checks if this file already registered to a Replica Catalogue
*
* @return <tt>true</tt> if it is registered, <tt>false</tt> otherwise
*/
public boolean isRegistered() {
boolean result = true;
if (id == File.NOT_REGISTERED) {
result = false;
}
return result;
}
/**
* Marks this file as a master copy or replica
*
* @param masterCopy a flag denotes <tt>true</tt> for master copy or <tt>false</tt> for a
* replica
*/
public void setMasterCopy(boolean masterCopy) {
this.masterCopy = masterCopy;
}
/**
* Checks whether this file is a master copy or replica
*
* @return <tt>true</tt> if it is a master copy or <tt>false</tt> otherwise
*/
public boolean isMasterCopy() {
return masterCopy;
}
/**
* Marks this file as a read only or not
*
* @param readOnly a flag denotes <tt>true</tt> for read only or <tt>false</tt> for re-writeable
*/
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Checks whether this file is a read only or not
*
* @return <tt>true</tt> if it is a read only or <tt>false</tt> otherwise
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Sets the file name
*
* @param name the file name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the file name
*
* @return the file name
*/
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,683 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.cloudbus.cloudsim.distributions.ContinuousDistribution;
/**
* An implementation of a storage system. It simulates the behaviour of a typical harddrive storage.
* The default values for this storage are those of a Maxtor DiamonMax 10 ATA harddisk with the
* following parameters:
* <ul>
* <li>latency = 4.17 ms
* <li>avg seek time = 9 ms
* <li>max transfer rate = 133 MB/sec
* </ul>
*
* @author Uros Cibej
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public class HarddriveStorage implements Storage {
/** a list storing the names of all the files on the harddrive. */
private List<String> nameList;
/** a list storing all the files stored on the harddrive. */
private List<File> fileList;
/** the name of the harddrive. */
private final String name;
/** a generator required to randomize the seek time. */
private ContinuousDistribution gen;
/** the current size of files on the harddrive. */
private double currentSize;
/** the total capacity of the harddrive in MB. */
private final double capacity;
/** the maximum transfer rate in MB/sec. */
private double maxTransferRate;
/** the latency of the harddrive in seconds. */
private double latency;
/** the average seek time in seconds. */
private double avgSeekTime;
/**
* Creates a new harddrive storage with a given name and capacity.
*
* @param name the name of the new harddrive storage
* @param capacity the capacity in MByte
* @throws ParameterException when the name and the capacity are not valid
*/
public HarddriveStorage(String name, double capacity) throws ParameterException {
if (name == null || name.length() == 0) {
throw new ParameterException("HarddriveStorage(): Error - invalid storage name.");
}
if (capacity <= 0) {
throw new ParameterException("HarddriveStorage(): Error - capacity <= 0.");
}
this.name = name;
this.capacity = capacity;
init();
}
/**
* Creates a new harddrive storage with a given capacity. In this case the name of the storage
* is a default name.
*
* @param capacity the capacity in MByte
* @throws ParameterException when the capacity is not valid
*/
public HarddriveStorage(double capacity) throws ParameterException {
if (capacity <= 0) {
throw new ParameterException("HarddriveStorage(): Error - capacity <= 0.");
}
name = "HarddriveStorage";
this.capacity = capacity;
init();
}
/**
* The initialization of the harddrive is done in this method. The most common parameters, such
* as latency, average seek time and maximum transfer rate are set. The default values are set
* to simulate the Maxtor DiamonMax 10 ATA harddisk. Furthermore, the necessary lists are
* created.
*/
private void init() {
fileList = new ArrayList<File>();
nameList = new ArrayList<String>();
gen = null;
currentSize = 0;
latency = 0.00417; // 4.17 ms in seconds
avgSeekTime = 0.009; // 9 ms
maxTransferRate = 133; // in MB/sec
}
/**
* Gets the available space on this storage in MB.
*
* @return the available space in MB
*/
@Override
public double getAvailableSpace() {
return capacity - currentSize;
}
/**
* Checks if the storage is full or not.
*
* @return <tt>true</tt> if the storage is full, <tt>false</tt> otherwise
*/
@Override
public boolean isFull() {
if (Math.abs(currentSize - capacity) < .0000001) { // currentSize == capacity
return true;
}
return false;
}
/**
* Gets the number of files stored on this storage.
*
* @return the number of stored files
*/
@Override
public int getNumStoredFile() {
return fileList.size();
}
/**
* Makes a reservation of the space on the storage to store a file.
*
* @param fileSize the size to be reserved in MB
* @return <tt>true</tt> if reservation succeeded, <tt>false</tt> otherwise
*/
@Override
public boolean reserveSpace(int fileSize) {
if (fileSize <= 0) {
return false;
}
if (currentSize + fileSize >= capacity) {
return false;
}
currentSize += fileSize;
return true;
}
/**
* Adds a file for which the space has already been reserved. The time taken (in seconds) for
* adding the file can also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file to be added
* @return the time (in seconds) required to add the file
*/
@Override
public double addReservedFile(File file) {
if (file == null) {
return 0;
}
currentSize -= file.getSize();
double result = addFile(file);
// if add file fails, then set the current size back to its old value
if (result == 0.0) {
currentSize += file.getSize();
}
return result;
}
/**
* Checks whether there is enough space on the storage for a certain file.
*
* @param fileSize a FileAttribute object to compare to
* @return <tt>true</tt> if enough space available, <tt>false</tt> otherwise
*/
@Override
public boolean hasPotentialAvailableSpace(int fileSize) {
if (fileSize <= 0) {
return false;
}
// check if enough space left
if (getAvailableSpace() > fileSize) {
return true;
}
Iterator<File> it = fileList.iterator();
File file = null;
int deletedFileSize = 0;
// if not enough space, then if want to clear/delete some files
// then check whether it still have space or not
boolean result = false;
while (it.hasNext()) {
file = it.next();
if (!file.isReadOnly()) {
deletedFileSize += file.getSize();
}
if (deletedFileSize > fileSize) {
result = true;
break;
}
}
return result;
}
/**
* Gets the total capacity of the storage in MB.
*
* @return the capacity of the storage in MB
*/
@Override
public double getCapacity() {
return capacity;
}
/**
* Gets the current size of the stored files in MB.
*
* @return the current size of the stored files in MB
*/
@Override
public double getCurrentSize() {
return currentSize;
}
/**
* Gets the name of the storage.
*
* @return the name of this storage
*/
@Override
public String getName() {
return name;
}
/**
* Sets the latency of this harddrive in seconds.
*
* @param latency the new latency in seconds
* @return <tt>true</tt> if the setting succeeded, <tt>false</tt> otherwise
*/
public boolean setLatency(double latency) {
if (latency < 0) {
return false;
}
this.latency = latency;
return true;
}
/**
* Gets the latency of this harddrive in seconds.
*
* @return the latency in seconds
*/
public double getLatency() {
return latency;
}
/**
* Sets the maximum transfer rate of this storage system in MB/sec.
*
* @param rate the maximum transfer rate in MB/sec
* @return <tt>true</tt> if the setting succeeded, <tt>false</tt> otherwise
*/
@Override
public boolean setMaxTransferRate(int rate) {
if (rate <= 0) {
return false;
}
maxTransferRate = rate;
return true;
}
/**
* Gets the maximum transfer rate of the storage in MB/sec.
*
* @return the maximum transfer rate in MB/sec
*/
@Override
public double getMaxTransferRate() {
return maxTransferRate;
}
/**
* Sets the average seek time of the storage in seconds.
*
* @param seekTime the average seek time in seconds
* @return <tt>true</tt> if the setting succeeded, <tt>false</tt> otherwise
*/
public boolean setAvgSeekTime(double seekTime) {
return setAvgSeekTime(seekTime, null);
}
/**
* Sets the average seek time and a new generator of seek times in seconds. The generator
* determines a randomized seek time.
*
* @param seekTime the average seek time in seconds
* @param gen the ContinuousGenerator which generates seek times
* @return <tt>true</tt> if the setting succeeded, <tt>false</tt> otherwise
*/
public boolean setAvgSeekTime(double seekTime, ContinuousDistribution gen) {
if (seekTime <= 0.0) {
return false;
}
avgSeekTime = seekTime;
this.gen = gen;
return true;
}
/**
* Gets the average seek time of the harddrive in seconds.
*
* @return the average seek time in seconds
*/
public double getAvgSeekTime() {
return avgSeekTime;
}
/**
* Gets the file with the specified name. The time taken (in seconds) for getting the file can
* also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the needed file
* @return the file with the specified filename
*/
@Override
public File getFile(String fileName) {
// check first whether file name is valid or not
File obj = null;
if (fileName == null || fileName.length() == 0) {
Log.printLine(name + ".getFile(): Warning - invalid " + "file name.");
return obj;
}
Iterator<File> it = fileList.iterator();
int size = 0;
int index = 0;
boolean found = false;
File tempFile = null;
// find the file in the disk
while (it.hasNext()) {
tempFile = it.next();
size += tempFile.getSize();
if (tempFile.getName().equals(fileName)) {
found = true;
obj = tempFile;
break;
}
index++;
}
// if the file is found, then determine the time taken to get it
if (found) {
obj = fileList.get(index);
double seekTime = getSeekTime(size);
double transferTime = getTransferTime(obj.getSize());
// total time for this operation
obj.setTransactionTime(seekTime + transferTime);
}
return obj;
}
/**
* Gets the list of file names located on this storage.
*
* @return a List of file names
*/
@Override
public List<String> getFileNameList() {
return nameList;
}
/**
* Get the seek time for a file with the defined size. Given a file size in MB, this method
* returns a seek time for the file in seconds.
*
* @param fileSize the size of a file in MB
* @return the seek time in seconds
*/
private double getSeekTime(int fileSize) {
double result = 0;
if (gen != null) {
result += gen.sample();
}
if (fileSize > 0 && capacity != 0) {
result += (fileSize / capacity);
}
return result;
}
/**
* Gets the transfer time of a given file.
*
* @param fileSize the size of the transferred file
* @return the transfer time in seconds
*/
private double getTransferTime(int fileSize) {
double result = 0;
if (fileSize > 0 && capacity != 0) {
result = (fileSize * maxTransferRate) / capacity;
}
return result;
}
/**
* Check if the file is valid or not. This method checks whether the given file or the file name
* of the file is valid. The method name parameter is used for debugging purposes, to output in
* which method an error has occured.
*
* @param file the file to be checked for validity
* @param methodName the name of the method in which we check for validity of the file
* @return <tt>true</tt> if the file is valid, <tt>false</tt> otherwise
*/
private boolean isFileValid(File file, String methodName) {
if (file == null) {
Log.printLine(name + "." + methodName + ": Warning - the given file is null.");
return false;
}
String fileName = file.getName();
if (fileName == null || fileName.length() == 0) {
Log.printLine(name + "." + methodName + ": Warning - invalid file name.");
return false;
}
return true;
}
/**
* Adds a file to the storage. First, the method checks if there is enough space on the storage,
* then it checks if the file with the same name is already taken to avoid duplicate filenames. <br>
* The time taken (in seconds) for adding the file can also be found using
* {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file to be added
* @return the time taken (in seconds) for adding the specified file
*/
@Override
public double addFile(File file) {
double result = 0.0;
// check if the file is valid or not
if (!isFileValid(file, "addFile()")) {
return result;
}
// check the capacity
if (file.getSize() + currentSize > capacity) {
Log.printLine(name + ".addFile(): Warning - not enough space" + " to store " + file.getName());
return result;
}
// check if the same file name is alredy taken
if (!contains(file.getName())) {
double seekTime = getSeekTime(file.getSize());
double transferTime = getTransferTime(file.getSize());
fileList.add(file); // add the file into the HD
nameList.add(file.getName()); // add the name to the name list
currentSize += file.getSize(); // increment the current HD size
result = seekTime + transferTime; // add total time
}
file.setTransactionTime(result);
return result;
}
/**
* Adds a set of files to the storage. Runs through the list of files and save all of them. The
* time taken (in seconds) for adding each file can also be found using
* {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param list the files to be added
* @return the time taken (in seconds) for adding the specified files
*/
@Override
public double addFile(List<File> list) {
double result = 0.0;
if (list == null || list.isEmpty()) {
Log.printLine(name + ".addFile(): Warning - list is empty.");
return result;
}
Iterator<File> it = list.iterator();
File file = null;
while (it.hasNext()) {
file = it.next();
result += addFile(file); // add each file in the list
}
return result;
}
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the file to be removed
* @return the deleted file
*/
@Override
public File deleteFile(String fileName) {
if (fileName == null || fileName.length() == 0) {
return null;
}
Iterator<File> it = fileList.iterator();
File file = null;
while (it.hasNext()) {
file = it.next();
String name = file.getName();
// if a file is found then delete
if (fileName.equals(name)) {
double result = deleteFile(file);
file.setTransactionTime(result);
break;
} else {
file = null;
}
}
return file;
}
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the file to be removed
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
@Override
public double deleteFile(String fileName, File file) {
return deleteFile(file);
}
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
@Override
public double deleteFile(File file) {
double result = 0.0;
// check if the file is valid or not
if (!isFileValid(file, "deleteFile()")) {
return result;
}
double seekTime = getSeekTime(file.getSize());
double transferTime = getTransferTime(file.getSize());
// check if the file is in the storage
if (contains(file)) {
fileList.remove(file); // remove the file HD
nameList.remove(file.getName()); // remove the name from name list
currentSize -= file.getSize(); // decrement the current HD space
result = seekTime + transferTime; // total time
file.setTransactionTime(result);
}
return result;
}
/**
* Checks whether a certain file is on the storage or not.
*
* @param fileName the name of the file we are looking for
* @return <tt>true</tt> if the file is in the storage, <tt>false</tt> otherwise
*/
@Override
public boolean contains(String fileName) {
boolean result = false;
if (fileName == null || fileName.length() == 0) {
Log.printLine(name + ".contains(): Warning - invalid file name");
return result;
}
// check each file in the list
Iterator<String> it = nameList.iterator();
while (it.hasNext()) {
String name = it.next();
if (name.equals(fileName)) {
result = true;
break;
}
}
return result;
}
/**
* Checks whether a certain file is on the storage or not.
*
* @param file the file we are looking for
* @return <tt>true</tt> if the file is in the storage, <tt>false</tt> otherwise
*/
@Override
public boolean contains(File file) {
boolean result = false;
if (!isFileValid(file, "contains()")) {
return result;
}
result = contains(file.getName());
return result;
}
/**
* Renames a file on the storage. The time taken (in seconds) for renaming the file can also be
* found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file we would like to rename
* @param newName the new name of the file
* @return <tt>true</tt> if the renaming succeeded, <tt>false</tt> otherwise
*/
@Override
public boolean renameFile(File file, String newName) {
// check whether the new filename is conflicting with existing ones
// or not
boolean result = false;
if (contains(newName)) {
return result;
}
// replace the file name in the file (physical) list
File obj = getFile(file.getName());
if (obj == null) {
return result;
} else {
obj.setName(newName);
}
// replace the file name in the name list
Iterator<String> it = nameList.iterator();
while (it.hasNext()) {
String name = it.next();
if (name.equals(file.getName())) {
file.setTransactionTime(0);
nameList.remove(name);
nameList.add(newName);
result = true;
break;
}
}
return result;
}
}

View File

@@ -0,0 +1,621 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.lists.PeList;
import org.cloudbus.cloudsim.provisioners.BwProvisioner;
import org.cloudbus.cloudsim.provisioners.RamProvisioner;
/**
* Host executes actions related to management of virtual machines (e.g., creation and destruction).
* A host has a defined policy for provisioning memory and bw, as well as an allocation policy for
* Pe's to virtual machines. A host is associated to a datacenter. It can host virtual machines.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class Host {
/** The id. */
private int id;
/** The storage. */
private long storage;
/** The ram provisioner. */
private RamProvisioner ramProvisioner;
/** The bw provisioner. */
private BwProvisioner bwProvisioner;
/** The allocation policy. */
private VmScheduler vmScheduler;
/** The vm list. */
private final List<? extends Vm> vmList = new ArrayList<Vm>();
/** The pe list. */
private List<? extends Pe> peList;
/** Tells whether this machine is working properly or has failed. */
private boolean failed;
/** The vms migrating in. */
private final List<Vm> vmsMigratingIn = new ArrayList<Vm>();
/** The datacenter where the host is placed. */
private Datacenter datacenter;
/**
* Instantiates a new host.
*
* @param id the id
* @param ramProvisioner the ram provisioner
* @param bwProvisioner the bw provisioner
* @param storage the storage
* @param peList the pe list
* @param vmScheduler the vm scheduler
*/
public Host(
int id,
RamProvisioner ramProvisioner,
BwProvisioner bwProvisioner,
long storage,
List<? extends Pe> peList,
VmScheduler vmScheduler) {
setId(id);
setRamProvisioner(ramProvisioner);
setBwProvisioner(bwProvisioner);
setStorage(storage);
setVmScheduler(vmScheduler);
setPeList(peList);
setFailed(false);
}
/**
* Requests updating of processing of cloudlets in the VMs running in this host.
*
* @param currentTime the current time
* @return expected time of completion of the next cloudlet in all VMs in this host.
* Double.MAX_VALUE if there is no future events expected in this host
* @pre currentTime >= 0.0
* @post $none
*/
public double updateVmsProcessing(double currentTime) {
double smallerTime = Double.MAX_VALUE;
for (Vm vm : getVmList()) {
double time = vm.updateVmProcessing(currentTime, getVmScheduler().getAllocatedMipsForVm(vm));
if (time > 0.0 && time < smallerTime) {
smallerTime = time;
}
}
return smallerTime;
}
/**
* Adds the migrating in vm.
*
* @param vm the vm
*/
public void addMigratingInVm(Vm vm) {
vm.setInMigration(true);
if (!getVmsMigratingIn().contains(vm)) {
if (getStorage() < vm.getSize()) {
Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #"
+ getId() + " failed by storage");
System.exit(0);
}
if (!getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam())) {
Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #"
+ getId() + " failed by RAM");
System.exit(0);
}
if (!getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw())) {
Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #"
+ getId() + " failed by BW");
System.exit(0);
}
getVmScheduler().getVmsMigratingIn().add(vm.getUid());
if (!getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips())) {
Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #"
+ getId() + " failed by MIPS");
System.exit(0);
}
setStorage(getStorage() - vm.getSize());
getVmsMigratingIn().add(vm);
getVmList().add(vm);
updateVmsProcessing(CloudSim.clock());
vm.getHost().updateVmsProcessing(CloudSim.clock());
}
}
/**
* Removes the migrating in vm.
*
* @param vm the vm
*/
public void removeMigratingInVm(Vm vm) {
vmDeallocate(vm);
getVmsMigratingIn().remove(vm);
getVmList().remove(vm);
getVmScheduler().getVmsMigratingIn().remove(vm.getUid());
vm.setInMigration(false);
}
/**
* Reallocate migrating in vms.
*/
public void reallocateMigratingInVms() {
for (Vm vm : getVmsMigratingIn()) {
if (!getVmList().contains(vm)) {
getVmList().add(vm);
}
if (!getVmScheduler().getVmsMigratingIn().contains(vm.getUid())) {
getVmScheduler().getVmsMigratingIn().add(vm.getUid());
}
getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam());
getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw());
getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips());
setStorage(getStorage() - vm.getSize());
}
}
/**
* Checks if is suitable for vm.
*
* @param vm the vm
* @return true, if is suitable for vm
*/
public boolean isSuitableForVm(Vm vm) {
return (getVmScheduler().getPeCapacity() >= vm.getCurrentRequestedMaxMips()
&& getVmScheduler().getAvailableMips() >= vm.getCurrentRequestedTotalMips()
&& getRamProvisioner().isSuitableForVm(vm, vm.getCurrentRequestedRam()) && getBwProvisioner()
.isSuitableForVm(vm, vm.getCurrentRequestedBw()));
}
/**
* Allocates PEs and memory to a new VM in the Host.
*
* @param vm Vm being started
* @return $true if the VM could be started in the host; $false otherwise
* @pre $none
* @post $none
*/
public boolean vmCreate(Vm vm) {
if (getStorage() < vm.getSize()) {
Log.printLine("[VmScheduler.vmCreate] Allocation of VM #" + vm.getId() + " to Host #" + getId()
+ " failed by storage");
return false;
}
if (!getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam())) {
Log.printLine("[VmScheduler.vmCreate] Allocation of VM #" + vm.getId() + " to Host #" + getId()
+ " failed by RAM");
return false;
}
if (!getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw())) {
Log.printLine("[VmScheduler.vmCreate] Allocation of VM #" + vm.getId() + " to Host #" + getId()
+ " failed by BW");
getRamProvisioner().deallocateRamForVm(vm);
return false;
}
if (!getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips())) {
Log.printLine("[VmScheduler.vmCreate] Allocation of VM #" + vm.getId() + " to Host #" + getId()
+ " failed by MIPS");
getRamProvisioner().deallocateRamForVm(vm);
getBwProvisioner().deallocateBwForVm(vm);
return false;
}
setStorage(getStorage() - vm.getSize());
getVmList().add(vm);
vm.setHost(this);
return true;
}
/**
* Destroys a VM running in the host.
*
* @param vm the VM
* @pre $none
* @post $none
*/
public void vmDestroy(Vm vm) {
if (vm != null) {
vmDeallocate(vm);
getVmList().remove(vm);
vm.setHost(null);
}
}
/**
* Destroys all VMs running in the host.
*
* @pre $none
* @post $none
*/
public void vmDestroyAll() {
vmDeallocateAll();
for (Vm vm : getVmList()) {
vm.setHost(null);
setStorage(getStorage() + vm.getSize());
}
getVmList().clear();
}
/**
* Deallocate all hostList for the VM.
*
* @param vm the VM
*/
protected void vmDeallocate(Vm vm) {
getRamProvisioner().deallocateRamForVm(vm);
getBwProvisioner().deallocateBwForVm(vm);
getVmScheduler().deallocatePesForVm(vm);
setStorage(getStorage() + vm.getSize());
}
/**
* Deallocate all hostList for the VM.
*/
protected void vmDeallocateAll() {
getRamProvisioner().deallocateRamForAllVms();
getBwProvisioner().deallocateBwForAllVms();
getVmScheduler().deallocatePesForAllVms();
}
/**
* Returns a VM object.
*
* @param vmId the vm id
* @param userId ID of VM's owner
* @return the virtual machine object, $null if not found
* @pre $none
* @post $none
*/
public Vm getVm(int vmId, int userId) {
for (Vm vm : getVmList()) {
if (vm.getId() == vmId && vm.getUserId() == userId) {
return vm;
}
}
return null;
}
/**
* Gets the pes number.
*
* @return the pes number
*/
public int getNumberOfPes() {
return getPeList().size();
}
/**
* Gets the free pes number.
*
* @return the free pes number
*/
public int getNumberOfFreePes() {
return PeList.getNumberOfFreePes(getPeList());
}
/**
* Gets the total mips.
*
* @return the total mips
*/
public int getTotalMips() {
return PeList.getTotalMips(getPeList());
}
/**
* Allocates PEs for a VM.
*
* @param vm the vm
* @param mipsShare the mips share
* @return $true if this policy allows a new VM in the host, $false otherwise
* @pre $none
* @post $none
*/
public boolean allocatePesForVm(Vm vm, List<Double> mipsShare) {
return getVmScheduler().allocatePesForVm(vm, mipsShare);
}
/**
* Releases PEs allocated to a VM.
*
* @param vm the vm
* @pre $none
* @post $none
*/
public void deallocatePesForVm(Vm vm) {
getVmScheduler().deallocatePesForVm(vm);
}
/**
* Returns the MIPS share of each Pe that is allocated to a given VM.
*
* @param vm the vm
* @return an array containing the amount of MIPS of each pe that is available to the VM
* @pre $none
* @post $none
*/
public List<Double> getAllocatedMipsForVm(Vm vm) {
return getVmScheduler().getAllocatedMipsForVm(vm);
}
/**
* Gets the total allocated MIPS for a VM over all the PEs.
*
* @param vm the vm
* @return the allocated mips for vm
*/
public double getTotalAllocatedMipsForVm(Vm vm) {
return getVmScheduler().getTotalAllocatedMipsForVm(vm);
}
/**
* Returns maximum available MIPS among all the PEs.
*
* @return max mips
*/
public double getMaxAvailableMips() {
return getVmScheduler().getMaxAvailableMips();
}
/**
* Gets the free mips.
*
* @return the free mips
*/
public double getAvailableMips() {
return getVmScheduler().getAvailableMips();
}
/**
* Gets the machine bw.
*
* @return the machine bw
* @pre $none
* @post $result > 0
*/
public long getBw() {
return getBwProvisioner().getBw();
}
/**
* Gets the machine memory.
*
* @return the machine memory
* @pre $none
* @post $result > 0
*/
public int getRam() {
return getRamProvisioner().getRam();
}
/**
* Gets the machine storage.
*
* @return the machine storage
* @pre $none
* @post $result >= 0
*/
public long getStorage() {
return storage;
}
/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
protected void setId(int id) {
this.id = id;
}
/**
* Gets the ram provisioner.
*
* @return the ram provisioner
*/
public RamProvisioner getRamProvisioner() {
return ramProvisioner;
}
/**
* Sets the ram provisioner.
*
* @param ramProvisioner the new ram provisioner
*/
protected void setRamProvisioner(RamProvisioner ramProvisioner) {
this.ramProvisioner = ramProvisioner;
}
/**
* Gets the bw provisioner.
*
* @return the bw provisioner
*/
public BwProvisioner getBwProvisioner() {
return bwProvisioner;
}
/**
* Sets the bw provisioner.
*
* @param bwProvisioner the new bw provisioner
*/
protected void setBwProvisioner(BwProvisioner bwProvisioner) {
this.bwProvisioner = bwProvisioner;
}
/**
* Gets the VM scheduler.
*
* @return the VM scheduler
*/
public VmScheduler getVmScheduler() {
return vmScheduler;
}
/**
* Sets the VM scheduler.
*
* @param vmScheduler the vm scheduler
*/
protected void setVmScheduler(VmScheduler vmScheduler) {
this.vmScheduler = vmScheduler;
}
/**
* Gets the pe list.
*
* @param <T> the generic type
* @return the pe list
*/
@SuppressWarnings("unchecked")
public <T extends Pe> List<T> getPeList() {
return (List<T>) peList;
}
/**
* Sets the pe list.
*
* @param <T> the generic type
* @param peList the new pe list
*/
protected <T extends Pe> void setPeList(List<T> peList) {
this.peList = peList;
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Vm> List<T> getVmList() {
return (List<T>) vmList;
}
/**
* Sets the storage.
*
* @param storage the new storage
*/
protected void setStorage(long storage) {
this.storage = storage;
}
/**
* Checks if is failed.
*
* @return true, if is failed
*/
public boolean isFailed() {
return failed;
}
/**
* Sets the PEs of this machine to a FAILED status. NOTE: <tt>resName</tt> is used for debugging
* purposes, which is <b>ON</b> by default. Use {@link #setFailed(boolean)} if you do not want
* this information.
*
* @param resName the name of the resource
* @param failed the failed
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setFailed(String resName, boolean failed) {
// all the PEs are failed (or recovered, depending on fail)
this.failed = failed;
PeList.setStatusFailed(getPeList(), resName, getId(), failed);
return true;
}
/**
* Sets the PEs of this machine to a FAILED status.
*
* @param failed the failed
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
public boolean setFailed(boolean failed) {
// all the PEs are failed (or recovered, depending on fail)
this.failed = failed;
PeList.setStatusFailed(getPeList(), failed);
return true;
}
/**
* Sets the particular Pe status on this Machine.
*
* @param peId the pe id
* @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
* @return <tt>true</tt> if the Pe status has changed, <tt>false</tt> otherwise (Pe id might not
* be exist)
* @pre peID >= 0
* @post $none
*/
public boolean setPeStatus(int peId, int status) {
return PeList.setPeStatus(getPeList(), peId, status);
}
/**
* Gets the vms migrating in.
*
* @return the vms migrating in
*/
public List<Vm> getVmsMigratingIn() {
return vmsMigratingIn;
}
/**
* Gets the data center.
*
* @return the data center where the host runs
*/
public Datacenter getDatacenter() {
return datacenter;
}
/**
* Sets the data center.
*
* @param datacenter the data center from this host
*/
public void setDatacenter(Datacenter datacenter) {
this.datacenter = datacenter;
}
}

View File

@@ -0,0 +1,304 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.lists.PeList;
import org.cloudbus.cloudsim.provisioners.BwProvisioner;
import org.cloudbus.cloudsim.provisioners.RamProvisioner;
/**
* The class of a host supporting dynamic workloads and performance degradation.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class HostDynamicWorkload extends Host {
/** The utilization mips. */
private double utilizationMips;
/** The previous utilization mips. */
private double previousUtilizationMips;
/** The state history. */
private final List<HostStateHistoryEntry> stateHistory = new LinkedList<HostStateHistoryEntry>();
/**
* Instantiates a new host.
*
* @param id the id
* @param ramProvisioner the ram provisioner
* @param bwProvisioner the bw provisioner
* @param storage the storage
* @param peList the pe list
* @param vmScheduler the VM scheduler
*/
public HostDynamicWorkload(
int id,
RamProvisioner ramProvisioner,
BwProvisioner bwProvisioner,
long storage,
List<? extends Pe> peList,
VmScheduler vmScheduler) {
super(id, ramProvisioner, bwProvisioner, storage, peList, vmScheduler);
setUtilizationMips(0);
setPreviousUtilizationMips(0);
}
/*
* (non-Javadoc)
* @see cloudsim.Host#updateVmsProcessing(double)
*/
@Override
public double updateVmsProcessing(double currentTime) {
double smallerTime = super.updateVmsProcessing(currentTime);
setPreviousUtilizationMips(getUtilizationMips());
setUtilizationMips(0);
double hostTotalRequestedMips = 0;
for (Vm vm : getVmList()) {
getVmScheduler().deallocatePesForVm(vm);
}
for (Vm vm : getVmList()) {
getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips());
}
for (Vm vm : getVmList()) {
double totalRequestedMips = vm.getCurrentRequestedTotalMips();
double totalAllocatedMips = getVmScheduler().getTotalAllocatedMipsForVm(vm);
if (!Log.isDisabled()) {
Log.formatLine(
"%.2f: [Host #" + getId() + "] Total allocated MIPS for VM #" + vm.getId()
+ " (Host #" + vm.getHost().getId()
+ ") is %.2f, was requested %.2f out of total %.2f (%.2f%%)",
CloudSim.clock(),
totalAllocatedMips,
totalRequestedMips,
vm.getMips(),
totalRequestedMips / vm.getMips() * 100);
List<Pe> pes = getVmScheduler().getPesAllocatedForVM(vm);
StringBuilder pesString = new StringBuilder();
for (Pe pe : pes) {
pesString.append(String.format(" PE #" + pe.getId() + ": %.2f.", pe.getPeProvisioner()
.getTotalAllocatedMipsForVm(vm)));
}
Log.formatLine(
"%.2f: [Host #" + getId() + "] MIPS for VM #" + vm.getId() + " by PEs ("
+ getNumberOfPes() + " * " + getVmScheduler().getPeCapacity() + ")."
+ pesString,
CloudSim.clock());
}
if (getVmsMigratingIn().contains(vm)) {
Log.formatLine("%.2f: [Host #" + getId() + "] VM #" + vm.getId()
+ " is being migrated to Host #" + getId(), CloudSim.clock());
} else {
if (totalAllocatedMips + 0.1 < totalRequestedMips) {
Log.formatLine("%.2f: [Host #" + getId() + "] Under allocated MIPS for VM #" + vm.getId()
+ ": %.2f", CloudSim.clock(), totalRequestedMips - totalAllocatedMips);
}
vm.addStateHistoryEntry(
currentTime,
totalAllocatedMips,
totalRequestedMips,
(vm.isInMigration() && !getVmsMigratingIn().contains(vm)));
if (vm.isInMigration()) {
Log.formatLine(
"%.2f: [Host #" + getId() + "] VM #" + vm.getId() + " is in migration",
CloudSim.clock());
totalAllocatedMips /= 0.9; // performance degradation due to migration - 10%
}
}
setUtilizationMips(getUtilizationMips() + totalAllocatedMips);
hostTotalRequestedMips += totalRequestedMips;
}
addStateHistoryEntry(
currentTime,
getUtilizationMips(),
hostTotalRequestedMips,
(getUtilizationMips() > 0));
return smallerTime;
}
/**
* Gets the completed vms.
*
* @return the completed vms
*/
public List<Vm> getCompletedVms() {
List<Vm> vmsToRemove = new ArrayList<Vm>();
for (Vm vm : getVmList()) {
if (vm.isInMigration()) {
continue;
}
if (vm.getCurrentRequestedTotalMips() == 0) {
vmsToRemove.add(vm);
}
}
return vmsToRemove;
}
/**
* Gets the max utilization among by all PEs.
*
* @return the utilization
*/
public double getMaxUtilization() {
return PeList.getMaxUtilization(getPeList());
}
/**
* Gets the max utilization among by all PEs allocated to the VM.
*
* @param vm the vm
* @return the utilization
*/
public double getMaxUtilizationAmongVmsPes(Vm vm) {
return PeList.getMaxUtilizationAmongVmsPes(getPeList(), vm);
}
/**
* Gets the utilization of memory.
*
* @return the utilization of memory
*/
public double getUtilizationOfRam() {
return getRamProvisioner().getUsedRam();
}
/**
* Gets the utilization of bw.
*
* @return the utilization of bw
*/
public double getUtilizationOfBw() {
return getBwProvisioner().getUsedBw();
}
/**
* Get current utilization of CPU in percentage.
*
* @return current utilization of CPU in percents
*/
public double getUtilizationOfCpu() {
double utilization = getUtilizationMips() / getTotalMips();
if (utilization > 1 && utilization < 1.01) {
utilization = 1;
}
return utilization;
}
/**
* Gets the previous utilization of CPU in percentage.
*
* @return the previous utilization of cpu
*/
public double getPreviousUtilizationOfCpu() {
double utilization = getPreviousUtilizationMips() / getTotalMips();
if (utilization > 1 && utilization < 1.01) {
utilization = 1;
}
return utilization;
}
/**
* Get current utilization of CPU in MIPS.
*
* @return current utilization of CPU in MIPS
*/
public double getUtilizationOfCpuMips() {
return getUtilizationMips();
}
/**
* Gets the utilization mips.
*
* @return the utilization mips
*/
public double getUtilizationMips() {
return utilizationMips;
}
/**
* Sets the utilization mips.
*
* @param utilizationMips the new utilization mips
*/
protected void setUtilizationMips(double utilizationMips) {
this.utilizationMips = utilizationMips;
}
/**
* Gets the previous utilization mips.
*
* @return the previous utilization mips
*/
public double getPreviousUtilizationMips() {
return previousUtilizationMips;
}
/**
* Sets the previous utilization mips.
*
* @param previousUtilizationMips the new previous utilization mips
*/
protected void setPreviousUtilizationMips(double previousUtilizationMips) {
this.previousUtilizationMips = previousUtilizationMips;
}
/**
* Gets the state history.
*
* @return the state history
*/
public List<HostStateHistoryEntry> getStateHistory() {
return stateHistory;
}
/**
* Adds the state history entry.
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param isActive the is active
*/
public
void
addStateHistoryEntry(double time, double allocatedMips, double requestedMips, boolean isActive) {
HostStateHistoryEntry newState = new HostStateHistoryEntry(
time,
allocatedMips,
requestedMips,
isActive);
if (!getStateHistory().isEmpty()) {
HostStateHistoryEntry previousState = getStateHistory().get(getStateHistory().size() - 1);
if (previousState.getTime() == time) {
getStateHistory().set(getStateHistory().size() - 1, newState);
return;
}
}
getStateHistory().add(newState);
}
}

View File

@@ -0,0 +1,118 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2011, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* The Class HostStateHistoryEntry.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.1.2
*/
public class HostStateHistoryEntry {
/** The time. */
private double time;
/** The allocated mips. */
private double allocatedMips;
/** The requested mips. */
private double requestedMips;
/** The is active. */
private boolean isActive;
/**
* Instantiates a new vm mips allocation history entry.
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param isActive the is active
*/
public HostStateHistoryEntry(double time, double allocatedMips, double requestedMips, boolean isActive) {
setTime(time);
setAllocatedMips(allocatedMips);
setRequestedMips(requestedMips);
setActive(isActive);
}
/**
* Sets the time.
*
* @param time the new time
*/
protected void setTime(double time) {
this.time = time;
}
/**
* Gets the time.
*
* @return the time
*/
public double getTime() {
return time;
}
/**
* Sets the allocated mips.
*
* @param allocatedMips the new allocated mips
*/
protected void setAllocatedMips(double allocatedMips) {
this.allocatedMips = allocatedMips;
}
/**
* Gets the allocated mips.
*
* @return the allocated mips
*/
public double getAllocatedMips() {
return allocatedMips;
}
/**
* Sets the requested mips.
*
* @param requestedMips the new requested mips
*/
protected void setRequestedMips(double requestedMips) {
this.requestedMips = requestedMips;
}
/**
* Gets the requested mips.
*
* @return the requested mips
*/
public double getRequestedMips() {
return requestedMips;
}
/**
* Sets the active.
*
* @param isActive the new active
*/
public void setActive(boolean isActive) {
this.isActive = isActive;
}
/**
* Checks if is active.
*
* @return true, if is active
*/
public boolean isActive() {
return isActive;
}
}

View File

@@ -0,0 +1,566 @@
/*
* ** Network and Service Differentiation Extensions to CloudSim 3.0 **
*
* Gokul Poduval & Chen-Khong Tham
* Computer Communication Networks (CCN) Lab
* Dept of Electrical & Computer Engineering
* National University of Singapore
* August 2004
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2004, The University of Melbourne, Australia and National
* University of Singapore
* InfoPacket.java - Implementation of a Information Packet.
*
*/
package org.cloudbus.cloudsim;
import java.text.DecimalFormat;
import java.util.Vector;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
/**
* InfoPacket class can be used to gather information from the network layer. An InfoPacket
* traverses the network topology similar to a {@link gridsim.net.NetPacket}, but it collects
* information like bandwidths, and Round Trip Time etc. It is the equivalent of ICMP in physical
* networks.
* <p>
* You can set all the parameters to an InfoPacket that can be applied to a NetPacket. So if you
* want to find out the kind of information that a particular type of NetPacket is experiencing, set
* the size and network class of an InfoPacket to the same as the NetPacket, and send it to the same
* destination from the same source.
*
* @author Gokul Poduval
* @author Chen-Khong Tham, National University of Singapore
* @since CloudSim Toolkit 1.0
*/
public class InfoPacket implements Packet {
/** The packet name. */
private final String name;
/** The size of this packet. */
private long size;
/** The id of this packet. */
private final int packetId;
/** The original sender id. */
private final int srcId;
/** The destination id. */
private int destId;
/** The last hop. */
private int last;
/** Whether going or returning. */
private int tag;
/** The number of hops. */
private int hopsNumber;
/** The original ping size. */
private long pingSize;
/** The level of service type. */
private int netServiceType;
/** The bandwidth bottleneck. */
private double bandwidth;
/** The list of entity IDs. */
private Vector<Integer> entities;
/** The list of entry times. */
private Vector<Double> entryTimes;
/** The list of exit times. */
private Vector<Double> exitTimes;
/** The list of entity's baud rate. */
private Vector<Double> baudRates;
/** The formatting the decimal points. */
private DecimalFormat num;
/**
* Constructs a new Information packet.
*
* @param name Name of this packet
* @param packetID The ID of this packet
* @param size size of the packet
* @param srcID The ID of the entity that sends out this packet
* @param destID The ID of the entity to which this packet is destined
* @param netServiceType the class of traffic this packet belongs to
* @pre name != null
* @post $none
*/
public InfoPacket(String name, int packetID, long size, int srcID, int destID, int netServiceType) {
this.name = name;
packetId = packetID;
srcId = srcID;
destId = destID;
this.size = size;
this.netServiceType = netServiceType;
init();
}
/**
* Initialises common attributes.
*
* @pre $none
* @post $none
*/
private void init() {
last = srcId;
tag = CloudSimTags.INFOPKT_SUBMIT;
bandwidth = -1;
hopsNumber = 0;
pingSize = size;
if (name != null) {
entities = new Vector<Integer>();
entryTimes = new Vector<Double>();
exitTimes = new Vector<Double>();
baudRates = new Vector<Double>();
num = new DecimalFormat("#0.000#"); // 4 decimal spaces
}
}
/**
* Returns the ID of this packet.
*
* @return packet ID
* @pre $none
* @post $none
*/
@Override
public int getId() {
return packetId;
}
/**
* Sets original size of ping request.
*
* @param size ping data size (in bytes)
* @pre size >= 0
* @post $none
*/
public void setOriginalPingSize(long size) {
pingSize = size;
}
/**
* Gets original size of ping request.
*
* @return original size
* @pre $none
* @post $none
*/
public long getOriginalPingSize() {
return pingSize;
}
/**
* Returns a human-readable information of this packet.
*
* @return description of this packet
* @pre $none
* @post $none
*/
@Override
public String toString() {
if (name == null) {
return "Empty InfoPacket that contains no ping information.";
}
int SIZE = 1000; // number of chars
StringBuffer sb = new StringBuffer(SIZE);
sb.append("Ping information for " + name + "\n");
sb.append("Entity Name\tEntry Time\tExit Time\t Bandwidth\n");
sb.append("----------------------------------------------------------\n");
String tab = " "; // 4 spaces
for (int i = 0; i < entities.size(); i++) {
int resID = entities.get(i).intValue();
sb.append(CloudSim.getEntityName(resID) + "\t\t");
String entry = getData(entryTimes, i);
String exit = getData(exitTimes, i);
String bw = getData(baudRates, i);
sb.append(entry + tab + tab + exit + tab + tab + bw + "\n");
}
sb.append("\nRound Trip Time : " + num.format(getTotalResponseTime()));
sb.append(" seconds");
sb.append("\nNumber of Hops : " + getNumHop());
sb.append("\nBottleneck Bandwidth : " + bandwidth + " bits/s");
return sb.toString();
}
/**
* Gets relevant data from a list.
*
* @param v a list
* @param index the location in a list
* @return the data
* @pre v != null
* @post index > 0
*/
private String getData(Vector<Double> v, int index) {
String result;
try {
Double obj = v.get(index);
double id = obj.doubleValue();
result = num.format(id);
} catch (Exception e) {
result = " N/A";
}
return result;
}
/**
* Gets the size of this packet.
*
* @return size of the packet.
* @pre $none
* @post $none
*/
@Override
public long getSize() {
return size;
}
/**
* Sets the size of this packet.
*
* @param size size of the packet
* @return <tt>true</tt> if it is successful, <tt>false</tt> otherwise
* @pre size >= 0
* @post $none
*/
@Override
public boolean setSize(long size) {
if (size < 0) {
return false;
}
this.size = size;
return true;
}
/**
* Gets the id of the entity to which the packet is destined.
*
* @return the desination ID
* @pre $none
* @post $none
*/
@Override
public int getDestId() {
return destId;
}
/**
* Gets the id of the entity that sent out this packet.
*
* @return the source ID
* @pre $none
* @post $none
*/
@Override
public int getSrcId() {
return srcId;
}
/**
* Returns the number of hops that this packet has traversed. Since the packet takes a round
* trip, the same router may have been traversed twice.
*
* @return the number of hops this packet has traversed
* @pre $none
* @post $none
*/
public int getNumHop() {
int PAIR = 2;
return ((hopsNumber - PAIR) + 1) / PAIR;
}
/**
* Gets the total time that this packet has spent in the network. This is basically the RTT.
* Dividing this by half should be the approximate latency.
* <p>
* RTT is taken as the final entry time - first exit time.
*
* @return total round time
* @pre $none
* @post $none
*/
public double getTotalResponseTime() {
if (exitTimes == null || entryTimes == null) {
return 0;
}
double time = 0;
try {
double startTime = exitTimes.firstElement().doubleValue();
double receiveTime = entryTimes.lastElement().doubleValue();
time = receiveTime - startTime;
} catch (Exception e) {
time = 0;
}
return time;
}
/**
* Returns the bottleneck bandwidth between the source and the destination.
*
* @return the bottleneck bandwidth
* @pre $none
* @post $none
*/
public double getBaudRate() {
return bandwidth;
}
/**
* This method should be called by network entities that count as hops, for e.g. Routers or
* CloudResources. It should not be called by links etc.
*
* @param id the id of the hop that this InfoPacket is traversing
* @pre id > 0
* @post $none
*/
public void addHop(int id) {
if (entities == null) {
return;
}
hopsNumber++;
entities.add(Integer.valueOf(id));
}
/**
* This method should be called by routers and other entities when this InfoPacket reaches them
* along with the current simulation time.
*
* @param time current simulation time, use {@link gridsim.CloudSim#clock()} to obtain this
* @pre time >= 0
* @post $none
*/
public void addEntryTime(double time) {
if (entryTimes == null) {
return;
}
if (time < 0) {
time = 0.0;
}
entryTimes.add(Double.valueOf(time));
}
/**
* This method should be called by routers and other entities when this InfoPacket is leaving
* them. It should also supply the current simulation time.
*
* @param time current simulation time, use {@link gridsim.CloudSim#clock()} to obtain this
* @pre time >= 0
* @post $none
*/
public void addExitTime(double time) {
if (exitTimes == null) {
return;
}
if (time < 0) {
time = 0.0;
}
exitTimes.add(Double.valueOf(time));
}
/**
* Every entity that the InfoPacket traverses should add the baud rate of the link on which this
* packet will be sent out next.
*
* @param baudRate the entity's baud rate in bits/s
* @pre baudRate > 0
* @post $none
*/
public void addBaudRate(double baudRate) {
if (baudRates == null) {
return;
}
baudRates.add(new Double(baudRate));
if (bandwidth < 0 || baudRate < bandwidth) {
bandwidth = baudRate;
}
}
/**
* Returns the list of all the bandwidths that this packet has traversed.
*
* @return a Double Array of links bandwidths
* @pre $none
* @post $none
*/
public Object[] getDetailBaudRate() {
if (baudRates == null) {
return null;
}
return baudRates.toArray();
}
/**
* Returns the list of all the hops that this packet has traversed.
*
* @return an Integer Array of hop ids
* @pre $none
* @post $none
*/
public Object[] getDetailHops() {
if (entities == null) {
return null;
}
return entities.toArray();
}
/**
* Returns the list of all entry time that this packet has traversed.
*
* @return an Integer Array of entry time
* @pre $none
* @post $none
*/
public Object[] getDetailEntryTimes() {
if (entryTimes == null) {
return null;
}
return entryTimes.toArray();
}
/**
* Returns the list of all exit time that this packet has traversed.
*
* @return an Integer Array of exit time
* @pre $none
* @post $none
*/
public Object[] getDetailExitTimes() {
if (exitTimes == null) {
return null;
}
return exitTimes.toArray();
}
/**
* Gets an entity ID from the last hop that this packet has traversed.
*
* @return an entity ID
* @pre $none
* @post $none
*/
@Override
public int getLast() {
return last;
}
/**
* Sets an entity ID from the last hop that this packet has traversed.
*
* @param last an entity ID from the last hop
* @pre last > 0
* @post $none
*/
@Override
public void setLast(int last) {
this.last = last;
}
/**
* Gets the network service type of this packet.
*
* @return the network service type
* @pre $none
* @post $none
*/
@Override
public int getNetServiceType() {
return netServiceType;
}
/**
* Sets the network service type of this packet.
*
* @param netServiceType the packet's network service type
* @pre netServiceType >= 0
* @post $none
*/
@Override
public void setNetServiceType(int netServiceType) {
this.netServiceType = netServiceType;
}
/**
* Gets this packet tag.
*
* @return this packet tag
* @pre $none
* @post $none
*/
@Override
public int getTag() {
return tag;
}
/**
* Sets the tag of this packet.
*
* @param tag the packet's tag
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @pre tag > 0
* @post $none
*/
public boolean setTag(int tag) {
boolean flag = false;
switch (tag) {
case CloudSimTags.INFOPKT_SUBMIT:
case CloudSimTags.INFOPKT_RETURN:
this.tag = tag;
flag = true;
break;
default:
flag = false;
break;
}
return flag;
}
/**
* Sets the destination ID for this packet.
*
* @param id this packet's destination ID
* @pre id > 0
* @post $none
*/
public void setDestId(int id) {
destId = id;
}
}

View File

@@ -0,0 +1,166 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.io.IOException;
import java.io.OutputStream;
/**
* The Log class used for performing loggin of the simulation process. It provides the ability to
* substitute the output stream by any OutputStream subclass.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class Log {
/** The Constant LINE_SEPARATOR. */
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** The output. */
private static OutputStream output;
/** The disable output flag. */
private static boolean disabled;
/**
* Prints the message.
*
* @param message the message
*/
public static void print(String message) {
if (!isDisabled()) {
try {
getOutput().write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Prints the message passed as a non-String object.
*
* @param message the message
*/
public static void print(Object message) {
if (!isDisabled()) {
print(String.valueOf(message));
}
}
/**
* Prints the line.
*
* @param message the message
*/
public static void printLine(String message) {
if (!isDisabled()) {
print(message + LINE_SEPARATOR);
}
}
/**
* Prints the empty line.
*/
public static void printLine() {
if (!isDisabled()) {
print(LINE_SEPARATOR);
}
}
/**
* Prints the line passed as a non-String object.
*
* @param message the message
*/
public static void printLine(Object message) {
if (!isDisabled()) {
printLine(String.valueOf(message));
}
}
/**
* Prints a string formated as in String.format().
*
* @param format the format
* @param args the args
*/
public static void format(String format, Object... args) {
if (!isDisabled()) {
print(String.format(format, args));
}
}
/**
* Prints a line formated as in String.format().
*
* @param format the format
* @param args the args
*/
public static void formatLine(String format, Object... args) {
if (!isDisabled()) {
printLine(String.format(format, args));
}
}
/**
* Sets the output.
*
* @param _output the new output
*/
public static void setOutput(OutputStream _output) {
output = _output;
}
/**
* Gets the output.
*
* @return the output
*/
public static OutputStream getOutput() {
if (output == null) {
setOutput(System.out);
}
return output;
}
/**
* Sets the disable output flag.
*
* @param _disabled the new disabled
*/
public static void setDisabled(boolean _disabled) {
disabled = _disabled;
}
/**
* Checks if the output is disabled.
*
* @return true, if is disable
*/
public static boolean isDisabled() {
return disabled;
}
/**
* Disables the output.
*/
public static void disable() {
setDisabled(true);
}
/**
* Enables the output.
*/
public static void enable() {
setDisabled(false);
}
}

View File

@@ -0,0 +1,248 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.cloudbus.cloudsim.network.DelayMatrix_Float;
import org.cloudbus.cloudsim.network.GraphReaderBrite;
import org.cloudbus.cloudsim.network.TopologicalGraph;
import org.cloudbus.cloudsim.network.TopologicalLink;
import org.cloudbus.cloudsim.network.TopologicalNode;
/**
* NetworkTopology is a class that implements network layer in CloudSim. It reads a BRITE file and
* generates a topological network from it. Information of this network is used to simulate latency
* in network traffic of CloudSim.
* <p>
* The topology file may contain more nodes the the number of entities in the simulation. It allows
* for users to increase the scale of the simulation without changing the topology file.
* Nevertheless, each CloudSim entity must be mapped to one (and only one) BRITE node to allow
* proper work of the network simulation. Each BRITE node can be mapped to only one entity at a
* time.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class NetworkTopology {
protected static int nextIdx = 0;
private static boolean networkEnabled = false;
protected static DelayMatrix_Float delayMatrix = null;
protected static double[][] bwMatrix = null;
protected static TopologicalGraph graph = null;
protected static Map<Integer, Integer> map = null;
/**
* Creates the network topology if file exists and if file can be succesfully parsed. File is
* written in the BRITE format and contains topologycal information on simulation entities.
*
* @param fileName name of the BRITE file
* @pre fileName != null
* @post $none
*/
public static void buildNetworkTopology(String fileName) {
Log.printLine("Topology file: " + fileName);
// try to find the file
GraphReaderBrite reader = new GraphReaderBrite();
try {
graph = reader.readGraphFile(fileName);
map = new HashMap<Integer, Integer>();
generateMatrices();
} catch (IOException e) {
// problem with the file. Does not simulate network
Log.printLine("Problem in processing BRITE file. Network simulation is disabled. Error: "
+ e.getMessage());
}
}
/**
* Generates the matrices used internally to set latency and bandwidth between elements
*/
private static void generateMatrices() {
// creates the delay matrix
delayMatrix = new DelayMatrix_Float(graph, false);
// creates the bw matrix
bwMatrix = createBwMatrix(graph, false);
networkEnabled = true;
}
/**
* Adds a new link in the network topology
*
* @param srcId ID of the link's source
* @param destId ID of the link's destination
* @param bw Link's bandwidth
* @param lat link's latency
* @pre srcId > 0
* @pre destId > 0
* @post $none
*/
public static void addLink(int srcId, int destId, double bw, double lat) {
if (graph == null) {
graph = new TopologicalGraph();
}
if (map == null) {
map = new HashMap<Integer, Integer>();
}
// maybe add the nodes
if (!map.containsKey(srcId)) {
graph.addNode(new TopologicalNode(nextIdx));
map.put(srcId, nextIdx);
nextIdx++;
}
if (!map.containsKey(destId)) {
graph.addNode(new TopologicalNode(nextIdx));
map.put(destId, nextIdx);
nextIdx++;
}
// generate a new link
graph.addLink(new TopologicalLink(map.get(srcId), map.get(destId), (float) lat, (float) bw));
generateMatrices();
}
/**
* Creates the matrix containiing the available bandiwdth beteen two nodes
*
* @param graph topological graph describing the topology
* @param directed true if the graph is directed; false otherwise
* @return the bandwidth graph
*/
private static double[][] createBwMatrix(TopologicalGraph graph, boolean directed) {
int nodes = graph.getNumberOfNodes();
double[][] mtx = new double[nodes][nodes];
// cleanup matrix
for (int i = 0; i < nodes; i++) {
for (int j = 0; j < nodes; j++) {
mtx[i][j] = 0.0;
}
}
Iterator<TopologicalLink> iter = graph.getLinkIterator();
while (iter.hasNext()) {
TopologicalLink edge = iter.next();
mtx[edge.getSrcNodeID()][edge.getDestNodeID()] = edge.getLinkBw();
if (!directed) {
mtx[edge.getDestNodeID()][edge.getSrcNodeID()] = edge.getLinkBw();
}
}
return mtx;
}
/**
* Maps a CloudSim entity to a node in the network topology
*
* @param cloudSimEntityID ID of the entity being mapped
* @param briteID ID of the BRITE node that corresponds to the CloudSim entity
* @pre cloudSimEntityID >= 0
* @pre briteID >= 0
* @post $none
*/
public static void mapNode(int cloudSimEntityID, int briteID) {
if (networkEnabled) {
try {
// this CloudSim entity was already mapped?
if (!map.containsKey(cloudSimEntityID)) {
if (!map.containsValue(briteID)) { // this BRITE node was already mapped?
map.put(cloudSimEntityID, briteID);
} else {
Log.printLine("Error in network mapping. BRITE node " + briteID + " already in use.");
}
} else {
Log.printLine("Error in network mapping. CloudSim entity " + cloudSimEntityID
+ " already mapped.");
}
} catch (Exception e) {
Log.printLine("Error in network mapping. CloudSim node " + cloudSimEntityID
+ " not mapped to BRITE node " + briteID + ".");
}
}
}
/**
* Unmaps a previously mapped CloudSim entity to a node in the network topology
*
* @param cloudSimEntityID ID of the entity being unmapped
* @pre cloudSimEntityID >= 0
* @post $none
*/
public static void unmapNode(int cloudSimEntityID) {
if (networkEnabled) {
try {
map.remove(cloudSimEntityID);
} catch (Exception e) {
Log.printLine("Error in network unmapping. CloudSim node: " + cloudSimEntityID);
}
}
}
/**
* Calculates the delay between two nodes
*
* @param srcID ID of the source node
* @param destID ID of the destination node
* @return communication delay between the two nodes
* @pre srcID >= 0
* @pre destID >= 0
* @post $none
*/
public static double getDelay(int srcID, int destID) {
if (networkEnabled) {
try {
// add the network latency
double delay = delayMatrix.getDelay(map.get(srcID), map.get(destID));
return delay;
} catch (Exception e) {
// in case of error, just keep running and return 0.0
}
}
return 0.0;
}
/**
* This method returns true if network simulation is working. If there were some problem during
* creation of network (e.g., during parsing of BRITE file) that does not allow a proper
* simulation of the network, this method returns false.
*
* @return $true if network simulation is ok. $false otherwise
* @pre $none
* @post $none
*/
public static boolean isNetworkEnabled() {
return networkEnabled;
}
}

View File

@@ -0,0 +1,130 @@
/*
* Gokul Poduval & Chen-Khong Tham
* Computer Communication Networks (CCN) Lab
* Dept of Electrical & Computer Engineering
* National University of Singapore
* August 2004
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2004, The University of Melbourne, Australia and National
* University of Singapore
* Packet.java - Interface of a Network Packet.
*
*/
package org.cloudbus.cloudsim;
/**
* This class contains the structure for a network packet.
*
* @author Gokul Poduval
* @author Chen-Khong Tham, National University of Singapore
* @since CloudSim Toolkit 1.0
*/
public interface Packet {
/**
* Returns a string describing this packet in detail.
*
* @return description of this packet
* @pre $none
* @post $none
*/
@Override
String toString();
/**
* Returns the size of this packet
*
* @return size of the packet
* @pre $none
* @post $none
*/
long getSize();
/**
* Sets the size of this packet
*
* @param size size of the packet
* @return <tt>true</tt> if it is successful, <tt>false</tt> otherwise
* @pre size >= 0
* @post $none
*/
boolean setSize(long size);
/**
* Returns the destination id of this packet.
*
* @return destination id
* @pre $none
* @post $none
*/
int getDestId();
/**
* Returns the ID of this packet
*
* @return packet ID
* @pre $none
* @post $none
*/
int getId();
/**
* Returns the ID of the source of this packet.
*
* @return source id
* @pre $none
* @post $none
*/
int getSrcId();
/**
* Gets the network service type of this packet
*
* @return the network service type
* @pre $none
* @post $none
*/
int getNetServiceType();
/**
* Sets the network service type of this packet.
* <p>
* By default, the service type is 0 (zero). It is depends on the packet scheduler to determine
* the priority of this service level.
*
* @param serviceType this packet's service type
* @pre serviceType >= 0
* @post $none
*/
void setNetServiceType(int serviceType);
/**
* Gets an entity ID from the last hop that this packet has traversed.
*
* @return an entity ID
* @pre $none
* @post $none
*/
int getLast();
/**
* Sets an entity ID from the last hop that this packet has traversed.
*
* @param last an entity ID from the last hop
* @pre last > 0
* @post $none
*/
void setLast(int last);
/**
* Gets this packet tag
*
* @return this packet tag
* @pre $none
* @post $none
*/
int getTag();
}

View File

@@ -0,0 +1,69 @@
/*
* ** Network and Service Differentiation Extensions to CloudSim 3.0 **
*
* Gokul Poduval & Chen-Khong Tham
* Computer Communication Networks (CCN) Lab
* Dept of Electrical & Computer Engineering
* National University of Singapore
* October 2004
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2004, The University of Melbourne, Australia and
* National University of Singapore
* ParameterException.java - Thrown for illegal parameters
*
*/
package org.cloudbus.cloudsim;
/**
* This exception is to report bad or invalid parameters given during constructor.
*
* @author Gokul Poduval
* @author Chen-Khong Tham, National University of Singapore
* @since CloudSim Toolkit 1.0
*/
public class ParameterException extends Exception {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The message. */
private final String message;
/**
* Constructs a new exception with <tt>null</tt> as its detail message.
*
* @pre $none
* @post $none
*/
public ParameterException() {
super();
message = null;
}
/**
* Creates a new ParameterException object.
*
* @param message an error message
* @pre $none
* @post $none
*/
public ParameterException(String message) {
super();
this.message = message;
}
/**
* Returns an error message of this object.
*
* @return an error message
* @pre $none
* @post $none
*/
@Override
public String toString() {
return message;
}
}

View File

@@ -0,0 +1,175 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import org.cloudbus.cloudsim.provisioners.PeProvisioner;
/**
* CloudSim Pe (Processing Element) class represents CPU unit, defined in terms of Millions
* Instructions Per Second (MIPS) rating.<br>
* <b>ASSUMPTION:<b> All PEs under the same Machine have the same MIPS rating.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @since CloudSim Toolkit 1.0
*/
public class Pe {
/** Denotes Pe is FREE for allocation. */
public static final int FREE = 1;
/** Denotes Pe is allocated and hence busy in processing Cloudlet. */
public static final int BUSY = 2;
/**
* Denotes Pe is failed and hence it can't process any Cloudlet at this moment. This Pe is
* failed because it belongs to a machine which is also failed.
*/
public static final int FAILED = 3;
/** The id. */
private int id;
// FOR SPACE SHARED RESOURCE: Jan 21
/** The status of Pe: FREE, BUSY, FAILED: . */
private int status;
/** The pe provisioner. */
private PeProvisioner peProvisioner;
/**
* Allocates a new Pe object.
*
* @param id the Pe ID
* @param peProvisioner the pe provisioner
* @pre id >= 0
* @pre peProvisioner != null
* @post $none
*/
public Pe(int id, PeProvisioner peProvisioner) {
setId(id);
setPeProvisioner(peProvisioner);
// when created it should be set to FREE, i.e. available for use.
status = FREE;
}
/**
* Sets the id.
*
* @param id the new id
*/
protected void setId(int id) {
this.id = id;
}
/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the MIPS Rating of this Pe.
*
* @param d the mips
* @pre mips >= 0
* @post $none
*/
public void setMips(double d) {
getPeProvisioner().setMips(d);
}
/**
* Gets the MIPS Rating of this Pe.
*
* @return the MIPS Rating
* @pre $none
* @post $result >= 0
*/
public int getMips() {
return (int) getPeProvisioner().getMips();
}
/**
* Gets the status of this Pe.
*
* @return the status of this Pe
* @pre $none
* @post $none
*/
public int getStatus() {
return status;
}
/**
* Sets Pe status to free, meaning it is available for processing. This should be used by SPACE
* shared hostList only.
*
* @pre $none
* @post $none
*/
public void setStatusFree() {
setStatus(FREE);
}
/**
* Sets Pe status to busy, meaning it is already executing Cloudlets. This should be used by
* SPACE shared hostList only.
*
* @pre $none
* @post $none
*/
public void setStatusBusy() {
setStatus(BUSY);
}
/**
* Sets this Pe to FAILED.
*
* @pre $none
* @post $none
*/
public void setStatusFailed() {
setStatus(FAILED);
}
/**
* Sets Pe status to either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
*
* @param status Pe status, <tt>true</tt> if it is FREE, <tt>false</tt> if BUSY.
* @pre $none
* @post $none
*/
public void setStatus(int status) {
this.status = status;
}
/**
* Sets the pe provisioner.
*
* @param peProvisioner the new pe provisioner
*/
protected void setPeProvisioner(PeProvisioner peProvisioner) {
this.peProvisioner = peProvisioner;
}
/**
* Gets the Pe provisioner.
*
* @return the Pe provisioner
*/
public PeProvisioner getPeProvisioner() {
return peProvisioner;
}
}

View File

@@ -0,0 +1,551 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* CloudSim ResCloudlet represents a Cloudlet submitted to CloudResource for processing. This class
* keeps track the time for all activities in the CloudResource for a specific Cloudlet. Before a
* Cloudlet exits the CloudResource, it is RECOMMENDED to call this method
* {@link #finalizeCloudlet()}.
* <p>
* It contains a Cloudlet object along with its arrival time and the ID of the machine and the Pe
* (Processing Element) allocated to it. It acts as a placeholder for maintaining the amount of
* resource share allocated at various times for simulating any scheduling using internal events.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @since CloudSim Toolkit 1.0
*/
public class ResCloudlet {
/** The Cloudlet object. */
private final Cloudlet cloudlet;
/** The Cloudlet arrival time for the first time. */
private double arrivalTime;
/** The estimation of Cloudlet finished time. */
private double finishedTime;
/** The length of Cloudlet finished so far. */
private long cloudletFinishedSoFar;
/**
* Cloudlet execution start time. This attribute will only hold the latest time since a Cloudlet
* can be cancel, paused or resumed.
*/
private double startExecTime;
/** The total time to complete this Cloudlet. */
private double totalCompletionTime;
// The below attributes are only be used by the SpaceShared policy.
/** The machine id this Cloudlet is assigned to. */
private int machineId;
/** The Pe id this Cloudlet is assigned to. */
private int peId;
/** The an array of machine IDs. */
private int[] machineArrayId = null;
/** The an array of Pe IDs. */
private int[] peArrayId = null;
/** The index of machine and Pe arrays. */
private int index;
// NOTE: Below attributes are related to AR stuff
/** The Constant NOT_FOUND. */
private static final int NOT_FOUND = -1;
/** The reservation start time. */
private final long startTime;
/** The reservation duration time. */
private final int duration;
/** The reservation id. */
private final int reservId;
/** The num Pe needed to execute this Cloudlet. */
private int pesNumber;
/**
* Allocates a new ResCloudlet object upon the arrival of a Cloudlet object. The arriving time
* is determined by {@link gridsim.CloudSim#clock()}.
*
* @param cloudlet a cloudlet object
* @see gridsim.CloudSim#clock()
* @pre cloudlet != null
* @post $none
*/
public ResCloudlet(Cloudlet cloudlet) {
// when a new ResCloudlet is created, then it will automatically set
// the submission time and other properties, such as remaining length
this.cloudlet = cloudlet;
startTime = 0;
reservId = NOT_FOUND;
duration = 0;
init();
}
/**
* Allocates a new ResCloudlet object upon the arrival of a Cloudlet object. Use this
* constructor to store reserved Cloudlets, i.e. Cloudlets that done reservation before. The
* arriving time is determined by {@link gridsim.CloudSim#clock()}.
*
* @param cloudlet a cloudlet object
* @param startTime a reservation start time. Can also be interpreted as starting time to
* execute this Cloudlet.
* @param duration a reservation duration time. Can also be interpreted as how long to execute
* this Cloudlet.
* @param reservID a reservation ID that owns this Cloudlet
* @see gridsim.CloudSim#clock()
* @pre cloudlet != null
* @pre startTime > 0
* @pre duration > 0
* @pre reservID > 0
* @post $none
*/
public ResCloudlet(Cloudlet cloudlet, long startTime, int duration, int reservID) {
this.cloudlet = cloudlet;
this.startTime = startTime;
reservId = reservID;
this.duration = duration;
init();
}
/**
* Gets the Cloudlet or reservation start time.
*
* @return Cloudlet's starting time
* @pre $none
* @post $none
*/
public long getStartTime() {
return startTime;
}
/**
* Gets the reservation duration time.
*
* @return reservation duration time
* @pre $none
* @post $none
*/
public int getDurationTime() {
return duration;
}
/**
* Gets the number of PEs required to execute this Cloudlet.
*
* @return number of Pe
* @pre $none
* @post $none
*/
public int getNumberOfPes() {
return pesNumber;
}
/**
* Gets the reservation ID that owns this Cloudlet.
*
* @return a reservation ID
* @pre $none
* @post $none
*/
public int getReservationID() {
return reservId;
}
/**
* Checks whether this Cloudlet is submitted by reserving or not.
*
* @return <tt>true</tt> if this Cloudlet has reserved before, <tt>false</tt> otherwise
* @pre $none
* @post $none
*/
public boolean hasReserved() {
if (reservId == NOT_FOUND) {
return false;
}
return true;
}
/**
* Initialises all local attributes.
*
* @pre $none
* @post $none
*/
private void init() {
// get number of PEs required to run this Cloudlet
pesNumber = cloudlet.getNumberOfPes();
// if more than 1 Pe, then create an array
if (pesNumber > 1) {
machineArrayId = new int[pesNumber];
peArrayId = new int[pesNumber];
}
arrivalTime = CloudSim.clock();
cloudlet.setSubmissionTime(arrivalTime);
// default values
finishedTime = NOT_FOUND; // Cannot finish in this hourly slot.
machineId = NOT_FOUND;
peId = NOT_FOUND;
index = 0;
totalCompletionTime = 0.0;
startExecTime = 0.0;
// In case a Cloudlet has been executed partially by some other grid
// hostList.
cloudletFinishedSoFar = cloudlet.getCloudletFinishedSoFar() * Consts.MILLION;
}
/**
* Gets this Cloudlet entity Id.
*
* @return the Cloudlet entity Id
* @pre $none
* @post $none
*/
public int getCloudletId() {
return cloudlet.getCloudletId();
}
/**
* Gets the user or owner of this Cloudlet.
*
* @return the Cloudlet's user Id
* @pre $none
* @post $none
*/
public int getUserId() {
return cloudlet.getUserId();
}
/**
* Gets the Cloudlet's length.
*
* @return Cloudlet's length
* @pre $none
* @post $none
*/
public long getCloudletLength() {
return cloudlet.getCloudletLength();
}
/**
* Gets the total Cloudlet's length (across all PEs).
*
* @return total Cloudlet's length
* @pre $none
* @post $none
*/
public long getCloudletTotalLength() {
return cloudlet.getCloudletTotalLength();
}
/**
* Gets the Cloudlet's class type.
*
* @return class type of the Cloudlet
* @pre $none
* @post $none
*/
public int getCloudletClassType() {
return cloudlet.getClassType();
}
/**
* Sets the Cloudlet status.
*
* @param status the Cloudlet status
* @return <tt>true</tt> if the new status has been set, <tt>false</tt> otherwise
* @pre status >= 0
* @post $none
*/
public boolean setCloudletStatus(int status) {
// gets Cloudlet's previous status
int prevStatus = cloudlet.getCloudletStatus();
// if the status of a Cloudlet is the same as last time, then ignore
if (prevStatus == status) {
return false;
}
boolean success = true;
try {
double clock = CloudSim.clock(); // gets the current clock
// sets Cloudlet's current status
cloudlet.setCloudletStatus(status);
// if a previous Cloudlet status is INEXEC
if (prevStatus == Cloudlet.INEXEC) {
// and current status is either CANCELED, PAUSED or SUCCESS
if (status == Cloudlet.CANCELED || status == Cloudlet.PAUSED || status == Cloudlet.SUCCESS) {
// then update the Cloudlet completion time
totalCompletionTime += (clock - startExecTime);
index = 0;
return true;
}
}
if (prevStatus == Cloudlet.RESUMED && status == Cloudlet.SUCCESS) {
// then update the Cloudlet completion time
totalCompletionTime += (clock - startExecTime);
return true;
}
// if a Cloudlet is now in execution
if (status == Cloudlet.INEXEC || (prevStatus == Cloudlet.PAUSED && status == Cloudlet.RESUMED)) {
startExecTime = clock;
cloudlet.setExecStartTime(startExecTime);
}
} catch (Exception e) {
success = false;
}
return success;
}
/**
* Gets the Cloudlet's execution start time.
*
* @return Cloudlet's execution start time
* @pre $none
* @post $none
*/
public double getExecStartTime() {
return cloudlet.getExecStartTime();
}
/**
* Sets this Cloudlet's execution parameters. These parameters are set by the CloudResource
* before departure or sending back to the original Cloudlet's owner.
*
* @param wallClockTime the time of this Cloudlet resides in a CloudResource (from arrival time
* until departure time).
* @param actualCPUTime the total execution time of this Cloudlet in a CloudResource.
* @pre wallClockTime >= 0.0
* @pre actualCPUTime >= 0.0
* @post $none
*/
public void setExecParam(double wallClockTime, double actualCPUTime) {
cloudlet.setExecParam(wallClockTime, actualCPUTime);
}
/**
* Sets the machine and Pe (Processing Element) ID.
*
* @param machineId machine ID
* @param peId Pe ID
* @pre machineID >= 0
* @pre peID >= 0
* @post $none
*/
public void setMachineAndPeId(int machineId, int peId) {
// if this job only requires 1 Pe
this.machineId = machineId;
this.peId = peId;
// if this job requires many PEs
if (peArrayId != null && pesNumber > 1) {
machineArrayId[index] = machineId;
peArrayId[index] = peId;
index++;
}
}
/**
* Gets machine ID.
*
* @return machine ID or <tt>-1</tt> if it is not specified before
* @pre $none
* @post $result >= -1
*/
public int getMachineId() {
return machineId;
}
/**
* Gets Pe ID.
*
* @return Pe ID or <tt>-1</tt> if it is not specified before
* @pre $none
* @post $result >= -1
*/
public int getPeId() {
return peId;
}
/**
* Gets a list of Pe IDs. <br>
* NOTE: To get the machine IDs corresponding to these Pe IDs, use {@link #getMachineIdList()}.
*
* @return an array containing Pe IDs.
* @pre $none
* @post $none
*/
public int[] getPeIdList() {
return peArrayId;
}
/**
* Gets a list of Machine IDs. <br>
* NOTE: To get the Pe IDs corresponding to these machine IDs, use {@link #getPeIdList()}.
*
* @return an array containing Machine IDs.
* @pre $none
* @post $none
*/
public int[] getMachineIdList() {
return machineArrayId;
}
/**
* Gets the remaining cloudlet length.
*
* @return cloudlet length
* @pre $none
* @post $result >= 0
*/
public long getRemainingCloudletLength() {
long length = cloudlet.getCloudletTotalLength() * Consts.MILLION - cloudletFinishedSoFar;
// Remaining Cloudlet length can't be negative number.
if (length < 0) {
return 0;
}
return (long) Math.floor(length / Consts.MILLION);
}
/**
* Finalizes all relevant information before <tt>exiting</tt> the CloudResource entity. This
* method sets the final data of:
* <ul>
* <li>wall clock time, i.e. the time of this Cloudlet resides in a CloudResource (from arrival
* time until departure time).
* <li>actual CPU time, i.e. the total execution time of this Cloudlet in a CloudResource.
* <li>Cloudlet's finished so far
* </ul>
*
* @pre $none
* @post $none
*/
public void finalizeCloudlet() {
// Sets the wall clock time and actual CPU time
double wallClockTime = CloudSim.clock() - arrivalTime;
cloudlet.setExecParam(wallClockTime, totalCompletionTime);
long finished = 0;
//if (cloudlet.getCloudletTotalLength() * Consts.MILLION < cloudletFinishedSoFar) {
if (cloudlet.getCloudletStatus()==Cloudlet.SUCCESS) {
finished = cloudlet.getCloudletLength();
} else {
finished = cloudletFinishedSoFar / Consts.MILLION;
}
cloudlet.setCloudletFinishedSoFar(finished);
}
/**
* A method that updates the length of cloudlet that has been completed.
*
* @param miLength cloudlet length in Instructions (I)
* @pre miLength >= 0.0
* @post $none
*/
public void updateCloudletFinishedSoFar(long miLength) {
cloudletFinishedSoFar += miLength;
}
/**
* Gets arrival time of a cloudlet.
*
* @return arrival time
* @pre $none
* @post $result >= 0.0
*/
public double getCloudletArrivalTime() {
return arrivalTime;
}
/**
* Sets the finish time for this Cloudlet. If time is negative, then it is being ignored.
*
* @param time finish time
* @pre time >= 0.0
* @post $none
*/
public void setFinishTime(double time) {
if (time < 0.0) {
return;
}
finishedTime = time;
}
/**
* Gets the Cloudlet's finish time.
*
* @return finish time of a cloudlet or <tt>-1.0</tt> if it cannot finish in this hourly slot
* @pre $none
* @post $result >= -1.0
*/
public double getClouddletFinishTime() {
return finishedTime;
}
/**
* Gets this Cloudlet object.
*
* @return cloudlet object
* @pre $none
* @post $result != null
*/
public Cloudlet getCloudlet() {
return cloudlet;
}
/**
* Gets the Cloudlet status.
*
* @return Cloudlet status
* @pre $none
* @post $none
*/
public int getCloudletStatus() {
return cloudlet.getCloudletStatus();
}
/**
* Get unique string identificator of the VM.
*
* @return string uid
*/
public String getUid() {
return getUserId() + "-" + getCloudletId();
}
}

View File

@@ -0,0 +1,166 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.Iterator;
import java.util.List;
/**
* SANStorage represents a storage area network composed of a set of harddisks connected in a LAN.
* Capacity of individual disks are abstracted, thus only the overall capacity of the SAN is
* considered. WARNING: This class is not yet fully functional. Effects of network contention are
* not considered in the simulation. So, time for file transfer is underestimated in the presence of
* high network load.
*
* @author Rodrigo N. Calheiros
* @since CloudSim Toolkit 1.0
*/
public class SanStorage extends HarddriveStorage {
/** The bandwidth. */
double bandwidth;
/** The network latency. */
double networkLatency;
/**
* Creates a new SAN with a given capacity, latency, and bandwidth of the network connection.
*
* @param capacity Storage device capacity
* @param bandwidth Network bandwidth
* @param networkLatency Network latency
* @throws ParameterException when the name and the capacity are not valid
*/
public SanStorage(double capacity, double bandwidth, double networkLatency) throws ParameterException {
super(capacity);
this.bandwidth = bandwidth;
this.networkLatency = networkLatency;
}
/**
* Creates a new SAN with a given capacity, latency, and bandwidth of the network connection.
*
* @param name the name of the new harddrive storage
* @param capacity Storage device capacity
* @param bandwidth Network bandwidth
* @param networkLatency Network latency
* @throws ParameterException when the name and the capacity are not valid
*/
public SanStorage(String name, double capacity, double bandwidth, double networkLatency)
throws ParameterException {
super(name, capacity);
this.bandwidth = bandwidth;
this.networkLatency = networkLatency;
}
/**
* Adds a file for which the space has already been reserved.
*
* @param file the file to be added
* @return the time (in seconds) required to add the file
*/
@Override
public double addReservedFile(File file) {
double time = super.addReservedFile(file);
time += networkLatency;
time += file.getSize() * bandwidth;
return time;
}
/**
* Gets the maximum transfer rate of the storage in MB/sec.
*
* @return the maximum transfer rate in MB/sec
*/
@Override
public double getMaxTransferRate() {
double diskRate = super.getMaxTransferRate();
// the max transfer rate is the minimum between
// the network bandwidth and the disk rate
if (diskRate < bandwidth) {
return diskRate;
}
return bandwidth;
}
/**
* Adds a file to the storage.
*
* @param file the file to be added
* @return the time taken (in seconds) for adding the specified file
*/
@Override
public double addFile(File file) {
double time = super.addFile(file);
time += networkLatency;
time += file.getSize() * bandwidth;
return time;
}
/**
* Adds a set of files to the storage. Runs through the list of files and save all of them. The
* time taken (in seconds) for adding each file can also be found using
* {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param list the files to be added
* @return the time taken (in seconds) for adding the specified files
*/
@Override
public double addFile(List<File> list) {
double result = 0.0;
if (list == null || list.size() == 0) {
Log.printLine(getName() + ".addFile(): Warning - list is empty.");
return result;
}
Iterator<File> it = list.iterator();
File file = null;
while (it.hasNext()) {
file = it.next();
result += this.addFile(file); // add each file in the list
}
return result;
}
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the file to be removed
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
@Override
public double deleteFile(String fileName, File file) {
return this.deleteFile(file);
}
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
@Override
public double deleteFile(File file) {
double time = super.deleteFile(file);
time += networkLatency;
time += file.getSize() * bandwidth;
return time;
}
}

View File

@@ -0,0 +1,197 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.List;
/**
* An interface which defines the desired functionality of a storage system in a Data Cloud. The
* classes that implement this interface should simulate the characteristics of different storage
* systems by setting the capacity of the storage and the maximum transfer rate. The transfer rate
* defines the time required to execute some common operations on the storage, e.g. storing a file,
* getting a file and deleting a file.
*
* @author Uros Cibej
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public interface Storage {
/**
* Gets the name of the storage.
*
* @return the name of this storage
*/
String getName();
/**
* Gets the total capacity of the storage in MByte.
*
* @return the capacity of the storage in MB
*/
double getCapacity();
/**
* Gets the current size of the storage in MByte.
*
* @return the current size of the storage in MB
*/
double getCurrentSize();
/**
* Gets the maximum transfer rate of the storage in MByte/sec.
*
* @return the maximum transfer rate in MB/sec
*/
double getMaxTransferRate();
/**
* Gets the available space on this storage in MByte.
*
* @return the available space in MB
*/
double getAvailableSpace();
/**
* Sets the maximum transfer rate of this storage system in MByte/sec.
*
* @param rate the maximum transfer rate in MB/sec
* @return <tt>true</tt> if the setting succeeded, <tt>false</tt> otherwise
*/
boolean setMaxTransferRate(int rate);
/**
* Checks if the storage is full or not.
*
* @return <tt>true</tt> if the storage is full, <tt>false</tt> otherwise
*/
boolean isFull();
/**
* Gets the number of files stored on this storage.
*
* @return the number of stored files
*/
int getNumStoredFile();
/**
* Makes a reservation of the space on the storage to store a file.
*
* @param fileSize the size to be reserved in MB
* @return <tt>true</tt> if reservation succeeded, <tt>false</tt> otherwise
*/
boolean reserveSpace(int fileSize);
/**
* Adds a file for which the space has already been reserved. The time taken (in seconds) for
* adding the specified file can also be found using
* {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file to be added
* @return the time (in seconds) required to add the file
*/
double addReservedFile(File file);
/**
* Checks whether there is enough space on the storage for a certain file.
*
* @param fileSize a FileAttribute object to compare to
* @return <tt>true</tt> if enough space available, <tt>false</tt> otherwise
*/
boolean hasPotentialAvailableSpace(int fileSize);
/**
* Gets the file with the specified name. The time taken (in seconds) for getting the specified
* file can also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the needed file
* @return the file with the specified filename
*/
File getFile(String fileName);
/**
* Gets the list of file names located on this storage.
*
* @return a List of file names
*/
List<String> getFileNameList();
/**
* Adds a file to the storage. The time taken (in seconds) for adding the specified file can
* also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file to be added
* @return the time taken (in seconds) for adding the specified file
*/
double addFile(File file);
/**
* Adds a set of files to the storage. The time taken (in seconds) for adding each file can also
* be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param list the files to be added
* @return the time taken (in seconds) for adding the specified files
*/
double addFile(List<File> list);
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the specified file
* can be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the file to be removed
* @return the deleted file.
*/
File deleteFile(String fileName);
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the specified file
* can also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param fileName the name of the file to be removed
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
double deleteFile(String fileName, File file);
/**
* Removes a file from the storage. The time taken (in seconds) for deleting the specified file
* can also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file which is removed from the storage is returned through this parameter
* @return the time taken (in seconds) for deleting the specified file
*/
double deleteFile(File file);
/**
* Checks whether a file is stored in the storage or not.
*
* @param fileName the name of the file we are looking for
* @return <tt>true</tt> if the file is in the storage, <tt>false</tt> otherwise
*/
boolean contains(String fileName);
/**
* Checks whether a file is stored in the storage or not.
*
* @param file the file we are looking for
* @return <tt>true</tt> if the file is in the storage, <tt>false</tt> otherwise
*/
boolean contains(File file);
/**
* Renames a file on the storage. The time taken (in seconds) for renaming the specified file
* can also be found using {@link gridsim.datagrid.File#getTransactionTime()}.
*
* @param file the file we would like to rename
* @param newName the new name of the file
* @return <tt>true</tt> if the renaming succeeded, <tt>false</tt> otherwise
*/
boolean renameFile(File file, String newName);
}

View File

@@ -0,0 +1,28 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* The UtilizationModel interface needs to be implemented in order to provide a fine-grained control
* over resource usage by a Cloudlet.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public interface UtilizationModel {
/**
* Returns utilization in percents according to the time.
*
* @param time the time
* @return utilization percentage
*/
double getUtilization(double time);
}

View File

@@ -0,0 +1,29 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* The UtilizationModelFull class is a simple model, according to which a Cloudlet always utilize
* all the available CPU capacity.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class UtilizationModelFull implements UtilizationModel {
/*
* (non-Javadoc)
* @see cloudsim.power.UtilizationModel#getUtilization(double)
*/
@Override
public double getUtilization(double time) {
return 1;
}
}

View File

@@ -0,0 +1,29 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* The UtilizationModelNull class is a simple model, according to which a Cloudlet always require
* zero capacity.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class UtilizationModelNull implements UtilizationModel {
/*
* (non-Javadoc)
* @see cloudsim.power.UtilizationModel#getUtilization(double)
*/
@Override
public double getUtilization(double time) {
return 0;
}
}

View File

@@ -0,0 +1,97 @@
package org.cloudbus.cloudsim;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* The Class UtilizationModelPlanetLab.
*/
public class UtilizationModelPlanetLabInMemory implements UtilizationModel {
/** The scheduling interval. */
private double schedulingInterval;
/** The data (5 min * 288 = 24 hours). */
private final double[] data;
/**
* Instantiates a new utilization model PlanetLab.
*
* @param inputPath the input path
* @throws NumberFormatException the number format exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public UtilizationModelPlanetLabInMemory(String inputPath, double schedulingInterval)
throws NumberFormatException,
IOException {
data = new double[289];
setSchedulingInterval(schedulingInterval);
BufferedReader input = new BufferedReader(new FileReader(inputPath));
int n = data.length;
for (int i = 0; i < n - 1; i++) {
data[i] = Integer.valueOf(input.readLine()) / 100.0;
}
data[n - 1] = data[n - 2];
input.close();
}
/**
* Instantiates a new utilization model PlanetLab with variable data samples.
*
* @param inputPath the input path
* @param dataSamples number of samples in the file
* @throws NumberFormatException the number format exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public UtilizationModelPlanetLabInMemory(String inputPath, double schedulingInterval, int dataSamples)
throws NumberFormatException,
IOException {
setSchedulingInterval(schedulingInterval);
data = new double[dataSamples];
BufferedReader input = new BufferedReader(new FileReader(inputPath));
int n = data.length;
for (int i = 0; i < n - 1; i++) {
data[i] = Integer.valueOf(input.readLine()) / 100.0;
}
data[n - 1] = data[n - 2];
input.close();
}
/*
* (non-Javadoc)
* @see cloudsim.power.UtilizationModel#getUtilization(double)
*/
@Override
public double getUtilization(double time) {
if (time % getSchedulingInterval() == 0) {
return data[(int) time / (int) getSchedulingInterval()];
}
int time1 = (int) Math.floor(time / getSchedulingInterval());
int time2 = (int) Math.ceil(time / getSchedulingInterval());
double utilization1 = data[time1];
double utilization2 = data[time2];
double delta = (utilization2 - utilization1) / ((time2 - time1) * getSchedulingInterval());
double utilization = utilization1 + delta * (time - time1 * getSchedulingInterval());
return utilization;
}
/**
* Sets the scheduling interval.
*
* @param schedulingInterval the new scheduling interval
*/
public void setSchedulingInterval(double schedulingInterval) {
this.schedulingInterval = schedulingInterval;
}
/**
* Gets the scheduling interval.
*
* @return the scheduling interval
*/
public double getSchedulingInterval() {
return schedulingInterval;
}
}

View File

@@ -0,0 +1,130 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* The UtilizationModelStochastic class implements a model, according to which a Cloudlet generates
* random CPU utilization every time frame.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class UtilizationModelStochastic implements UtilizationModel {
/** The random generator. */
private Random randomGenerator;
/** The history. */
private Map<Double, Double> history;
/**
* Instantiates a new utilization model stochastic.
*/
public UtilizationModelStochastic() {
setHistory(new HashMap<Double, Double>());
setRandomGenerator(new Random());
}
/**
* Instantiates a new utilization model stochastic.
*
* @param seed the seed
*/
public UtilizationModelStochastic(long seed) {
setHistory(new HashMap<Double, Double>());
setRandomGenerator(new Random(seed));
}
/*
* (non-Javadoc)
* @see cloudsim.power.UtilizationModel#getUtilization(double)
*/
@Override
public double getUtilization(double time) {
if (getHistory().containsKey(time)) {
return getHistory().get(time);
}
double utilization = getRandomGenerator().nextDouble();
getHistory().put(time, utilization);
return utilization;
}
/**
* Gets the history.
*
* @return the history
*/
protected Map<Double, Double> getHistory() {
return history;
}
/**
* Sets the history.
*
* @param history the history
*/
protected void setHistory(Map<Double, Double> history) {
this.history = history;
}
/**
* Save history.
*
* @param filename the filename
* @throws Exception the exception
*/
public void saveHistory(String filename) throws Exception {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(getHistory());
oos.close();
}
/**
* Load history.
*
* @param filename the filename
* @throws Exception the exception
*/
@SuppressWarnings("unchecked")
public void loadHistory(String filename) throws Exception {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
setHistory((Map<Double, Double>) ois.readObject());
ois.close();
}
/**
* Sets the random generator.
*
* @param randomGenerator the new random generator
*/
public void setRandomGenerator(Random randomGenerator) {
this.randomGenerator = randomGenerator;
}
/**
* Gets the random generator.
*
* @return the random generator
*/
public Random getRandomGenerator() {
return randomGenerator;
}
}

View File

@@ -0,0 +1,609 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Vm represents a VM: it runs inside a Host, sharing hostList with other VMs. It processes
* cloudlets. This processing happens according to a policy, defined by the CloudletScheduler. Each
* VM has a owner, which can submit cloudlets to the VM to be executed
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class Vm {
/** The id. */
private int id;
/** The user id. */
private int userId;
/** The uid. */
private String uid;
/** The size. */
private long size;
/** The MIPS. */
private double mips;
/** The number of PEs. */
private int numberOfPes;
/** The ram. */
private int ram;
/** The bw. */
private long bw;
/** The vmm. */
private String vmm;
/** The Cloudlet scheduler. */
private CloudletScheduler cloudletScheduler;
/** The host. */
private Host host;
/** In migration flag. */
private boolean inMigration;
/** The current allocated size. */
private long currentAllocatedSize;
/** The current allocated ram. */
private int currentAllocatedRam;
/** The current allocated bw. */
private long currentAllocatedBw;
/** The current allocated mips. */
private List<Double> currentAllocatedMips;
/** The VM is being instantiated. */
private boolean beingInstantiated;
/** The mips allocation history. */
private final List<VmStateHistoryEntry> stateHistory = new LinkedList<VmStateHistoryEntry>();
/**
* Creates a new VMCharacteristics object.
*
* @param id unique ID of the VM
* @param userId ID of the VM's owner
* @param mips the mips
* @param numberOfPes amount of CPUs
* @param ram amount of ram
* @param bw amount of bandwidth
* @param size amount of storage
* @param vmm virtual machine monitor
* @param cloudletScheduler cloudletScheduler policy for cloudlets
* @pre id >= 0
* @pre userId >= 0
* @pre size > 0
* @pre ram > 0
* @pre bw > 0
* @pre cpus > 0
* @pre priority >= 0
* @pre cloudletScheduler != null
* @post $none
*/
public Vm(
int id,
int userId,
double mips,
int numberOfPes,
int ram,
long bw,
long size,
String vmm,
CloudletScheduler cloudletScheduler) {
setId(id);
setUserId(userId);
setUid(getUid(userId, id));
setMips(mips);
setNumberOfPes(numberOfPes);
setRam(ram);
setBw(bw);
setSize(size);
setVmm(vmm);
setCloudletScheduler(cloudletScheduler);
setInMigration(false);
setBeingInstantiated(true);
setCurrentAllocatedBw(0);
setCurrentAllocatedMips(null);
setCurrentAllocatedRam(0);
setCurrentAllocatedSize(0);
}
/**
* Updates the processing of cloudlets running on this VM.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each Pe available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is no
* next events
* @pre currentTime >= 0
* @post $none
*/
public double updateVmProcessing(double currentTime, List<Double> mipsShare) {
if (mipsShare != null) {
return getCloudletScheduler().updateVmProcessing(currentTime, mipsShare);
}
return 0.0;
}
/**
* Gets the current requested mips.
*
* @return the current requested mips
*/
public List<Double> getCurrentRequestedMips() {
List<Double> currentRequestedMips = getCloudletScheduler().getCurrentRequestedMips();
if (isBeingInstantiated()) {
currentRequestedMips = new ArrayList<Double>();
for (int i = 0; i < getNumberOfPes(); i++) {
currentRequestedMips.add(getMips());
}
}
return currentRequestedMips;
}
/**
* Gets the current requested total mips.
*
* @return the current requested total mips
*/
public double getCurrentRequestedTotalMips() {
double totalRequestedMips = 0;
for (double mips : getCurrentRequestedMips()) {
totalRequestedMips += mips;
}
return totalRequestedMips;
}
/**
* Gets the current requested max mips among all virtual PEs.
*
* @return the current requested max mips
*/
public double getCurrentRequestedMaxMips() {
double maxMips = 0;
for (double mips : getCurrentRequestedMips()) {
if (mips > maxMips) {
maxMips = mips;
}
}
return maxMips;
}
/**
* Gets the current requested bw.
*
* @return the current requested bw
*/
public long getCurrentRequestedBw() {
if (isBeingInstantiated()) {
return getBw();
}
return (long) (getCloudletScheduler().getCurrentRequestedUtilizationOfBw() * getBw());
}
/**
* Gets the current requested ram.
*
* @return the current requested ram
*/
public int getCurrentRequestedRam() {
if (isBeingInstantiated()) {
return getRam();
}
return (int) (getCloudletScheduler().getCurrentRequestedUtilizationOfRam() * getRam());
}
/**
* Get utilization created by all clouddlets running on this VM.
*
* @param time the time
* @return total utilization
*/
public double getTotalUtilizationOfCpu(double time) {
return getCloudletScheduler().getTotalUtilizationOfCpu(time);
}
/**
* Get utilization created by all cloudlets running on this VM in MIPS.
*
* @param time the time
* @return total utilization
*/
public double getTotalUtilizationOfCpuMips(double time) {
return getTotalUtilizationOfCpu(time) * getMips();
}
/**
* Sets the uid.
*
* @param uid the new uid
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* Get unique string identificator of the VM.
*
* @return string uid
*/
public String getUid() {
return uid;
}
/**
* Generate unique string identificator of the VM.
*
* @param userId the user id
* @param vmId the vm id
* @return string uid
*/
public static String getUid(int userId, int vmId) {
return userId + "-" + vmId;
}
/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
protected void setId(int id) {
this.id = id;
}
/**
* Sets the user id.
*
* @param userId the new user id
*/
protected void setUserId(int userId) {
this.userId = userId;
}
/**
* Gets the ID of the owner of the VM.
*
* @return VM's owner ID
* @pre $none
* @post $none
*/
public int getUserId() {
return userId;
}
/**
* Gets the mips.
*
* @return the mips
*/
public double getMips() {
return mips;
}
/**
* Sets the mips.
*
* @param mips the new mips
*/
protected void setMips(double mips) {
this.mips = mips;
}
/**
* Gets the number of pes.
*
* @return the number of pes
*/
public int getNumberOfPes() {
return numberOfPes;
}
/**
* Sets the number of pes.
*
* @param numberOfPes the new number of pes
*/
protected void setNumberOfPes(int numberOfPes) {
this.numberOfPes = numberOfPes;
}
/**
* Gets the amount of ram.
*
* @return amount of ram
* @pre $none
* @post $none
*/
public int getRam() {
return ram;
}
/**
* Sets the amount of ram.
*
* @param ram new amount of ram
* @pre ram > 0
* @post $none
*/
public void setRam(int ram) {
this.ram = ram;
}
/**
* Gets the amount of bandwidth.
*
* @return amount of bandwidth
* @pre $none
* @post $none
*/
public long getBw() {
return bw;
}
/**
* Sets the amount of bandwidth.
*
* @param bw new amount of bandwidth
* @pre bw > 0
* @post $none
*/
public void setBw(long bw) {
this.bw = bw;
}
/**
* Gets the amount of storage.
*
* @return amount of storage
* @pre $none
* @post $none
*/
public long getSize() {
return size;
}
/**
* Sets the amount of storage.
*
* @param size new amount of storage
* @pre size > 0
* @post $none
*/
public void setSize(long size) {
this.size = size;
}
/**
* Gets the VMM.
*
* @return VMM
* @pre $none
* @post $none
*/
public String getVmm() {
return vmm;
}
/**
* Sets the VMM.
*
* @param vmm the new VMM
*/
protected void setVmm(String vmm) {
this.vmm = vmm;
}
/**
* Sets the host that runs this VM.
*
* @param host Host running the VM
* @pre host != $null
* @post $none
*/
public void setHost(Host host) {
this.host = host;
}
/**
* Gets the host.
*
* @return the host
*/
public Host getHost() {
return host;
}
/**
* Gets the vm scheduler.
*
* @return the vm scheduler
*/
public CloudletScheduler getCloudletScheduler() {
return cloudletScheduler;
}
/**
* Sets the vm scheduler.
*
* @param cloudletScheduler the new vm scheduler
*/
protected void setCloudletScheduler(CloudletScheduler cloudletScheduler) {
this.cloudletScheduler = cloudletScheduler;
}
/**
* Checks if is in migration.
*
* @return true, if is in migration
*/
public boolean isInMigration() {
return inMigration;
}
/**
* Sets the in migration.
*
* @param inMigration the new in migration
*/
public void setInMigration(boolean inMigration) {
this.inMigration = inMigration;
}
/**
* Gets the current allocated size.
*
* @return the current allocated size
*/
public long getCurrentAllocatedSize() {
return currentAllocatedSize;
}
/**
* Sets the current allocated size.
*
* @param currentAllocatedSize the new current allocated size
*/
protected void setCurrentAllocatedSize(long currentAllocatedSize) {
this.currentAllocatedSize = currentAllocatedSize;
}
/**
* Gets the current allocated ram.
*
* @return the current allocated ram
*/
public int getCurrentAllocatedRam() {
return currentAllocatedRam;
}
/**
* Sets the current allocated ram.
*
* @param currentAllocatedRam the new current allocated ram
*/
public void setCurrentAllocatedRam(int currentAllocatedRam) {
this.currentAllocatedRam = currentAllocatedRam;
}
/**
* Gets the current allocated bw.
*
* @return the current allocated bw
*/
public long getCurrentAllocatedBw() {
return currentAllocatedBw;
}
/**
* Sets the current allocated bw.
*
* @param currentAllocatedBw the new current allocated bw
*/
public void setCurrentAllocatedBw(long currentAllocatedBw) {
this.currentAllocatedBw = currentAllocatedBw;
}
/**
* Gets the current allocated mips.
*
* @return the current allocated mips
* @TODO replace returning the field by a call to getCloudletScheduler().getCurrentMipsShare()
*/
public List<Double> getCurrentAllocatedMips() {
return currentAllocatedMips;
}
/**
* Sets the current allocated mips.
*
* @param currentAllocatedMips the new current allocated mips
*/
public void setCurrentAllocatedMips(List<Double> currentAllocatedMips) {
this.currentAllocatedMips = currentAllocatedMips;
}
/**
* Checks if is being instantiated.
*
* @return true, if is being instantiated
*/
public boolean isBeingInstantiated() {
return beingInstantiated;
}
/**
* Sets the being instantiated.
*
* @param beingInstantiated the new being instantiated
*/
public void setBeingInstantiated(boolean beingInstantiated) {
this.beingInstantiated = beingInstantiated;
}
/**
* Gets the state history.
*
* @return the state history
*/
public List<VmStateHistoryEntry> getStateHistory() {
return stateHistory;
}
/**
* Adds the state history entry.
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param isInMigration the is in migration
*/
public void addStateHistoryEntry(
double time,
double allocatedMips,
double requestedMips,
boolean isInMigration) {
VmStateHistoryEntry newState = new VmStateHistoryEntry(
time,
allocatedMips,
requestedMips,
isInMigration);
if (!getStateHistory().isEmpty()) {
VmStateHistoryEntry previousState = getStateHistory().get(getStateHistory().size() - 1);
if (previousState.getTime() == time) {
getStateHistory().set(getStateHistory().size() - 1, newState);
return;
}
}
getStateHistory().add(newState);
}
}

View File

@@ -0,0 +1,119 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.List;
import java.util.Map;
/**
* VmAllocationPolicy is an abstract class that represents the provisioning policy of hosts to
* virtual machines in a Datacentre. It supports two-stage commit of reservation of hosts: first, we
* reserve the host and, once commited by the user, it is effectivelly allocated to he/she
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public abstract class VmAllocationPolicy {
/** The host list. */
private List<? extends Host> hostList;
/**
* Allocates a new VmAllocationPolicy object.
*
* @param list Machines available in this Datacentre
* @pre $none
* @post $none
*/
public VmAllocationPolicy(List<? extends Host> list) {
setHostList(list);
}
/**
* Allocates a host for a given VM. The host to be allocated is the one that was already
* reserved.
*
* @param vm virtual machine which the host is reserved to
* @return $true if the host could be allocated; $false otherwise
* @pre $none
* @post $none
*/
public abstract boolean allocateHostForVm(Vm vm);
/**
* Allocates a specified host for a given VM.
*
* @param vm virtual machine which the host is reserved to
* @return $true if the host could be allocated; $false otherwise
* @pre $none
* @post $none
*/
public abstract boolean allocateHostForVm(Vm vm, Host host);
/**
* Optimize allocation of the VMs according to current utilization.
*
* @param vmList the vm list
* @param utilizationBound the utilization bound
* @param time the time
* @return the array list< hash map< string, object>>
*/
public abstract List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList);
/**
* Releases the host used by a VM.
*
* @param vm the vm
* @pre $none
* @post $none
*/
public abstract void deallocateHostForVm(Vm vm);
/**
* Get the host that is executing the given VM belonging to the given user.
*
* @param vm the vm
* @return the Host with the given vmID and userID; $null if not found
* @pre $none
* @post $none
*/
public abstract Host getHost(Vm vm);
/**
* Get the host that is executing the given VM belonging to the given user.
*
* @param vmId the vm id
* @param userId the user id
* @return the Host with the given vmID and userID; $null if not found
* @pre $none
* @post $none
*/
public abstract Host getHost(int vmId, int userId);
/**
* Sets the host list.
*
* @param hostList the new host list
*/
protected void setHostList(List<? extends Host> hostList) {
this.hostList = hostList;
}
/**
* Gets the host list.
*
* @return the host list
*/
@SuppressWarnings("unchecked")
public <T extends Host> List<T> getHostList() {
return (List<T>) hostList;
}
}

View File

@@ -0,0 +1,240 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* VmAllocationPolicySimple is an VmAllocationPolicy that chooses, as the host for a VM, the host
* with less PEs in use.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class VmAllocationPolicySimple extends VmAllocationPolicy {
/** The vm table. */
private Map<String, Host> vmTable;
/** The used pes. */
private Map<String, Integer> usedPes;
/** The free pes. */
private List<Integer> freePes;
/**
* Creates the new VmAllocationPolicySimple object.
*
* @param list the list
* @pre $none
* @post $none
*/
public VmAllocationPolicySimple(List<? extends Host> list) {
super(list);
setFreePes(new ArrayList<Integer>());
for (Host host : getHostList()) {
getFreePes().add(host.getNumberOfPes());
}
setVmTable(new HashMap<String, Host>());
setUsedPes(new HashMap<String, Integer>());
}
/**
* Allocates a host for a given VM.
*
* @param vm VM specification
* @return $true if the host could be allocated; $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean allocateHostForVm(Vm vm) {
int requiredPes = vm.getNumberOfPes();
boolean result = false;
int tries = 0;
List<Integer> freePesTmp = new ArrayList<Integer>();
for (Integer freePes : getFreePes()) {
freePesTmp.add(freePes);
}
if (!getVmTable().containsKey(vm.getUid())) { // if this vm was not created
do {// we still trying until we find a host or until we try all of them
int moreFree = Integer.MIN_VALUE;
int idx = -1;
// we want the host with less pes in use
for (int i = 0; i < freePesTmp.size(); i++) {
if (freePesTmp.get(i) > moreFree) {
moreFree = freePesTmp.get(i);
idx = i;
}
}
Host host = getHostList().get(idx);
result = host.vmCreate(vm);
if (result) { // if vm were succesfully created in the host
getVmTable().put(vm.getUid(), host);
getUsedPes().put(vm.getUid(), requiredPes);
getFreePes().set(idx, getFreePes().get(idx) - requiredPes);
result = true;
break;
} else {
freePesTmp.set(idx, Integer.MIN_VALUE);
}
tries++;
} while (!result && tries < getFreePes().size());
}
return result;
}
/**
* Releases the host used by a VM.
*
* @param vm the vm
* @pre $none
* @post none
*/
@Override
public void deallocateHostForVm(Vm vm) {
Host host = getVmTable().remove(vm.getUid());
int idx = getHostList().indexOf(host);
int pes = getUsedPes().remove(vm.getUid());
if (host != null) {
host.vmDestroy(vm);
getFreePes().set(idx, getFreePes().get(idx) + pes);
}
}
/**
* Gets the host that is executing the given VM belonging to the given user.
*
* @param vm the vm
* @return the Host with the given vmID and userID; $null if not found
* @pre $none
* @post $none
*/
@Override
public Host getHost(Vm vm) {
return getVmTable().get(vm.getUid());
}
/**
* Gets the host that is executing the given VM belonging to the given user.
*
* @param vmId the vm id
* @param userId the user id
* @return the Host with the given vmID and userID; $null if not found
* @pre $none
* @post $none
*/
@Override
public Host getHost(int vmId, int userId) {
return getVmTable().get(Vm.getUid(userId, vmId));
}
/**
* Gets the vm table.
*
* @return the vm table
*/
public Map<String, Host> getVmTable() {
return vmTable;
}
/**
* Sets the vm table.
*
* @param vmTable the vm table
*/
protected void setVmTable(Map<String, Host> vmTable) {
this.vmTable = vmTable;
}
/**
* Gets the used pes.
*
* @return the used pes
*/
protected Map<String, Integer> getUsedPes() {
return usedPes;
}
/**
* Sets the used pes.
*
* @param usedPes the used pes
*/
protected void setUsedPes(Map<String, Integer> usedPes) {
this.usedPes = usedPes;
}
/**
* Gets the free pes.
*
* @return the free pes
*/
protected List<Integer> getFreePes() {
return freePes;
}
/**
* Sets the free pes.
*
* @param freePes the new free pes
*/
protected void setFreePes(List<Integer> freePes) {
this.freePes = freePes;
}
/*
* (non-Javadoc)
* @see cloudsim.VmAllocationPolicy#optimizeAllocation(double, cloudsim.VmList, double)
*/
@Override
public List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#allocateHostForVm(org.cloudbus.cloudsim.Vm,
* org.cloudbus.cloudsim.Host)
*/
@Override
public boolean allocateHostForVm(Vm vm, Host host) {
if (host.vmCreate(vm)) { // if vm has been succesfully created in the host
getVmTable().put(vm.getUid(), host);
int requiredPes = vm.getNumberOfPes();
int idx = getHostList().indexOf(host);
getUsedPes().put(vm.getUid(), requiredPes);
getFreePes().set(idx, getFreePes().get(idx) - requiredPes);
Log.formatLine(
"%.2f: VM #" + vm.getId() + " has been allocated to the host #" + host.getId(),
CloudSim.clock());
return true;
}
return false;
}
}

View File

@@ -0,0 +1,280 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.lists.PeList;
/**
* VmScheduler is an abstract class that represents the policy used by a VMM to share processing
* power among VMs running in a host.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public abstract class VmScheduler {
/** The peList. */
private List<? extends Pe> peList;
/** The map of VMs to PEs. */
private Map<String, List<Pe>> peMap;
/** The MIPS that are currently allocated to the VMs. */
private Map<String, List<Double>> mipsMap;
/** The total available mips. */
private double availableMips;
/** The VMs migrating in. */
private List<String> vmsMigratingIn;
/** The VMs migrating out. */
private List<String> vmsMigratingOut;
/**
* Creates a new HostAllocationPolicy.
*
* @param pelist the pelist
* @pre peList != $null
* @post $none
*/
public VmScheduler(List<? extends Pe> pelist) {
setPeList(pelist);
setPeMap(new HashMap<String, List<Pe>>());
setMipsMap(new HashMap<String, List<Double>>());
setAvailableMips(PeList.getTotalMips(getPeList()));
setVmsMigratingIn(new ArrayList<String>());
setVmsMigratingOut(new ArrayList<String>());
}
/**
* Allocates PEs for a VM.
*
* @param vm the vm
* @param mipsShare the mips share
* @return $true if this policy allows a new VM in the host, $false otherwise
* @pre $none
* @post $none
*/
public abstract boolean allocatePesForVm(Vm vm, List<Double> mipsShare);
/**
* Releases PEs allocated to a VM.
*
* @param vm the vm
* @pre $none
* @post $none
*/
public abstract void deallocatePesForVm(Vm vm);
/**
* Releases PEs allocated to all the VMs.
*
* @pre $none
* @post $none
*/
public void deallocatePesForAllVms() {
getMipsMap().clear();
setAvailableMips(PeList.getTotalMips(getPeList()));
for (Pe pe : getPeList()) {
pe.getPeProvisioner().deallocateMipsForAllVms();
}
}
/**
* Gets the pes allocated for vm.
*
* @param vm the vm
* @return the pes allocated for vm
*/
public List<Pe> getPesAllocatedForVM(Vm vm) {
return getPeMap().get(vm.getUid());
}
/**
* Returns the MIPS share of each Pe that is allocated to a given VM.
*
* @param vm the vm
* @return an array containing the amount of MIPS of each pe that is available to the VM
* @pre $none
* @post $none
*/
public List<Double> getAllocatedMipsForVm(Vm vm) {
return getMipsMap().get(vm.getUid());
}
/**
* Gets the total allocated MIPS for a VM over all the PEs.
*
* @param vm the vm
* @return the allocated mips for vm
*/
public double getTotalAllocatedMipsForVm(Vm vm) {
double allocated = 0;
List<Double> mipsMap = getAllocatedMipsForVm(vm);
if (mipsMap != null) {
for (double mips : mipsMap) {
allocated += mips;
}
}
return allocated;
}
/**
* Returns maximum available MIPS among all the PEs.
*
* @return max mips
*/
public double getMaxAvailableMips() {
if (getPeList() == null) {
Log.printLine("Pe list is empty");
return 0;
}
double max = 0.0;
for (Pe pe : getPeList()) {
double tmp = pe.getPeProvisioner().getAvailableMips();
if (tmp > max) {
max = tmp;
}
}
return max;
}
/**
* Returns PE capacity in MIPS.
*
* @return mips
*/
public double getPeCapacity() {
if (getPeList() == null) {
Log.printLine("Pe list is empty");
return 0;
}
return getPeList().get(0).getMips();
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Pe> List<T> getPeList() {
return (List<T>) peList;
}
/**
* Sets the vm list.
*
* @param <T> the generic type
* @param peList the pe list
*/
protected <T extends Pe> void setPeList(List<T> peList) {
this.peList = peList;
}
/**
* Gets the mips map.
*
* @return the mips map
*/
protected Map<String, List<Double>> getMipsMap() {
return mipsMap;
}
/**
* Sets the mips map.
*
* @param mipsMap the mips map
*/
protected void setMipsMap(Map<String, List<Double>> mipsMap) {
this.mipsMap = mipsMap;
}
/**
* Gets the free mips.
*
* @return the free mips
*/
public double getAvailableMips() {
return availableMips;
}
/**
* Sets the free mips.
*
* @param availableMips the new free mips
*/
protected void setAvailableMips(double availableMips) {
this.availableMips = availableMips;
}
/**
* Gets the vms in migration.
*
* @return the vms in migration
*/
public List<String> getVmsMigratingOut() {
return vmsMigratingOut;
}
/**
* Sets the vms in migration.
*
* @param vmsInMigration the new vms migrating out
*/
protected void setVmsMigratingOut(List<String> vmsInMigration) {
vmsMigratingOut = vmsInMigration;
}
/**
* Gets the vms migrating in.
*
* @return the vms migrating in
*/
public List<String> getVmsMigratingIn() {
return vmsMigratingIn;
}
/**
* Sets the vms migrating in.
*
* @param vmsMigratingIn the new vms migrating in
*/
protected void setVmsMigratingIn(List<String> vmsMigratingIn) {
this.vmsMigratingIn = vmsMigratingIn;
}
/**
* Gets the pe map.
*
* @return the pe map
*/
public Map<String, List<Pe>> getPeMap() {
return peMap;
}
/**
* Sets the pe map.
*
* @param peMap the pe map
*/
protected void setPeMap(Map<String, List<Pe>> peMap) {
this.peMap = peMap;
}
}

View File

@@ -0,0 +1,138 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* VmSchedulerSpaceShared is a VMM allocation policy that allocates one or more Pe to a VM, and
* doesn't allow sharing of PEs. If there is no free PEs to the VM, allocation fails. Free PEs are
* not allocated to VMs
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class VmSchedulerSpaceShared extends VmScheduler {
/** Map containing VM ID and a vector of PEs allocated to this VM. */
private Map<String, List<Pe>> peAllocationMap;
/** The free pes vector. */
private List<Pe> freePes;
/**
* Instantiates a new vm scheduler space shared.
*
* @param pelist the pelist
*/
public VmSchedulerSpaceShared(List<? extends Pe> pelist) {
super(pelist);
setPeAllocationMap(new HashMap<String, List<Pe>>());
setFreePes(new ArrayList<Pe>());
getFreePes().addAll(pelist);
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmScheduler#allocatePesForVm(org.cloudbus.cloudsim.Vm,
* java.util.List)
*/
@Override
public boolean allocatePesForVm(Vm vm, List<Double> mipsShare) {
// if there is no enough free PEs, fails
if (getFreePes().size() < mipsShare.size()) {
return false;
}
List<Pe> selectedPes = new ArrayList<Pe>();
Iterator<Pe> peIterator = getFreePes().iterator();
Pe pe = peIterator.next();
double totalMips = 0;
for (Double mips : mipsShare) {
if (mips <= pe.getMips()) {
selectedPes.add(pe);
if (!peIterator.hasNext()) {
break;
}
pe = peIterator.next();
totalMips += mips;
}
}
if (mipsShare.size() > selectedPes.size()) {
return false;
}
getFreePes().removeAll(selectedPes);
getPeAllocationMap().put(vm.getUid(), selectedPes);
getMipsMap().put(vm.getUid(), mipsShare);
setAvailableMips(getAvailableMips() - totalMips);
return true;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmScheduler#deallocatePesForVm(org.cloudbus.cloudsim.Vm)
*/
@Override
public void deallocatePesForVm(Vm vm) {
getFreePes().addAll(getPeAllocationMap().get(vm.getUid()));
getPeAllocationMap().remove(vm.getUid());
double totalMips = 0;
for (double mips : getMipsMap().get(vm.getUid())) {
totalMips += mips;
}
setAvailableMips(getAvailableMips() + totalMips);
getMipsMap().remove(vm.getUid());
}
/**
* Sets the pe allocation map.
*
* @param peAllocationMap the pe allocation map
*/
protected void setPeAllocationMap(Map<String, List<Pe>> peAllocationMap) {
this.peAllocationMap = peAllocationMap;
}
/**
* Gets the pe allocation map.
*
* @return the pe allocation map
*/
protected Map<String, List<Pe>> getPeAllocationMap() {
return peAllocationMap;
}
/**
* Sets the free pes vector.
*
* @param freePes the new free pes vector
*/
protected void setFreePes(List<Pe> freePes) {
this.freePes = freePes;
}
/**
* Gets the free pes vector.
*
* @return the free pes vector
*/
protected List<Pe> getFreePes() {
return freePes;
}
}

View File

@@ -0,0 +1,245 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.lists.PeList;
import org.cloudbus.cloudsim.provisioners.PeProvisioner;
/**
* VmSchedulerTimeShared is a VMM allocation policy that allocates one or more Pe to a VM, and
* allows sharing of PEs by multiple VMs. This class also implements 10% performance degration due
* to VM migration. This scheduler does not support over-subscription.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class VmSchedulerTimeShared extends VmScheduler {
/** The mips map requested. */
private Map<String, List<Double>> mipsMapRequested;
/** The pes in use. */
private int pesInUse;
/**
* Instantiates a new vm scheduler time shared.
*
* @param pelist the pelist
*/
public VmSchedulerTimeShared(List<? extends Pe> pelist) {
super(pelist);
setMipsMapRequested(new HashMap<String, List<Double>>());
}
/*
* (non-Javadoc)
* @see cloudsim.VmScheduler#allocatePesForVm(cloudsim.Vm, java.util.List)
*/
@Override
public boolean allocatePesForVm(Vm vm, List<Double> mipsShareRequested) {
/**
* TODO: add the same to RAM and BW provisioners
*/
if (vm.isInMigration()) {
if (!getVmsMigratingIn().contains(vm.getUid()) && !getVmsMigratingOut().contains(vm.getUid())) {
getVmsMigratingOut().add(vm.getUid());
}
} else {
if (getVmsMigratingOut().contains(vm.getUid())) {
getVmsMigratingOut().remove(vm.getUid());
}
}
boolean result = allocatePesForVm(vm.getUid(), mipsShareRequested);
updatePeProvisioning();
return result;
}
/**
* Allocate pes for vm.
*
* @param vmUid the vm uid
* @param mipsShareRequested the mips share requested
* @return true, if successful
*/
protected boolean allocatePesForVm(String vmUid, List<Double> mipsShareRequested) {
double totalRequestedMips = 0;
double peMips = getPeCapacity();
for (Double mips : mipsShareRequested) {
// each virtual PE of a VM must require not more than the capacity of a physical PE
if (mips > peMips) {
return false;
}
totalRequestedMips += mips;
}
// This scheduler does not allow over-subscription
if (getAvailableMips() < totalRequestedMips) {
return false;
}
getMipsMapRequested().put(vmUid, mipsShareRequested);
setPesInUse(getPesInUse() + mipsShareRequested.size());
if (getVmsMigratingIn().contains(vmUid)) {
// the destination host only experience 10% of the migrating VM's MIPS
totalRequestedMips *= 0.1;
}
List<Double> mipsShareAllocated = new ArrayList<Double>();
for (Double mipsRequested : mipsShareRequested) {
if (getVmsMigratingOut().contains(vmUid)) {
// performance degradation due to migration = 10% MIPS
mipsRequested *= 0.9;
} else if (getVmsMigratingIn().contains(vmUid)) {
// the destination host only experience 10% of the migrating VM's MIPS
mipsRequested *= 0.1;
}
mipsShareAllocated.add(mipsRequested);
}
getMipsMap().put(vmUid, mipsShareAllocated);
setAvailableMips(getAvailableMips() - totalRequestedMips);
return true;
}
/**
* Update allocation of VMs on PEs.
*/
protected void updatePeProvisioning() {
getPeMap().clear();
for (Pe pe : getPeList()) {
pe.getPeProvisioner().deallocateMipsForAllVms();
}
Iterator<Pe> peIterator = getPeList().iterator();
Pe pe = peIterator.next();
PeProvisioner peProvisioner = pe.getPeProvisioner();
double availableMips = peProvisioner.getAvailableMips();
for (Map.Entry<String, List<Double>> entry : getMipsMap().entrySet()) {
String vmUid = entry.getKey();
getPeMap().put(vmUid, new LinkedList<Pe>());
for (double mips : entry.getValue()) {
while (mips >= 0.1) {
if (availableMips >= mips) {
peProvisioner.allocateMipsForVm(vmUid, mips);
getPeMap().get(vmUid).add(pe);
availableMips -= mips;
break;
} else {
peProvisioner.allocateMipsForVm(vmUid, availableMips);
getPeMap().get(vmUid).add(pe);
mips -= availableMips;
if (mips <= 0.1) {
break;
}
if (!peIterator.hasNext()) {
Log.printLine("There is no enough MIPS (" + mips + ") to accommodate VM " + vmUid);
}
pe = peIterator.next();
peProvisioner = pe.getPeProvisioner();
availableMips = peProvisioner.getAvailableMips();
}
}
}
}
}
/*
* (non-Javadoc)
* @see cloudsim.VmScheduler#deallocatePesForVm(cloudsim.Vm)
*/
@Override
public void deallocatePesForVm(Vm vm) {
getMipsMapRequested().remove(vm.getUid());
setPesInUse(0);
getMipsMap().clear();
setAvailableMips(PeList.getTotalMips(getPeList()));
for (Pe pe : getPeList()) {
pe.getPeProvisioner().deallocateMipsForVm(vm);
}
for (Map.Entry<String, List<Double>> entry : getMipsMapRequested().entrySet()) {
allocatePesForVm(entry.getKey(), entry.getValue());
}
updatePeProvisioning();
}
/**
* Releases PEs allocated to all the VMs.
*
* @pre $none
* @post $none
*/
@Override
public void deallocatePesForAllVms() {
super.deallocatePesForAllVms();
getMipsMapRequested().clear();
setPesInUse(0);
}
/**
* Returns maximum available MIPS among all the PEs. For the time shared policy it is just all
* the avaiable MIPS.
*
* @return max mips
*/
@Override
public double getMaxAvailableMips() {
return getAvailableMips();
}
/**
* Sets the pes in use.
*
* @param pesInUse the new pes in use
*/
protected void setPesInUse(int pesInUse) {
this.pesInUse = pesInUse;
}
/**
* Gets the pes in use.
*
* @return the pes in use
*/
protected int getPesInUse() {
return pesInUse;
}
/**
* Gets the mips map requested.
*
* @return the mips map requested
*/
protected Map<String, List<Double>> getMipsMapRequested() {
return mipsMapRequested;
}
/**
* Sets the mips map requested.
*
* @param mipsMapRequested the mips map requested
*/
protected void setMipsMapRequested(Map<String, List<Double>> mipsMapRequested) {
this.mipsMapRequested = mipsMapRequested;
}
}

View File

@@ -0,0 +1,176 @@
/*
* Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and
* Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.cloudbus.cloudsim.lists.PeList;
/**
* This is a Time-Shared VM Scheduler, which allows over-subscription. In other words, the scheduler
* still allows the allocation of VMs that require more CPU capacity that is available.
* Oversubscription results in performance degradation.
*
* @author Anton Beloglazov
* @author Rodrigo N. Calheiros
* @since CloudSim Toolkit 3.0
*/
public class VmSchedulerTimeSharedOverSubscription extends VmSchedulerTimeShared {
/**
* Instantiates a new vm scheduler time shared over subscription.
*
* @param pelist the pelist
*/
public VmSchedulerTimeSharedOverSubscription(List<? extends Pe> pelist) {
super(pelist);
}
/**
* Allocate pes for vm. The policy allows over-subscription. In other words, the policy still
* allows the allocation of VMs that require more CPU capacity that is available.
* Oversubscription results in performance degradation. Each virtual PE cannot be allocated more
* CPU capacity than MIPS of a single PE.
*
* @param vmUid the vm uid
* @param mipsShareRequested the mips share requested
* @return true, if successful
*/
@Override
protected boolean allocatePesForVm(String vmUid, List<Double> mipsShareRequested) {
double totalRequestedMips = 0;
// if the requested mips is bigger than the capacity of a single PE, we cap
// the request to the PE's capacity
List<Double> mipsShareRequestedCapped = new ArrayList<Double>();
double peMips = getPeCapacity();
for (Double mips : mipsShareRequested) {
if (mips > peMips) {
mipsShareRequestedCapped.add(peMips);
totalRequestedMips += peMips;
} else {
mipsShareRequestedCapped.add(mips);
totalRequestedMips += mips;
}
}
getMipsMapRequested().put(vmUid, mipsShareRequested);
setPesInUse(getPesInUse() + mipsShareRequested.size());
if (getVmsMigratingIn().contains(vmUid)) {
// the destination host only experience 10% of the migrating VM's MIPS
totalRequestedMips *= 0.1;
}
if (getAvailableMips() >= totalRequestedMips) {
List<Double> mipsShareAllocated = new ArrayList<Double>();
for (Double mipsRequested : mipsShareRequestedCapped) {
if (getVmsMigratingOut().contains(vmUid)) {
// performance degradation due to migration = 10% MIPS
mipsRequested *= 0.9;
} else if (getVmsMigratingIn().contains(vmUid)) {
// the destination host only experience 10% of the migrating VM's MIPS
mipsRequested *= 0.1;
}
mipsShareAllocated.add(mipsRequested);
}
//System.out.println("Setting MIPS of "+vmUid+" to "+mipsShareAllocated);
getMipsMap().put(vmUid, mipsShareAllocated);
setAvailableMips(getAvailableMips() - totalRequestedMips);
} else {
redistributeMipsDueToOverSubscription();
}
/*for(String uid : getMipsMap().keySet()){
System.out.println(uid+"\t--->\t"+getMipsMap().get(uid));
}*/
return true;
}
/**
* This method recalculates distribution of MIPs among VMs considering eventual shortage of MIPS
* compared to the amount requested by VMs.
*/
protected void redistributeMipsDueToOverSubscription() {
// First, we calculate the scaling factor - the MIPS allocation for all VMs will be scaled
// proportionally
double totalRequiredMipsByAllVms = 0;
Map<String, List<Double>> mipsMapCapped = new HashMap<String, List<Double>>();
for (Entry<String, List<Double>> entry : getMipsMapRequested().entrySet()) {
double requiredMipsByThisVm = 0.0;
String vmId = entry.getKey();
List<Double> mipsShareRequested = entry.getValue();
List<Double> mipsShareRequestedCapped = new ArrayList<Double>();
double peMips = getPeCapacity();
for (Double mips : mipsShareRequested) {
if (mips > peMips) {
mipsShareRequestedCapped.add(peMips);
requiredMipsByThisVm += peMips;
} else {
mipsShareRequestedCapped.add(mips);
requiredMipsByThisVm += mips;
}
}
mipsMapCapped.put(vmId, mipsShareRequestedCapped);
if (getVmsMigratingIn().contains(entry.getKey())) {
// the destination host only experience 10% of the migrating VM's MIPS
requiredMipsByThisVm *= 0.1;
}
totalRequiredMipsByAllVms += requiredMipsByThisVm;
}
double totalAvailableMips = PeList.getTotalMips(getPeList());
double scalingFactor = totalAvailableMips / totalRequiredMipsByAllVms;
// Clear the old MIPS allocation
getMipsMap().clear();
// Update the actual MIPS allocated to the VMs
for (Entry<String, List<Double>> entry : mipsMapCapped.entrySet()) {
String vmUid = entry.getKey();
List<Double> requestedMips = entry.getValue();
List<Double> updatedMipsAllocation = new ArrayList<Double>();
for (Double mips : requestedMips) {
if (getVmsMigratingOut().contains(vmUid)) {
// the original amount is scaled
mips *= scalingFactor;
// performance degradation due to migration = 10% MIPS
mips *= 0.9;
} else if (getVmsMigratingIn().contains(vmUid)) {
// the destination host only experiences 10% of the migrating VM's MIPS
mips *= 0.1;
// the final 10% of the requested MIPS are scaled
mips *= scalingFactor;
} else {
mips *= scalingFactor;
}
updatedMipsAllocation.add(Math.floor(mips));
}
// add in the new map
//System.out.println("Setting MIPS of "+vmUid+" to "+updatedMipsAllocation);
getMipsMap().put(vmUid, updatedMipsAllocation);
}
// As the host is oversubscribed, there no more available MIPS
setAvailableMips(0);
}
}

View File

@@ -0,0 +1,118 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2011, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim;
/**
* The Class VmMipsAllocationHistoryEntry.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.1.2
*/
public class VmStateHistoryEntry {
/** The time. */
private double time;
/** The allocated mips. */
private double allocatedMips;
/** The requested mips. */
private double requestedMips;
/** The is in migration. */
private boolean isInMigration;
/**
* Instantiates a new vm mips allocation history entry.
*
* @param time the time
* @param allocatedMips the allocated mips
* @param requestedMips the requested mips
* @param isInMigration the is in migration
*/
public VmStateHistoryEntry(double time, double allocatedMips, double requestedMips, boolean isInMigration) {
setTime(time);
setAllocatedMips(allocatedMips);
setRequestedMips(requestedMips);
setInMigration(isInMigration);
}
/**
* Sets the time.
*
* @param time the new time
*/
protected void setTime(double time) {
this.time = time;
}
/**
* Gets the time.
*
* @return the time
*/
public double getTime() {
return time;
}
/**
* Sets the allocated mips.
*
* @param allocatedMips the new allocated mips
*/
protected void setAllocatedMips(double allocatedMips) {
this.allocatedMips = allocatedMips;
}
/**
* Gets the allocated mips.
*
* @return the allocated mips
*/
public double getAllocatedMips() {
return allocatedMips;
}
/**
* Sets the requested mips.
*
* @param requestedMips the new requested mips
*/
protected void setRequestedMips(double requestedMips) {
this.requestedMips = requestedMips;
}
/**
* Gets the requested mips.
*
* @return the requested mips
*/
public double getRequestedMips() {
return requestedMips;
}
/**
* Sets the in migration.
*
* @param isInMigration the new in migration
*/
protected void setInMigration(boolean isInMigration) {
this.isInMigration = isInMigration;
}
/**
* Checks if is in migration.
*
* @return true, if is in migration
*/
public boolean isInMigration() {
return isInMigration;
}
}

View File

@@ -0,0 +1,332 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Log;
/**
* A Cloud Information Service (CIS) is an entity that provides cloud resource registration,
* indexing and discovery services. The Cloud hostList tell their readiness to process Cloudlets by
* registering themselves with this entity. Other entities such as the resource broker can contact
* this class for resource discovery service, which returns a list of registered resource IDs. In
* summary, it acts like a yellow page service. This class will be created by CloudSim upon
* initialisation of the simulation. Hence, do not need to worry about creating an object of this
* class.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @since CloudSim Toolkit 1.0
*/
public class CloudInformationService extends SimEntity {
/** For all types of hostList. */
private final List<Integer> resList;
/** Only for AR hostList. */
private final List<Integer> arList;
/** List of all regional GIS. */
private final List<Integer> gisList;
/**
* Allocates a new CloudInformationService object.
*
* @param name the name to be associated with this entity (as required by SimEntity class)
* @throws Exception This happens when creating this entity before initialising CloudSim package
* or this entity name is <tt>null</tt> or empty
* @pre name != null
* @post $none
*/
public CloudInformationService(String name) throws Exception {
super(name);
resList = new LinkedList<Integer>();
arList = new LinkedList<Integer>();
gisList = new LinkedList<Integer>();
}
/**
* Starts the CloudInformationService entity.
*/
@Override
public void startEntity() {
}
/**
* Processes events scheduled for this entity.
*
* @param ev the event to be handled.
* @see SimEntity#processEvent(SimEvent)
*/
@Override
public void processEvent(SimEvent ev) {
int id = -1; // requester id
switch (ev.getTag()) {
// storing regional GIS id
case CloudSimTags.REGISTER_REGIONAL_GIS:
gisList.add((Integer) ev.getData());
break;
// request for all regional GIS list
case CloudSimTags.REQUEST_REGIONAL_GIS:
// Get ID of an entity that send this event
id = ((Integer) ev.getData()).intValue();
// Send the regional GIS list back to sender
super.send(id, 0L, ev.getTag(), gisList);
break;
// A resource is requesting to register.
case CloudSimTags.REGISTER_RESOURCE:
resList.add((Integer) ev.getData());
break;
// A resource that can support Advance Reservation
case CloudSimTags.REGISTER_RESOURCE_AR:
resList.add((Integer) ev.getData());
arList.add((Integer) ev.getData());
break;
// A Broker is requesting for a list of all hostList.
case CloudSimTags.RESOURCE_LIST:
// Get ID of an entity that send this event
id = ((Integer) ev.getData()).intValue();
// Send the resource list back to the sender
super.send(id, 0L, ev.getTag(), resList);
break;
// A Broker is requesting for a list of all hostList.
case CloudSimTags.RESOURCE_AR_LIST:
// Get ID of an entity that send this event
id = ((Integer) ev.getData()).intValue();
// Send the resource AR list back to the sender
super.send(id, 0L, ev.getTag(), arList);
break;
default:
processOtherEvent(ev);
break;
}
}
/**
* Shutdowns the CloudInformationService.
*/
@Override
public void shutdownEntity() {
notifyAllEntity();
}
/**
* Gets the list of all CloudResource IDs, including hostList that support Advance Reservation.
*
* @return LinkedList containing resource IDs. Each ID is represented by an Integer object.
* @pre $none
* @post $none
*/
public List<Integer> getList() {
return resList;
}
/**
* Gets the list of CloudResource IDs that <b>only</b> support Advanced Reservation.
*
* @return LinkedList containing resource IDs. Each ID is represented by an Integer object.
* @pre $none
* @post $none
*/
public List<Integer> getAdvReservList() {
return arList;
}
/**
* Checks whether a given resource ID supports Advanced Reservations or not.
*
* @param id a resource ID
* @return <tt>true</tt> if this resource supports Advanced Reservations, <tt>false</tt>
* otherwise
* @pre id != null
* @post $none
*/
public boolean resourceSupportAR(Integer id) {
if (id == null) {
return false;
}
return resourceSupportAR(id.intValue());
}
/**
* Checks whether a given resource ID supports Advanced Reservations or not.
*
* @param id a resource ID
* @return <tt>true</tt> if this resource supports Advanced Reservations, <tt>false</tt>
* otherwise
* @pre id >= 0
* @post $none
*/
public boolean resourceSupportAR(int id) {
boolean flag = false;
if (id < 0) {
flag = false;
} else {
flag = checkResource(arList, id);
}
return flag;
}
/**
* Checks whether the given CloudResource ID exists or not.
*
* @param id a CloudResource id
* @return <tt>true</tt> if the given ID exists, <tt>false</tt> otherwise
* @pre id >= 0
* @post $none
*/
public boolean resourceExist(int id) {
boolean flag = false;
if (id < 0) {
flag = false;
} else {
flag = checkResource(resList, id);
}
return flag;
}
/**
* Checks whether the given CloudResource ID exists or not.
*
* @param id a CloudResource id
* @return <tt>true</tt> if the given ID exists, <tt>false</tt> otherwise
* @pre id != null
* @post $none
*/
public boolean resourceExist(Integer id) {
if (id == null) {
return false;
}
return resourceExist(id.intValue());
}
// //////////////////////// PROTECTED METHODS ////////////////////////////
/**
* This method needs to override by a child class for processing other events. These events are
* based on tags that are not mentioned in {@link #body()} method.
*
* @param ev a Sim_event object
* @pre ev != null
* @post $none
*/
protected void processOtherEvent(SimEvent ev) {
if (ev == null) {
Log.printLine("CloudInformationService.processOtherEvent(): "
+ "Unable to handle a request since the event is null.");
return;
}
Log.printLine("CloudInformationSevice.processOtherEvent(): " + "Unable to handle a request from "
+ CloudSim.getEntityName(ev.getSource()) + " with event tag = " + ev.getTag());
}
/**
* Notifies the registered entities about the end of simulation. This method should be
* overridden by the child class
*/
protected void processEndSimulation() {
// this should be overridden by the child class
}
// ////////////////// End of PROTECTED METHODS ///////////////////////////
/**
* Checks for a list for a particular resource id.
*
* @param list list of hostList
* @param id a resource ID
* @return true if a resource is in the list, otherwise false
* @pre list != null
* @pre id > 0
* @post $none
*/
private boolean checkResource(Collection<Integer> list, int id) {
boolean flag = false;
if (list == null || id < 0) {
return flag;
}
Integer obj = null;
Iterator<Integer> it = list.iterator();
// a loop to find the match the resource id in a list
while (it.hasNext()) {
obj = it.next();
if (obj.intValue() == id) {
flag = true;
break;
}
}
return flag;
}
/**
* Tells all registered entities the end of simulation.
*
* @pre $none
* @post $none
*/
private void notifyAllEntity() {
Log.printLine(super.getName() + ": Notify all CloudSim entities for shutting down.");
signalShutdown(resList);
signalShutdown(gisList);
// reset the values
resList.clear();
gisList.clear();
}
/**
* Sends a signal to all entity IDs mentioned in the given list.
*
* @param list List storing entity IDs
* @pre list != null
* @post $none
*/
protected void signalShutdown(Collection<Integer> list) {
// checks whether a list is empty or not
if (list == null) {
return;
}
Iterator<Integer> it = list.iterator();
Integer obj = null;
int id = 0; // entity ID
// Send END_OF_SIMULATION event to all entities in the list
while (it.hasNext()) {
obj = it.next();
id = obj.intValue();
super.send(id, 0L, CloudSimTags.END_OF_SIMULATION);
}
}
}

View File

@@ -0,0 +1,975 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.core.predicates.Predicate;
import org.cloudbus.cloudsim.core.predicates.PredicateAny;
import org.cloudbus.cloudsim.core.predicates.PredicateNone;
/**
* This class extends the CloudSimCore to enable network simulation in CloudSim. Also, it disables
* all the network models from CloudSim, to provide a simpler simulation of networking. In the
* network model used by CloudSim, a topology file written in BRITE format is used to describe the
* network. Later, nodes in such file are mapped to CloudSim entities. Delay calculated from the
* BRITE model are added to the messages send through CloudSim. Messages using the old model are
* converted to the apropriate methods with the correct parameters.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @since CloudSim Toolkit 1.0
*/
public class CloudSim {
/** The Constant CLOUDSIM_VERSION_STRING. */
private static final String CLOUDSIM_VERSION_STRING = "3.0";
/** The id of CIS entity. */
private static int cisId = -1;
/** The id of CloudSimShutdown entity. */
@SuppressWarnings("unused")
private static int shutdownId = -1;
/** The CIS object. */
private static CloudInformationService cis = null;
/** The Constant NOT_FOUND. */
private static final int NOT_FOUND = -1;
/** The trace flag. */
@SuppressWarnings("unused")
private static boolean traceFlag = false;
/** The calendar. */
private static Calendar calendar = null;
/** The termination time. */
private static double terminateAt = -1;
/** The minimal time between events. Events within shorter periods after the last event are discarded. */
private static double minTimeBetweenEvents = 0.1;
/**
* Initialises all the common attributes.
*
* @param _calendar the _calendar
* @param _traceFlag the _trace flag
* @param numUser number of users
* @throws Exception This happens when creating this entity before initialising CloudSim package
* or this entity name is <tt>null</tt> or empty
* @pre $none
* @post $none
*/
private static void initCommonVariable(Calendar _calendar, boolean _traceFlag, int numUser)
throws Exception {
initialize();
// NOTE: the order for the below 3 lines are important
traceFlag = _traceFlag;
// Set the current Wall clock time as the starting time of
// simulation
if (_calendar == null) {
calendar = Calendar.getInstance();
} else {
calendar = _calendar;
}
// creates a CloudSimShutdown object
CloudSimShutdown shutdown = new CloudSimShutdown("CloudSimShutdown", numUser);
shutdownId = shutdown.getId();
}
/**
* Initialises CloudSim parameters. This method should be called before creating any entities.
* <p>
* Inside this method, it will create the following CloudSim entities:
* <ul>
* <li>CloudInformationService.
* <li>CloudSimShutdown
* </ul>
* <p>
*
* @param numUser the number of User Entities created. This parameters indicates that
* {@link gridsim.CloudSimShutdown} first waits for all user entities's
* END_OF_SIMULATION signal before issuing terminate signal to other entities
* @param cal starting time for this simulation. If it is <tt>null</tt>, then the time will be
* taken from <tt>Calendar.getInstance()</tt>
* @param traceFlag <tt>true</tt> if CloudSim trace need to be written
* @see gridsim.CloudSimShutdown
* @see CloudInformationService.CloudInformationService
* @pre numUser >= 0
* @post $none
*/
public static void init(int numUser, Calendar cal, boolean traceFlag) {
try {
initCommonVariable(cal, traceFlag, numUser);
// create a GIS object
cis = new CloudInformationService("CloudInformationService");
// set all the above entity IDs
cisId = cis.getId();
} catch (IllegalArgumentException s) {
Log.printLine("CloudSim.init(): The simulation has been terminated due to an unexpected error");
Log.printLine(s.getMessage());
} catch (Exception e) {
Log.printLine("CloudSim.init(): The simulation has been terminated due to an unexpected error");
Log.printLine(e.getMessage());
}
}
/**
* Initialises CloudSim parameters. This method should be called before creating any entities.
* <p>
* Inside this method, it will create the following CloudSim entities:
* <ul>
* <li>CloudInformationService.
* <li>CloudSimShutdown
* </ul>
* <p>
*
* @param numUser the number of User Entities created. This parameters indicates that
* {@link gridsim.CloudSimShutdown} first waits for all user entities's
* END_OF_SIMULATION signal before issuing terminate signal to other entities
* @param cal starting time for this simulation. If it is <tt>null</tt>, then the time will be
* taken from <tt>Calendar.getInstance()</tt>
* @param traceFlag <tt>true</tt> if CloudSim trace need to be written
* @param periodBetweenEvents - the minimal period between events. Events within shorter periods
* after the last event are discarded.
* @see gridsim.CloudSimShutdown
* @see CloudInformationService.CloudInformationService
* @pre numUser >= 0
* @post $none
*/
public static void init(int numUser, Calendar cal, boolean traceFlag, double periodBetweenEvents) {
if (periodBetweenEvents <= 0) {
throw new IllegalArgumentException("The minimal time between events should be positive, but is:" + periodBetweenEvents);
}
init(numUser, cal, traceFlag);
minTimeBetweenEvents = periodBetweenEvents;
}
/**
* Starts the execution of CloudSim simulation. It waits for complete execution of all entities,
* i.e. until all entities threads reach non-RUNNABLE state or there are no more events in the
* future event queue.
* <p>
* <b>Note</b>: This method should be called after all the entities have been setup and added.
*
* @return the double
* @throws NullPointerException This happens when creating this entity before initialising
* CloudSim package or this entity name is <tt>null</tt> or empty.
* @see gridsim.CloudSim#init(int, Calendar, boolean)
* @pre $none
* @post $none
*/
public static double startSimulation() throws NullPointerException {
Log.printLine("Starting CloudSim version " + CLOUDSIM_VERSION_STRING);
try {
double clock = run();
// reset all static variables
cisId = -1;
shutdownId = -1;
cis = null;
calendar = null;
traceFlag = false;
return clock;
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new NullPointerException("CloudSim.startCloudSimulation() :"
+ " Error - you haven't initialized CloudSim.");
}
}
/**
* Stops Cloud Simulation (based on {@link Simulation#runStop()}). This should be only called if
* any of the user defined entities <b>explicitly</b> want to terminate simulation during
* execution.
*
* @throws NullPointerException This happens when creating this entity before initialising
* CloudSim package or this entity name is <tt>null</tt> or empty
* @see gridsim.CloudSim#init(int, Calendar, boolean)
* @see Simulation#runStop()
* @pre $none
* @post $none
*/
public static void stopSimulation() throws NullPointerException {
try {
runStop();
} catch (IllegalArgumentException e) {
throw new NullPointerException("CloudSim.stopCloudSimulation() : "
+ "Error - can't stop Cloud Simulation.");
}
}
/**
* This method is called if one wants to terminate the simulation.
*
* @return true, if successful; false otherwise.
*/
public static boolean terminateSimulation() {
running = false;
printMessage("Simulation: Reached termination time.");
return true;
}
/**
* This method is called if one wants to terminate the simulation at a given time.
*
* @param time the time at which the simulation has to be terminated
* @return true, if successful otherwise.
*/
public static boolean terminateSimulation(double time) {
if (time <= clock) {
return false;
} else {
terminateAt = time;
}
return true;
}
/**
* Returns the minimum time between events. Events within shorter periods after the last event are discarded.
* @return the minimum time between events.
*/
public static double getMinTimeBetweenEvents() {
return minTimeBetweenEvents;
}
/**
* Gets a new copy of initial simulation Calendar.
*
* @return a new copy of Calendar object or if CloudSim hasn't been initialized
* @see gridsim.CloudSim#init(int, Calendar, boolean, String[], String[], String)
* @see gridsim.CloudSim#init(int, Calendar, boolean)
* @pre $none
* @post $none
*/
public static Calendar getSimulationCalendar() {
// make a new copy
Calendar clone = calendar;
if (calendar != null) {
clone = (Calendar) calendar.clone();
}
return clone;
}
/**
* Gets the entity ID of <tt>CloudInformationService</tt>.
*
* @return the Entity ID or if it is not found
* @pre $none
* @post $result >= -1
*/
public static int getCloudInfoServiceEntityId() {
return cisId;
}
/**
* Sends a request to Cloud Information Service (GIS) entity to get the list of all Cloud
* hostList.
*
* @return A List containing CloudResource ID (as an Integer object) or if a CIS entity hasn't
* been created before
* @pre $none
* @post $none
*/
public static List<Integer> getCloudResourceList() {
if (cis == null) {
return null;
}
return cis.getList();
}
// ======== SIMULATION METHODS ===============//
/** The entities. */
private static List<SimEntity> entities;
/** The future event queue. */
protected static FutureQueue future;
/** The deferred event queue. */
protected static DeferredQueue deferred;
/** The simulation clock. */
private static double clock;
/** Flag for checking if the simulation is running. */
private static boolean running;
/** The entities by name. */
private static Map<String, SimEntity> entitiesByName;
// The predicates used in entity wait methods
/** The wait predicates. */
private static Map<Integer, Predicate> waitPredicates;
/** The paused. */
private static boolean paused = false;
/** The pause at. */
private static long pauseAt = -1;
/** The abrupt terminate. */
private static boolean abruptTerminate = false;
/**
* Initialise the simulation for stand alone simulations. This function should be called at the
* start of the simulation.
*/
protected static void initialize() {
Log.printLine("Initialising...");
entities = new ArrayList<SimEntity>();
entitiesByName = new LinkedHashMap<String, SimEntity>();
future = new FutureQueue();
deferred = new DeferredQueue();
waitPredicates = new HashMap<Integer, Predicate>();
clock = 0;
running = false;
}
// The two standard predicates
/** A standard predicate that matches any event. */
public final static PredicateAny SIM_ANY = new PredicateAny();
/** A standard predicate that does not match any events. */
public final static PredicateNone SIM_NONE = new PredicateNone();
// Public access methods
/**
* Get the current simulation time.
*
* @return the simulation time
*/
public static double clock() {
return clock;
}
/**
* Get the current number of entities in the simulation.
*
* @return The number of entities
*/
public static int getNumEntities() {
return entities.size();
}
/**
* Get the entity with a given id.
*
* @param id the entity's unique id number
* @return The entity, or if it could not be found
*/
public static SimEntity getEntity(int id) {
return entities.get(id);
}
/**
* Get the entity with a given name.
*
* @param name The entity's name
* @return The entity
*/
public static SimEntity getEntity(String name) {
return entitiesByName.get(name);
}
/**
* Get the id of an entity with a given name.
*
* @param name The entity's name
* @return The entity's unique id number
*/
public static int getEntityId(String name) {
SimEntity obj = entitiesByName.get(name);
if (obj == null) {
return NOT_FOUND;
} else {
return obj.getId();
}
}
/**
* Gets name of the entity given its entity ID.
*
* @param entityID the entity ID
* @return the Entity name or if this object does not have one
* @pre entityID > 0
* @post $none
*/
public static String getEntityName(int entityID) {
try {
return getEntity(entityID).getName();
} catch (IllegalArgumentException e) {
return null;
} catch (Exception e) {
return null;
}
}
/**
* Gets name of the entity given its entity ID.
*
* @param entityID the entity ID
* @return the Entity name or if this object does not have one
* @pre entityID > 0
* @post $none
*/
public static String getEntityName(Integer entityID) {
if (entityID != null) {
return getEntityName(entityID.intValue());
}
return null;
}
/**
* Returns a list of entities created for the simulation.
*
* @return the entity iterator
*/
public static List<SimEntity> getEntityList() {
// create a new list to prevent the user from changing
// the list of entities used by Simulation
List<SimEntity> list = new LinkedList<SimEntity>();
list.addAll(entities);
return list;
}
// Public update methods
/**
* Add a new entity to the simulation. This is present for compatibility with existing
* simulations since entities are automatically added to the simulation upon instantiation.
*
* @param e The new entity
*/
public static void addEntity(SimEntity e) {
SimEvent evt;
if (running) {
// Post an event to make this entity
evt = new SimEvent(SimEvent.CREATE, clock, 1, 0, 0, e);
future.addEvent(evt);
}
if (e.getId() == -1) { // Only add once!
int id = entities.size();
e.setId(id);
entities.add(e);
entitiesByName.put(e.getName(), e);
}
}
/**
* Internal method used to add a new entity to the simulation when the simulation is running. It
* should <b>not</b> be called from user simulations.
*
* @param e The new entity
*/
protected static void addEntityDynamically(SimEntity e) {
if (e == null) {
throw new IllegalArgumentException("Adding null entity.");
} else {
printMessage("Adding: " + e.getName());
}
e.startEntity();
}
/**
* Internal method used to run one tick of the simulation. This method should <b>not</b> be
* called in simulations.
*
* @return true, if successful otherwise
*/
public static boolean runClockTick() {
SimEntity ent;
boolean queue_empty;
int entities_size = entities.size();
for (int i = 0; i < entities_size; i++) {
ent = entities.get(i);
if (ent.getState() == SimEntity.RUNNABLE) {
ent.run();
}
}
// If there are more future events then deal with them
if (future.size() > 0) {
List<SimEvent> toRemove = new ArrayList<SimEvent>();
Iterator<SimEvent> fit = future.iterator();
queue_empty = false;
SimEvent first = fit.next();
processEvent(first);
future.remove(first);
fit = future.iterator();
// Check if next events are at same time...
boolean trymore = fit.hasNext();
while (trymore) {
SimEvent next = fit.next();
if (next.eventTime() == first.eventTime()) {
processEvent(next);
toRemove.add(next);
trymore = fit.hasNext();
} else {
trymore = false;
}
}
future.removeAll(toRemove);
} else {
queue_empty = true;
running = false;
printMessage("Simulation: No more future events");
}
return queue_empty;
}
/**
* Internal method used to stop the simulation. This method should <b>not</b> be used directly.
*/
public static void runStop() {
printMessage("Simulation completed.");
}
/**
* Used to hold an entity for some time.
*
* @param src the src
* @param delay the delay
*/
public static void hold(int src, long delay) {
SimEvent e = new SimEvent(SimEvent.HOLD_DONE, clock + delay, src);
future.addEvent(e);
entities.get(src).setState(SimEntity.HOLDING);
}
/**
* Used to pause an entity for some time.
*
* @param src the src
* @param delay the delay
*/
public static void pause(int src, double delay) {
SimEvent e = new SimEvent(SimEvent.HOLD_DONE, clock + delay, src);
future.addEvent(e);
entities.get(src).setState(SimEntity.HOLDING);
}
/**
* Used to send an event from one entity to another.
*
* @param src the src
* @param dest the dest
* @param delay the delay
* @param tag the tag
* @param data the data
*/
public static void send(int src, int dest, double delay, int tag, Object data) {
if (delay < 0) {
throw new IllegalArgumentException("Send delay can't be negative.");
}
SimEvent e = new SimEvent(SimEvent.SEND, clock + delay, src, dest, tag, data);
future.addEvent(e);
}
/**
* Used to send an event from one entity to another, with priority in the queue.
*
* @param src the src
* @param dest the dest
* @param delay the delay
* @param tag the tag
* @param data the data
*/
public static void sendFirst(int src, int dest, double delay, int tag, Object data) {
if (delay < 0) {
throw new IllegalArgumentException("Send delay can't be negative.");
}
SimEvent e = new SimEvent(SimEvent.SEND, clock + delay, src, dest, tag, data);
future.addEventFirst(e);
}
/**
* Sets an entity's state to be waiting. The predicate used to wait for an event is now passed
* to Sim_system. Only events that satisfy the predicate will be passed to the entity. This is
* done to avoid unnecessary context switches.
*
* @param src the src
* @param p the p
*/
public static void wait(int src, Predicate p) {
entities.get(src).setState(SimEntity.WAITING);
if (p != SIM_ANY) {
// If a predicate has been used store it in order to check it
waitPredicates.put(src, p);
}
}
/**
* Checks if events for a specific entity are present in the deferred event queue.
*
* @param d the d
* @param p the p
* @return the int
*/
public static int waiting(int d, Predicate p) {
int count = 0;
SimEvent event;
Iterator<SimEvent> iterator = deferred.iterator();
while (iterator.hasNext()) {
event = iterator.next();
if ((event.getDestination() == d) && (p.match(event))) {
count++;
}
}
return count;
}
/**
* Selects an event matching a predicate.
*
* @param src the src
* @param p the p
* @return the sim event
*/
public static SimEvent select(int src, Predicate p) {
SimEvent ev = null;
Iterator<SimEvent> iterator = deferred.iterator();
while (iterator.hasNext()) {
ev = iterator.next();
if (ev.getDestination() == src && p.match(ev)) {
iterator.remove();
break;
}
}
return ev;
}
/**
* Find first deferred event matching a predicate.
*
* @param src the src
* @param p the p
* @return the sim event
*/
public static SimEvent findFirstDeferred(int src, Predicate p) {
SimEvent ev = null;
Iterator<SimEvent> iterator = deferred.iterator();
while (iterator.hasNext()) {
ev = iterator.next();
if (ev.getDestination() == src && p.match(ev)) {
break;
}
}
return ev;
}
/**
* Removes an event from the event queue.
*
* @param src the src
* @param p the p
* @return the sim event
*/
public static SimEvent cancel(int src, Predicate p) {
SimEvent ev = null;
Iterator<SimEvent> iter = future.iterator();
while (iter.hasNext()) {
ev = iter.next();
if (ev.getSource() == src && p.match(ev)) {
iter.remove();
break;
}
}
return ev;
}
/**
* Removes all events that match a given predicate from the future event queue returns true if
* at least one event has been cancelled; false otherwise.
*
* @param src the src
* @param p the p
* @return true, if successful
*/
public static boolean cancelAll(int src, Predicate p) {
SimEvent ev = null;
int previousSize = future.size();
Iterator<SimEvent> iter = future.iterator();
while (iter.hasNext()) {
ev = iter.next();
if (ev.getSource() == src && p.match(ev)) {
iter.remove();
}
}
return previousSize < future.size();
}
//
// Private internal methods
//
/**
* Processes an event.
*
* @param e the e
*/
private static void processEvent(SimEvent e) {
int dest, src;
SimEntity dest_ent;
// Update the system's clock
if (e.eventTime() < clock) {
throw new IllegalArgumentException("Past event detected.");
}
clock = e.eventTime();
// Ok now process it
switch (e.getType()) {
case SimEvent.ENULL:
throw new IllegalArgumentException("Event has a null type.");
case SimEvent.CREATE:
SimEntity newe = (SimEntity) e.getData();
addEntityDynamically(newe);
break;
case SimEvent.SEND:
// Check for matching wait
dest = e.getDestination();
if (dest < 0) {
throw new IllegalArgumentException("Attempt to send to a null entity detected.");
} else {
int tag = e.getTag();
dest_ent = entities.get(dest);
if (dest_ent.getState() == SimEntity.WAITING) {
Integer destObj = Integer.valueOf(dest);
Predicate p = waitPredicates.get(destObj);
if ((p == null) || (tag == 9999) || (p.match(e))) {
dest_ent.setEventBuffer((SimEvent) e.clone());
dest_ent.setState(SimEntity.RUNNABLE);
waitPredicates.remove(destObj);
} else {
deferred.addEvent(e);
}
} else {
deferred.addEvent(e);
}
}
break;
case SimEvent.HOLD_DONE:
src = e.getSource();
if (src < 0) {
throw new IllegalArgumentException("Null entity holding.");
} else {
entities.get(src).setState(SimEntity.RUNNABLE);
}
break;
default:
break;
}
}
/**
* Internal method used to start the simulation. This method should <b>not</b> be used by user
* simulations.
*/
public static void runStart() {
running = true;
// Start all the entities
for (SimEntity ent : entities) {
ent.startEntity();
}
printMessage("Entities started.");
}
/**
* Check if the simulation is still running. This method should be used by entities to check if
* they should continue executing.
*
* @return if the simulation is still running, otherwise
*/
public static boolean running() {
return running;
}
/**
* This method is called if one wants to pause the simulation.
*
* @return true, if successful otherwise.
*/
public static boolean pauseSimulation() {
paused = true;
return paused;
}
/**
* This method is called if one wants to pause the simulation at a given time.
*
* @param time the time at which the simulation has to be paused
* @return true, if successful otherwise.
*/
public static boolean pauseSimulation(long time) {
if (time <= clock) {
return false;
} else {
pauseAt = time;
}
return true;
}
/**
* This method is called if one wants to resume the simulation that has previously been paused.
*
* @return if the simulation has been restarted or or otherwise.
*/
public static boolean resumeSimulation() {
paused = false;
if (pauseAt <= clock) {
pauseAt = -1;
}
return !paused;
}
/**
* Start the simulation running. This should be called after all the entities have been setup
* and added, and their ports linked.
*
* @return the double last clock value
*/
public static double run() {
if (!running) {
runStart();
}
while (true) {
if (runClockTick() || abruptTerminate) {
break;
}
// this block allows termination of simulation at a specific time
if (terminateAt > 0.0 && clock >= terminateAt) {
terminateSimulation();
clock = terminateAt;
break;
}
if (pauseAt != -1
&& ((future.size() > 0 && clock <= pauseAt && pauseAt <= future.iterator().next()
.eventTime()) || future.size() == 0 && pauseAt <= clock)) {
pauseSimulation();
clock = pauseAt;
}
while (paused) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
double clock = clock();
finishSimulation();
runStop();
return clock;
}
/**
* Internal method that allows the entities to terminate. This method should <b>not</b> be used
* in user simulations.
*/
public static void finishSimulation() {
// Allow all entities to exit their body method
if (!abruptTerminate) {
for (SimEntity ent : entities) {
if (ent.getState() != SimEntity.FINISHED) {
ent.run();
}
}
}
for (SimEntity ent : entities) {
ent.shutdownEntity();
}
// reset all static variables
// Private data members
entities = null;
entitiesByName = null;
future = null;
deferred = null;
clock = 0L;
running = false;
waitPredicates = null;
paused = false;
pauseAt = -1;
abruptTerminate = false;
}
/**
* Abruptally terminate.
*/
public static void abruptallyTerminate() {
abruptTerminate = true;
}
/**
* Prints a message about the progress of the simulation.
*
* @param message the message
*/
private static void printMessage(String message) {
Log.printLine(message);
}
/**
* Checks if is paused.
*
* @return true, if is paused
*/
public static boolean isPaused() {
return paused;
}
}

View File

@@ -0,0 +1,91 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import java.util.Calendar;
/**
* CloudimShutdown waits for termination of all CloudSim user entities to determine the end of
* simulation. This class will be created by CloudSim upon initialisation of the simulation, i.e.
* done via <tt>CloudSim.init()</tt> method. Hence, do not need to worry about creating an object of
* this class. This object signals the end of simulation to CloudInformationService (GIS) entity.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @since CloudSim Toolkit 1.0
*/
public class CloudSimShutdown extends SimEntity {
/** The num user. */
private int numUser;
/**
* Allocates a new CloudSimShutdown object.
* <p>
* The total number of grid user entity plays an important role to determine whether all
* hostList should be shut down or not. If one or more users are still not finish, then the
* hostList will not be shut down. Therefore, it is important to give a correct number of total
* grid user entity. Otherwise, CloudSim program will hang or encounter a weird behaviour.
*
* @param name the name to be associated with this entity (as required by SimEntity class)
* @param numUser total number of grid user entity
* @throws Exception This happens when creating this entity before initialising CloudSim package
* or this entity name is <tt>null</tt> or empty
* @see gridsim.CloudSim#init(int, Calendar, boolean)
* @pre name != null
* @pre numUser >= 0
* @post $none
*/
public CloudSimShutdown(String name, int numUser) throws Exception {
// NOTE: This entity doesn't use any I/O port.
// super(name, CloudSimTags.DEFAULT_BAUD_RATE);
super(name);
this.numUser = numUser;
}
/**
* The main method that shuts down hostList and Cloud Information Service (GIS). In addition,
* this method writes down a report at the end of a simulation based on
* <tt>reportWriterName</tt> defined in the Constructor. <br>
* <b>NOTE:</b> This method shuts down grid hostList and GIS entities either <tt>AFTER</tt> all
* grid users have been shut down or an entity requires an abrupt end of the whole simulation.
* In the first case, the number of grid users given in the Constructor <tt>must</tt> be
* correct. Otherwise, CloudSim package hangs forever or it does not terminate properly.
*
* @param ev the ev
* @pre $none
* @post $none
*/
@Override
public void processEvent(SimEvent ev) {
numUser--;
if (numUser == 0 || ev.getTag() == CloudSimTags.ABRUPT_END_OF_SIMULATION) {
CloudSim.abruptallyTerminate();
}
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.core.SimEntity#startEntity()
*/
@Override
public void startEntity() {
// do nothing
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.core.SimEntity#shutdownEntity()
*/
@Override
public void shutdownEntity() {
// do nothing
}
}

View File

@@ -0,0 +1,273 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
/**
* Contains various static command tags that indicate a type of action that needs to be undertaken
* by CloudSim entities when they receive or send events. <b>NOTE:</b> To avoid conflicts with other
* tags, CloudSim reserves negative numbers, 0 - 299, and 9600.
*
* @author Manzur Murshed
* @author Rajkumar Buyya
* @author Anthony Sulistio
* @since CloudSim Toolkit 1.0
*/
public class CloudSimTags {
/** Starting constant value for cloud-related tags **/
private static final int BASE = 0;
/** Starting constant value for network-related tags **/
private static final int NETBASE = 100;
/** Denotes boolean <tt>true</tt> in <tt>int</tt> value */
public static final int TRUE = 1;
/** Denotes boolean <tt>false</tt> in <tt>int</tt> value */
public static final int FALSE = 0;
/** Denotes the default baud rate for some CloudSim entities */
public static final int DEFAULT_BAUD_RATE = 9600;
/** Schedules an entity without any delay */
public static final double SCHEDULE_NOW = 0.0;
/** Denotes the end of simulation */
public static final int END_OF_SIMULATION = -1;
/**
* Denotes an abrupt end of simulation. That is, one event of this type is enough for
* {@link CloudSimShutdown} to trigger the end of the simulation
*/
public static final int ABRUPT_END_OF_SIMULATION = -2;
/**
* Denotes insignificant simulation entity or time. This tag will not be used for identification
* purposes.
*/
public static final int INSIGNIFICANT = BASE + 0;
/** Sends an Experiment object between UserEntity and Broker entity */
public static final int EXPERIMENT = BASE + 1;
/**
* Denotes a grid resource to be registered. This tag is normally used between
* CloudInformationService and CloudResouce entity.
*/
public static final int REGISTER_RESOURCE = BASE + 2;
/**
* Denotes a grid resource, that can support advance reservation, to be registered. This tag is
* normally used between CloudInformationService and CloudResouce entity.
*/
public static final int REGISTER_RESOURCE_AR = BASE + 3;
/**
* Denotes a list of all hostList, including the ones that can support advance reservation. This
* tag is normally used between CloudInformationService and CloudSim entity.
*/
public static final int RESOURCE_LIST = BASE + 4;
/**
* Denotes a list of hostList that only support advance reservation. This tag is normally used
* between CloudInformationService and CloudSim entity.
*/
public static final int RESOURCE_AR_LIST = BASE + 5;
/**
* Denotes grid resource characteristics information. This tag is normally used between CloudSim
* and CloudResource entity.
*/
public static final int RESOURCE_CHARACTERISTICS = BASE + 6;
/**
* Denotes grid resource allocation policy. This tag is normally used between CloudSim and
* CloudResource entity.
*/
public static final int RESOURCE_DYNAMICS = BASE + 7;
/**
* Denotes a request to get the total number of Processing Elements (PEs) of a resource. This
* tag is normally used between CloudSim and CloudResource entity.
*/
public static final int RESOURCE_NUM_PE = BASE + 8;
/**
* Denotes a request to get the total number of free Processing Elements (PEs) of a resource.
* This tag is normally used between CloudSim and CloudResource entity.
*/
public static final int RESOURCE_NUM_FREE_PE = BASE + 9;
/**
* Denotes a request to record events for statistical purposes. This tag is normally used
* between CloudSim and CloudStatistics entity.
*/
public static final int RECORD_STATISTICS = BASE + 10;
/** Denotes a request to get a statistical list. */
public static final int RETURN_STAT_LIST = BASE + 11;
/**
* Denotes a request to send an Accumulator object based on category into an event scheduler.
* This tag is normally used between ReportWriter and CloudStatistics entity.
*/
public static final int RETURN_ACC_STATISTICS_BY_CATEGORY = BASE + 12;
/**
* Denotes a request to register a CloudResource entity to a regional CloudInformationService
* (GIS) entity
*/
public static final int REGISTER_REGIONAL_GIS = BASE + 13;
/**
* Denotes a request to get a list of other regional GIS entities from the system GIS entity
*/
public static final int REQUEST_REGIONAL_GIS = BASE + 14;
/**
* Denotes request for grid resource characteristics information. This tag is normally used
* between CloudSim and CloudResource entity.
*/
public static final int RESOURCE_CHARACTERISTICS_REQUEST = BASE + 15;
/** This tag is used by an entity to send ping requests */
public static final int INFOPKT_SUBMIT = NETBASE + 5;
/** This tag is used to return the ping request back to sender */
public static final int INFOPKT_RETURN = NETBASE + 6;
/**
* Denotes the return of a Cloudlet back to sender. This tag is normally used by CloudResource
* entity.
*/
public static final int CLOUDLET_RETURN = BASE + 20;
/**
* Denotes the submission of a Cloudlet. This tag is normally used between CloudSim User and
* CloudResource entity.
*/
public static final int CLOUDLET_SUBMIT = BASE + 21;
/**
* Denotes the submission of a Cloudlet with an acknowledgement. This tag is normally used
* between CloudSim User and CloudResource entity.
*/
public static final int CLOUDLET_SUBMIT_ACK = BASE + 22;
/** Cancels a Cloudlet submitted in the CloudResource entity. */
public static final int CLOUDLET_CANCEL = BASE + 23;
/** Denotes the status of a Cloudlet. */
public static final int CLOUDLET_STATUS = BASE + 24;
/** Pauses a Cloudlet submitted in the CloudResource entity. */
public static final int CLOUDLET_PAUSE = BASE + 25;
/**
* Pauses a Cloudlet submitted in the CloudResource entity with an acknowledgement.
*/
public static final int CLOUDLET_PAUSE_ACK = BASE + 26;
/** Resumes a Cloudlet submitted in the CloudResource entity. */
public static final int CLOUDLET_RESUME = BASE + 27;
/**
* Resumes a Cloudlet submitted in the CloudResource entity with an acknowledgement.
*/
public static final int CLOUDLET_RESUME_ACK = BASE + 28;
/** Moves a Cloudlet to another CloudResource entity. */
public static final int CLOUDLET_MOVE = BASE + 29;
/**
* Moves a Cloudlet to another CloudResource entity with an acknowledgement.
*/
public static final int CLOUDLET_MOVE_ACK = BASE + 30;
/**
* Denotes a request to create a new VM in a Datacentre With acknowledgement information sent by
* the Datacentre
*/
public static final int VM_CREATE = BASE + 31;
/**
* Denotes a request to create a new VM in a Datacentre With acknowledgement information sent by
* the Datacentre
*/
public static final int VM_CREATE_ACK = BASE + 32;
/**
* Denotes a request to destroy a new VM in a Datacentre
*/
public static final int VM_DESTROY = BASE + 33;
/**
* Denotes a request to destroy a new VM in a Datacentre
*/
public static final int VM_DESTROY_ACK = BASE + 34;
/**
* Denotes a request to migrate a new VM in a Datacentre
*/
public static final int VM_MIGRATE = BASE + 35;
/**
* Denotes a request to migrate a new VM in a Datacentre With acknowledgement information sent
* by the Datacentre
*/
public static final int VM_MIGRATE_ACK = BASE + 36;
/**
* Denotes an event to send a file from a user to a datacenter
*/
public static final int VM_DATA_ADD = BASE + 37;
/**
* Denotes an event to send a file from a user to a datacenter
*/
public static final int VM_DATA_ADD_ACK = BASE + 38;
/**
* Denotes an event to remove a file from a datacenter
*/
public static final int VM_DATA_DEL = BASE + 39;
/**
* Denotes an event to remove a file from a datacenter
*/
public static final int VM_DATA_DEL_ACK = BASE + 40;
/**
* Denotes an internal event generated in a PowerDatacenter
*/
public static final int VM_DATACENTER_EVENT = BASE + 41;
/**
* Denotes an internal event generated in a Broker
*/
public static final int VM_BROKER_EVENT = BASE + 42;
public static final int Network_Event_UP = BASE + 43;
public static final int Network_Event_send = BASE + 44;
public static final int RESOURCE_Register = BASE + 45;
public static final int Network_Event_DOWN = BASE + 46;
public static final int Network_Event_Host = BASE + 47;
public static final int NextCycle = BASE + 48;
/** Private Constructor */
private CloudSimTags() {
throw new UnsupportedOperationException("CloudSim Tags cannot be instantiated");
}
}

View File

@@ -0,0 +1,88 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
/**
* This class implements the deferred event queue used by {@link Simulation}. The event queue uses a
* linked list to store the events.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see Simulation
* @see SimEvent
*/
public class DeferredQueue {
/** The list. */
private final List<SimEvent> list = new LinkedList<SimEvent>();
/** The max time. */
private double maxTime = -1;
/**
* Adds a new event to the queue. Adding a new event to the queue preserves the temporal order
* of the events.
*
* @param newEvent The event to be added to the queue.
*/
public void addEvent(SimEvent newEvent) {
// The event has to be inserted as the last of all events
// with the same event_time(). Yes, this matters.
double eventTime = newEvent.eventTime();
if (eventTime >= maxTime) {
list.add(newEvent);
maxTime = eventTime;
return;
}
ListIterator<SimEvent> iterator = list.listIterator();
SimEvent event;
while (iterator.hasNext()) {
event = iterator.next();
if (event.eventTime() > eventTime) {
iterator.previous();
iterator.add(newEvent);
return;
}
}
list.add(newEvent);
}
/**
* Returns an iterator to the events in the queue.
*
* @return the iterator
*/
public Iterator<SimEvent> iterator() {
return list.iterator();
}
/**
* Returns the size of this event queue.
*
* @return the number of events in the queue.
*/
public int size() {
return list.size();
}
/**
* Clears the queue.
*/
public void clear() {
list.clear();
}
}

View File

@@ -0,0 +1,99 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* This class implements the future event queue used by {@link Simulation}. The event queue uses a
* {@link TreeSet} in order to store the events.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see Simulation
* @see java.util.TreeSet
*/
public class FutureQueue {
/** The sorted set. */
private final SortedSet<SimEvent> sortedSet = new TreeSet<SimEvent>();
/** The serial. */
private long serial = 0;
/**
* Add a new event to the queue. Adding a new event to the queue preserves the temporal order of
* the events in the queue.
*
* @param newEvent The event to be put in the queue.
*/
public void addEvent(SimEvent newEvent) {
newEvent.setSerial(serial++);
sortedSet.add(newEvent);
}
/**
* Add a new event to the head of the queue.
*
* @param newEvent The event to be put in the queue.
*/
public void addEventFirst(SimEvent newEvent) {
newEvent.setSerial(0);
sortedSet.add(newEvent);
}
/**
* Returns an iterator to the queue.
*
* @return the iterator
*/
public Iterator<SimEvent> iterator() {
return sortedSet.iterator();
}
/**
* Returns the size of this event queue.
*
* @return the size
*/
public int size() {
return sortedSet.size();
}
/**
* Removes the event from the queue.
*
* @param event the event
* @return true, if successful
*/
public boolean remove(SimEvent event) {
return sortedSet.remove(event);
}
/**
* Removes all the events from the queue.
*
* @param events the events
* @return true, if successful
*/
public boolean removeAll(Collection<SimEvent> events) {
return sortedSet.removeAll(events);
}
/**
* Clears the queue.
*/
public void clear() {
sortedSet.clear();
}
}

View File

@@ -0,0 +1,682 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.NetworkTopology;
import org.cloudbus.cloudsim.core.predicates.Predicate;
/**
* This class represents a simulation entity. An entity handles events and can send events to other
* entities. When this class is extended, there are a few methods that need to be implemented:
* <ul>
* <li> {@link #startEntity()} is invoked by the {@link Simulation} class when the simulation is
* started. This method should be responsible for starting the entity up.
* <li> {@link #processEvent(SimEvent)} is invoked by the {@link Simulation} class whenever there is
* an event in the deferred queue, which needs to be processed by the entity.
* <li> {@link #shutdownEntity()} is invoked by the {@link Simulation} before the simulation
* finishes. If you want to save data in log files this is the method in which the corresponding
* code would be placed.
* </ul>
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public abstract class SimEntity implements Cloneable {
/** The name. */
private String name;
/** The id. */
private int id;
/** The buffer for selected incoming events. */
private SimEvent evbuf;
/** The entity's current state. */
private int state;
/**
* Creates a new entity.
*
* @param name the name to be associated with this entity
*/
public SimEntity(String name) {
if (name.indexOf(" ") != -1) {
throw new IllegalArgumentException("Entity names can't contain spaces.");
}
this.name = name;
id = -1;
state = RUNNABLE;
CloudSim.addEntity(this);
}
/**
* Get the name of this entity.
*
* @return The entity's name
*/
public String getName() {
return name;
}
/**
* Get the unique id number assigned to this entity.
*
* @return The id number
*/
public int getId() {
return id;
}
// The schedule functions
/**
* Send an event to another entity by id number, with data. Note that the tag <code>9999</code>
* is reserved.
*
* @param dest The unique id number of the destination entity
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void schedule(int dest, double delay, int tag, Object data) {
if (!CloudSim.running()) {
return;
}
CloudSim.send(id, dest, delay, tag, data);
}
/**
* Send an event to another entity by id number and with <b>no</b> data. Note that the tag
* <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
*/
public void schedule(int dest, double delay, int tag) {
schedule(dest, delay, tag, null);
}
/**
* Send an event to another entity through a port with a given name, with data. Note that the
* tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void schedule(String dest, double delay, int tag, Object data) {
schedule(CloudSim.getEntityId(dest), delay, tag, data);
}
/**
* Send an event to another entity through a port with a given name, with <b>no</b> data. Note
* that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
*/
public void schedule(String dest, double delay, int tag) {
schedule(dest, delay, tag, null);
}
/**
* Send an event to another entity by id number, with data. Note that the tag <code>9999</code>
* is reserved.
*
* @param dest The unique id number of the destination entity
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleNow(int dest, int tag, Object data) {
schedule(dest, 0, tag, data);
}
/**
* Send an event to another entity by id number and with <b>no</b> data. Note that the tag
* <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param tag An user-defined number representing the type of event.
*/
public void scheduleNow(int dest, int tag) {
schedule(dest, 0, tag, null);
}
/**
* Send an event to another entity through a port with a given name, with data. Note that the
* tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleNow(String dest, int tag, Object data) {
schedule(CloudSim.getEntityId(dest), 0, tag, data);
}
/**
* Send an event to another entity through a port with a given name, with <b>no</b> data. Note
* that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param tag An user-defined number representing the type of event.
*/
public void scheduleNow(String dest, int tag) {
schedule(dest, 0, tag, null);
}
/**
* Send a high priority event to another entity by id number, with data. Note that the tag
* <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleFirst(int dest, double delay, int tag, Object data) {
if (!CloudSim.running()) {
return;
}
CloudSim.sendFirst(id, dest, delay, tag, data);
}
/**
* Send a high priority event to another entity by id number and with <b>no</b> data. Note that
* the tag <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
*/
public void scheduleFirst(int dest, double delay, int tag) {
scheduleFirst(dest, delay, tag, null);
}
/**
* Send a high priority event to another entity through a port with a given name, with data.
* Note that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleFirst(String dest, double delay, int tag, Object data) {
scheduleFirst(CloudSim.getEntityId(dest), delay, tag, data);
}
/**
* Send a high priority event to another entity through a port with a given name, with <b>no</b>
* data. Note that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param delay How long from the current simulation time the event should be sent
* @param tag An user-defined number representing the type of event.
*/
public void scheduleFirst(String dest, double delay, int tag) {
scheduleFirst(dest, delay, tag, null);
}
/**
* Send a high priority event to another entity by id number, with data. Note that the tag
* <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleFirstNow(int dest, int tag, Object data) {
scheduleFirst(dest, 0, tag, data);
}
/**
* Send a high priority event to another entity by id number and with <b>no</b> data. Note that
* the tag <code>9999</code> is reserved.
*
* @param dest The unique id number of the destination entity
* @param tag An user-defined number representing the type of event.
*/
public void scheduleFirstNow(int dest, int tag) {
scheduleFirst(dest, 0, tag, null);
}
/**
* Send a high priority event to another entity through a port with a given name, with data.
* Note that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param tag An user-defined number representing the type of event.
* @param data The data to be sent with the event.
*/
public void scheduleFirstNow(String dest, int tag, Object data) {
scheduleFirst(CloudSim.getEntityId(dest), 0, tag, data);
}
/**
* Send a high priority event to another entity through a port with a given name, with <b>no</b>
* data. Note that the tag <code>9999</code> is reserved.
*
* @param dest The name of the port to send the event through
* @param tag An user-defined number representing the type of event.
*/
public void scheduleFirstNow(String dest, int tag) {
scheduleFirst(dest, 0, tag, null);
}
/**
* Set the entity to be inactive for a time period.
*
* @param delay the time period for which the entity will be inactive
*/
public void pause(double delay) {
if (delay < 0) {
throw new IllegalArgumentException("Negative delay supplied.");
}
if (!CloudSim.running()) {
return;
}
CloudSim.pause(id, delay);
}
/**
* Count how many events matching a predicate are waiting in the entity's deferred queue.
*
* @param p The event selection predicate
* @return The count of matching events
*/
public int numEventsWaiting(Predicate p) {
return CloudSim.waiting(id, p);
}
/**
* Count how many events are waiting in the entity's deferred queue.
*
* @return The count of events
*/
public int numEventsWaiting() {
return CloudSim.waiting(id, CloudSim.SIM_ANY);
}
/**
* Extract the first event matching a predicate waiting in the entity's deferred queue.
*
* @param p The event selection predicate
* @return the simulation event
*/
public SimEvent selectEvent(Predicate p) {
if (!CloudSim.running()) {
return null;
}
return CloudSim.select(id, p);
}
/**
* Cancel the first event matching a predicate waiting in the entity's future queue.
*
* @param p The event selection predicate
* @return The number of events cancelled (0 or 1)
*/
public SimEvent cancelEvent(Predicate p) {
if (!CloudSim.running()) {
return null;
}
return CloudSim.cancel(id, p);
}
/**
* Get the first event matching a predicate from the deferred queue, or if none match, wait for
* a matching event to arrive.
*
* @param p The predicate to match
* @return the simulation event
*/
public SimEvent getNextEvent(Predicate p) {
if (!CloudSim.running()) {
return null;
}
if (numEventsWaiting(p) > 0) {
return selectEvent(p);
}
return null;
}
/**
* Wait for an event matching a specific predicate. This method does not check the entity's
* deferred queue.
*
* @param p The predicate to match
*/
public void waitForEvent(Predicate p) {
if (!CloudSim.running()) {
return;
}
CloudSim.wait(id, p);
state = WAITING;
}
/**
* Get the first event waiting in the entity's deferred queue, or if there are none, wait for an
* event to arrive.
*
* @return the simulation event
*/
public SimEvent getNextEvent() {
return getNextEvent(CloudSim.SIM_ANY);
}
/**
* This method is invoked by the {@link Simulation} class when the simulation is started. This
* method should be responsible for starting the entity up.
*/
public abstract void startEntity();
/**
* This method is invoked by the {@link Simulation} class whenever there is an event in the
* deferred queue, which needs to be processed by the entity.
*
* @param ev the event to be processed by the entity
*/
public abstract void processEvent(SimEvent ev);
/**
* This method is invoked by the {@link Simulation} before the simulation finishes. If you want
* to save data in log files this is the method in which the corresponding code would be placed.
*/
public abstract void shutdownEntity();
public void run() {
SimEvent ev = evbuf != null ? evbuf : getNextEvent();
while (ev != null) {
processEvent(ev);
if (state != RUNNABLE) {
break;
}
ev = getNextEvent();
}
evbuf = null;
}
/**
* Get a clone of the entity. This is used when independent replications have been specified as
* an output analysis method. Clones or backups of the entities are made in the beginning of the
* simulation in order to reset the entities for each subsequent replication. This method should
* not be called by the user.
*
* @return A clone of the entity
* @throws CloneNotSupportedException the clone not supported exception
*/
@Override
protected final Object clone() throws CloneNotSupportedException {
SimEntity copy = (SimEntity) super.clone();
copy.setName(name);
copy.setEventBuffer(null);
return copy;
}
// Used to set a cloned entity's name
/**
* Sets the name.
*
* @param new_name the new name
*/
private void setName(String new_name) {
name = new_name;
}
// --------------- PACKAGE LEVEL METHODS ------------------
/**
* Gets the state.
*
* @return the state
*/
protected int getState() {
return state;
}
/**
* Gets the event buffer.
*
* @return the event buffer
*/
protected SimEvent getEventBuffer() {
return evbuf;
}
// The entity states
/** The Constant RUNNABLE. */
public static final int RUNNABLE = 0;
/** The Constant WAITING. */
public static final int WAITING = 1;
/** The Constant HOLDING. */
public static final int HOLDING = 2;
/** The Constant FINISHED. */
public static final int FINISHED = 3;
/**
* Sets the state.
*
* @param state the new state
*/
protected void setState(int state) {
this.state = state;
}
/**
* Sets the id.
*
* @param id the new id
*/
protected void setId(int id) {
this.id = id;
}
/**
* Sets the event buffer.
*
* @param e the new event buffer
*/
protected void setEventBuffer(SimEvent e) {
evbuf = e;
}
// --------------- EVENT / MESSAGE SEND WITH NETWORK DELAY METHODS ------------------
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityId the id number of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @param data A reference to data to be sent with the event
* @pre entityID > 0
* @pre delay >= 0.0
* @pre data != null
* @post $none
*/
protected void send(int entityId, double delay, int cloudSimTag, Object data) {
if (entityId < 0) {
return;
}
// if delay is -ve, then it doesn't make sense. So resets to 0.0
if (delay < 0) {
delay = 0;
}
if (Double.isInfinite(delay)) {
throw new IllegalArgumentException("The specified delay is infinite value");
}
if (entityId < 0) {
Log.printLine(getName() + ".send(): Error - " + "invalid entity id " + entityId);
return;
}
int srcId = getId();
if (entityId != srcId) {// does not delay self messages
delay += getNetworkDelay(srcId, entityId);
}
schedule(entityId, delay, cloudSimTag, data);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityId the id number of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @pre entityID > 0
* @pre delay >= 0.0
* @post $none
*/
protected void send(int entityId, double delay, int cloudSimTag) {
send(entityId, delay, cloudSimTag, null);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityName the name of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @param data A reference to data to be sent with the event
* @pre entityName != null
* @pre delay >= 0.0
* @pre data != null
* @post $none
*/
protected void send(String entityName, double delay, int cloudSimTag, Object data) {
send(CloudSim.getEntityId(entityName), delay, cloudSimTag, data);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityName the name of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @pre entityName != null
* @pre delay >= 0.0
* @post $none
*/
protected void send(String entityName, double delay, int cloudSimTag) {
send(entityName, delay, cloudSimTag, null);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityId the id number of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @param data A reference to data to be sent with the event
* @pre entityID > 0
* @pre delay >= 0.0
* @pre data != null
* @post $none
*/
protected void sendNow(int entityId, int cloudSimTag, Object data) {
send(entityId, 0, cloudSimTag, data);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityId the id number of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @pre entityID > 0
* @pre delay >= 0.0
* @post $none
*/
protected void sendNow(int entityId, int cloudSimTag) {
send(entityId, 0, cloudSimTag, null);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityName the name of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @param data A reference to data to be sent with the event
* @pre entityName != null
* @pre delay >= 0.0
* @pre data != null
* @post $none
*/
protected void sendNow(String entityName, int cloudSimTag, Object data) {
send(CloudSim.getEntityId(entityName), 0, cloudSimTag, data);
}
/**
* Sends an event/message to another entity by <tt>delaying</tt> the simulation time from the
* current time, with a tag representing the event type.
*
* @param entityName the name of the destination entity
* @param delay how long from the current simulation time the event should be sent. If delay is
* a negative number, then it will be changed to 0
* @param cloudSimTag an user-defined number representing the type of an event/message
* @pre entityName != null
* @pre delay >= 0.0
* @post $none
*/
protected void sendNow(String entityName, int cloudSimTag) {
send(entityName, 0, cloudSimTag, null);
}
/**
* Gets the network delay associated to the sent of a message from a given source to a given
* destination.
*
* @param src source of the message
* @param dst destination of the message
* @return delay to send a message from src to dst
* @pre src >= 0
* @pre dst >= 0
*/
private double getNetworkDelay(int src, int dst) {
if (NetworkTopology.isNetworkEnabled()) {
return NetworkTopology.getDelay(src, dst);
}
return 0.0;
}
}

View File

@@ -0,0 +1,234 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core;
/**
* This class represents a simulation event which is passed between the entities in the simulation.
*
* @author Costas Simatos
* @see Simulation
* @see SimEntity
*/
public class SimEvent implements Cloneable, Comparable<SimEvent> {
/** internal event type **/
private final int etype;
/** time at which event should occur **/
private final double time;
/** time that the event was removed from the queue for service **/
private double endWaitingTime;
/** id of entity who scheduled event **/
private int entSrc;
/** id of entity event will be sent to **/
private int entDst;
/** the user defined type of the event **/
private final int tag;
/** any data the event is carrying **/
private final Object data;
private long serial = -1;
// Internal event types
public static final int ENULL = 0;
public static final int SEND = 1;
public static final int HOLD_DONE = 2;
public static final int CREATE = 3;
/**
* Create a blank event.
*/
public SimEvent() {
etype = ENULL;
time = -1L;
endWaitingTime = -1.0;
entSrc = -1;
entDst = -1;
tag = -1;
data = null;
}
// ------------------- PACKAGE LEVEL METHODS --------------------------
SimEvent(int evtype, double time, int src, int dest, int tag, Object edata) {
etype = evtype;
this.time = time;
entSrc = src;
entDst = dest;
this.tag = tag;
data = edata;
}
SimEvent(int evtype, double time, int src) {
etype = evtype;
this.time = time;
entSrc = src;
entDst = -1;
tag = -1;
data = null;
}
protected void setSerial(long serial) {
this.serial = serial;
}
/**
* Used to set the time at which this event finished waiting in the event
*
* @param end_waiting_time
*/
protected void setEndWaitingTime(double end_waiting_time) {
endWaitingTime = end_waiting_time;
}
@Override
public String toString() {
return "Event tag = " + tag + " source = " + CloudSim.getEntity(entSrc).getName() + " destination = "
+ CloudSim.getEntity(entDst).getName();
}
/**
* The internal type
*
* @return
*/
public int getType() {
return etype;
}
// ------------------- PUBLIC METHODS --------------------------
/**
* @see Comparable#compareTo(Object)
*/
@Override
public int compareTo(SimEvent event) {
if (event == null) {
return 1;
} else if (time < event.time) {
return -1;
} else if (time > event.time) {
return 1;
} else if (serial < event.serial) {
return -1;
} else if (this == event) {
return 0;
} else {
return 1;
}
}
/**
* Get the unique id number of the entity which received this event.
*
* @return the id number
*/
public int getDestination() {
return entDst;
}
/**
* Get the unique id number of the entity which scheduled this event.
*
* @return the id number
*/
public int getSource() {
return entSrc;
}
/**
* Get the simulation time that this event was scheduled.
*
* @return The simulation time
*/
public double eventTime() {
return time;
}
/**
* Get the simulation time that this event was removed from the queue for service.
*
* @return The simulation time
*/
public double endWaitingTime() {
return endWaitingTime;
}
/**
* Get the user-defined tag of this event
*
* @return The tag
*/
public int type() {
return tag;
}
/**
* Get the unique id number of the entity which scheduled this event.
*
* @return the id number
*/
public int scheduledBy() {
return entSrc;
}
/**
* Get the user-defined tag of this event.
*
* @return The tag
*/
public int getTag() {
return tag;
}
/**
* Get the data passed in this event.
*
* @return A reference to the data
*/
public Object getData() {
return data;
}
/**
* Create an exact copy of this event.
*
* @return The event's copy
*/
@Override
public Object clone() {
return new SimEvent(etype, time, entSrc, entDst, tag, data);
}
/**
* Set the source entity of this event.
*
* @param s The unique id number of the entity
*/
public void setSource(int s) {
entSrc = s;
}
/**
* Set the destination entity of this event.
*
* @param d The unique id number of the entity
*/
public void setDestination(int d) {
entDst = d;
}
}

View File

@@ -0,0 +1,39 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* Predicates are used to select events from the deferred queue. This class is abstract and must be
* extended when writing a new predicate. Some standard predicates are provided.<br>
* The idea of simulation predicates was copied from SimJava 2.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see PredicateType
* @see PredicateFrom
* @see PredicateAny
* @see PredicateNone
* @see Simulation
*/
public abstract class Predicate {
/**
* The match function which must be overridden when writing a new predicate. The function is
* called with each event in the deferred queue as its parameter when a
* <code>Simulation.select()</code> call is made by the user.
*
* @param event The event to test for a match.
* @return The function should return <code>true</code> if the event matches and should be
* selected, or <code>false</code> if it does not match the predicate.
*/
public abstract boolean match(SimEvent event);
}

View File

@@ -0,0 +1,37 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate which will match any event on the deferred event queue. There is a publicly
* accessible instance of this predicate in <code>Simulation</code>, called
* <code>Simulation.SIM_ANY</code>, so no new instances need to be created. <br>
* The idea of simulation predicates was copied from SimJava 2.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see Predicate
* @see Simulation
*/
public class PredicateAny extends Predicate {
/**
* The match function called by <code>Simulation</code>, not used directly by the user.
*
* @param ev the ev
* @return true, if match
*/
@Override
public boolean match(SimEvent ev) {
return true;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate which selects events from specific entities.<br>
* The idea of simulation predicates was copied from SimJava 2.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see PredicateNotFrom
* @see Predicate
*/
public class PredicateFrom extends Predicate {
/** The ids. */
private final int[] ids;
/**
* Constructor used to select events that were sent by a specific entity.
*
* @param sourceId the id number of the source entity
*/
public PredicateFrom(int sourceId) {
ids = new int[] { sourceId };
}
/**
* Constructor used to select events that were sent by any entity from a given set.
*
* @param sourceIds the set of id numbers of the source entities
*/
public PredicateFrom(int[] sourceIds) {
ids = sourceIds.clone();
}
/**
* The match function called by <code>Simulation</code>, not used directly by the user.
*
* @param ev the event to check
* @return <code>true</code> if the event matches the predicate, <code>false</code> otherwise
*/
@Override
public boolean match(SimEvent ev) {
int src = ev.getSource();
for (int id : ids) {
if (src == id) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,37 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate which will <b>not</b> match any event on the deferred event queue. There is a
* publicly accessible instance of this predicate in the {@link Simulation} class, called
* {@link Simulation#SIM_NONE}, so the user does not need to create any new instances. The idea of
* simulation predicates was copied from SimJava 2.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see Predicate
* @see Simulation
*/
public class PredicateNone extends Predicate {
/**
* The match function called by {@link Simulation}, not used directly by the user.
*
* @param ev the event to check
* @return <code>true</code> if the event matches the predicate, <code>false</code> otherwise
*/
@Override
public boolean match(SimEvent ev) {
return false;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate which selects events that have not been sent by specific entities.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see PredicateFrom
* @see Predicate
*/
public class PredicateNotFrom extends Predicate {
/** The ids. */
private final int[] ids;
/**
* Constructor used to select events that were not sent by a specific entity.
*
* @param sourceId the id number of the source entity
*/
public PredicateNotFrom(int sourceId) {
ids = new int[] { sourceId };
}
/**
* Constructor used to select events that were not sent by any entity from a given set.
*
* @param sourceIds the set of id numbers of the source entities
*/
public PredicateNotFrom(int[] sourceIds) {
ids = sourceIds.clone();
}
/**
* The match function called by {@link Simulation}, not used directly by the user.
*
* @param ev the event to check
* @return <code>true</code> if the event matches the predicate, <code>false</code> otherwise
*/
@Override
public boolean match(SimEvent ev) {
int src = ev.getSource();
for (int id : ids) {
if (src == id) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate to select events that don't match specific tags.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see PredicateType
* @see Predicate
*/
public class PredicateNotType extends Predicate {
/** The tags. */
private final int[] tags;
/**
* Constructor used to select events whose tags do not match a given tag.
*
* @param tag An event tag value
*/
public PredicateNotType(int tag) {
tags = new int[] { tag };
}
/**
* Constructor used to select events whose tag values do not match any of the given tags.
*
* @param tags the list of tags
*/
public PredicateNotType(int[] tags) {
this.tags = tags.clone();
}
/**
* The match function called by {@link Simulation}, not used directly by the user.
*
* @param ev the ev
* @return true, if match
*/
@Override
public boolean match(SimEvent ev) {
int tag = ev.getTag();
for (int tag2 : tags) {
if (tag == tag2) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.core.predicates;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A predicate to select events with specific tags.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
* @see PredicateNotType
* @see Predicate
*/
public class PredicateType extends Predicate {
/** The tags. */
private final int[] tags;
/**
* Constructor used to select events with the tag value <code>t1</code>.
*
* @param t1 an event tag value
*/
public PredicateType(int t1) {
tags = new int[] { t1 };
}
/**
* Constructor used to select events with a tag value equal to any of the specified tags.
*
* @param tags the list of tags
*/
public PredicateType(int[] tags) {
this.tags = tags.clone();
}
/**
* The match function called by <code>Sim_system</code>, not used directly by the user.
*
* @param ev the ev
* @return true, if match
*/
@Override
public boolean match(SimEvent ev) {
int tag = ev.getTag();
for (int tag2 : tags) {
if (tag == tag2) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,26 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
/**
* Interface to be implemented by a random number generator.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public interface ContinuousDistribution {
/**
* Sample the random number generator.
*
* @return The sample
*/
double sample();
}

View File

@@ -0,0 +1,64 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* An exponential number generator.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class ExponentialDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The mean. */
private final double mean;
/**
* Creates a new exponential number generator.
*
* @param seed the seed to be used.
* @param mean the mean for the distribution.
*/
public ExponentialDistr(long seed, double mean) {
if (mean <= 0.0) {
throw new IllegalArgumentException("Mean must be greater than 0.0");
}
numGen = new Random(seed);
this.mean = mean;
}
/**
* Creates a new exponential number generator.
*
* @param mean the mean for the distribution.
*/
public ExponentialDistr(double mean) {
if (mean <= 0.0) {
throw new IllegalArgumentException("Mean must be greated than 0.0");
}
numGen = new Random(System.currentTimeMillis());
this.mean = mean;
}
/**
* Generate a new random number.
*
* @return the next random number in the sequence
*/
@Override
public double sample() {
return -mean * Math.log(numGen.nextDouble());
}
}

View File

@@ -0,0 +1,78 @@
/*
* Title: CloudSim Toolkit
* Descripimport java.util.Random;
mulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class GammaDistr.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class GammaDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The alpha. */
private final int alpha;
/** The beta. */
private final double beta;
/**
* Instantiates a new gamma distr.
*
* @param seed the seed
* @param alpha the alpha
* @param beta the beta
*/
public GammaDistr(Random seed, int alpha, double beta) {
if (alpha <= 0 || beta <= 0.0) {
throw new IllegalArgumentException("Alpha and beta must be greater than 0.0");
}
numGen = seed;
this.alpha = alpha;
this.beta = beta;
}
/**
* Instantiates a new gamma distr.
*
* @param alpha the alpha
* @param beta the beta
*/
public GammaDistr(int alpha, double beta) {
if (alpha <= 0 || beta <= 0.0) {
throw new IllegalArgumentException("Alpha and beta must be greater than 0.0");
}
numGen = new Random(System.currentTimeMillis());
this.alpha = alpha;
this.beta = beta;
}
/*
* (non-Javadoc)
* @see cloudsim.distributions.ContinuousDistribution#sample()
*/
@Override
public double sample() {
double sum = 0.0;
for (int i = 0; i < alpha; i++) {
sum += Math.log(numGen.nextDouble());
}
return -beta * sum;
}
}

View File

@@ -0,0 +1,77 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class LognormalDistr.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class LognormalDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The mean. */
private final double mean;
/** The dev. */
private final double dev;
/**
* Instantiates a new lognormal distr.
*
* @param seed the seed
* @param mean the mean
* @param dev the dev
*/
public LognormalDistr(Random seed, double mean, double dev) {
if (mean <= 0.0 || dev <= 0.0) {
throw new IllegalArgumentException("Mean and deviation must be greater than 0.0");
}
numGen = seed;
this.mean = mean;
this.dev = dev;
}
/**
* Instantiates a new lognormal distr.
*
* @param mean the mean
* @param dev the dev
*/
public LognormalDistr(double mean, double dev) {
if (mean <= 0.0 || dev <= 0.0) {
throw new IllegalArgumentException("Mean and deviation must be greater than 0.0");
}
numGen = new Random(System.currentTimeMillis());
this.mean = mean;
this.dev = dev;
}
/*
* (non-Javadoc)
* @see cloudsim.distributions.ContinuousDistribution#sample()
*/
@Override
public double sample() {
// generate a normal variate from a uniform variate
double n = Math.sqrt(-2 * Math.log(numGen.nextDouble()))
* Math.sin(2 * Math.PI * numGen.nextDouble());
// use it to generate the lognormal variate
return Math.pow(Math.E, mean + dev * n);
}
}

View File

@@ -0,0 +1,68 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class LomaxDistribution.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class LomaxDistribution extends ParetoDistr implements ContinuousDistribution {
/** The shift. */
private final double shift;
/**
* Instantiates a new lomax distribution.
*
* @param shape the shape
* @param location the location
* @param shift the shift
*/
public LomaxDistribution(double shape, double location, double shift) {
super(shape, location);
if (shift > location) {
throw new IllegalArgumentException("Shift must be smaller or equal than location");
}
this.shift = shift;
}
/**
* Instantiates a new lomax distribution.
*
* @param seed the seed
* @param shape the shape
* @param location the location
* @param shift the shift
*/
public LomaxDistribution(Random seed, double shape, double location, double shift) {
super(seed, shape, location);
if (shift > location) {
throw new IllegalArgumentException("Shift must be smaller or equal than location");
}
this.shift = shift;
}
/*
* (non-Javadoc)
* @see cloudsim.distributions.ParetoDistr#sample()
*/
@Override
public double sample() {
return super.sample() - shift;
}
}

View File

@@ -0,0 +1,73 @@
/*
* Title: CloudSim Toolkit
* Descripimport java.util.Random;
mulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class ParetoDistr.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class ParetoDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The shape. */
private final double shape;
/** The location. */
private final double location;
/**
* Instantiates a new pareto distr.
*
* @param seed the seed
* @param shape the shape
* @param location the location
*/
public ParetoDistr(Random seed, double shape, double location) {
if (shape <= 0.0 || location <= 0.0) {
throw new IllegalArgumentException("Mean and deviation must be greater than 0.0");
}
numGen = seed;
this.shape = shape;
this.location = location;
}
/**
* Instantiates a new pareto distr.
*
* @param shape the shape
* @param location the location
*/
public ParetoDistr(double shape, double location) {
if (shape <= 0.0 || location <= 0.0) {
throw new IllegalArgumentException("Mean and deviation must be greater than 0.0");
}
numGen = new Random(System.currentTimeMillis());
this.shape = shape;
this.location = location;
}
/*
* (non-Javadoc)
* @see cloudsim.distributions.ContinuousDistribution#sample()
*/
@Override
public double sample() {
return location / Math.pow(numGen.nextDouble(), 1 / shape);
}
}

View File

@@ -0,0 +1,95 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* A random number generator based on the Uniform distribution.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class UniformDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The min. */
private final double mag, min;
/**
* Creates new uniform distribution.
*
* @param min minimum value
* @param max maximum value
*/
public UniformDistr(double min, double max) {
if (min >= max) {
throw new IllegalArgumentException("Maximum must be greater than the minimum.");
}
numGen = new Random();
mag = max - min;
this.min = min;
}
/**
* Creates new uniform distribution.
*
* @param min minimum value
* @param max maximum value
* @param seed simulation seed to be used
*/
public UniformDistr(double min, double max, long seed) {
if (min >= max) {
throw new IllegalArgumentException("Maximum must be greater than the minimum.");
}
numGen = new Random(seed);
mag = max - min;
this.min = min;
}
/**
* Generate a new random number.
*
* @return the next random number in the sequence
*/
@Override
public double sample() {
return (numGen.nextDouble() * (mag)) + min;
}
/**
* Generates a new random number based on the number generator and values provided as
* parameters.
*
* @param rd the random number generator
* @param min the minimum value
* @param max the maximum value
* @return the next random number in the sequence
*/
public static double sample(Random rd, double min, double max) {
if (min >= max) {
throw new IllegalArgumentException("Maximum must be greater than the minimum.");
}
return (rd.nextDouble() * (max - min)) + min;
}
/**
* Set the random number generator's seed.
*
* @param seed the new seed for the generator
*/
public void setSeed(long seed) {
numGen.setSeed(seed);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Title: CloudSim Toolkit
* Descripimport java.util.Random;
mulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class WeibullDistr.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class WeibullDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The alpha. */
private final double alpha;
/** The beta. */
private final double beta;
/**
* Instantiates a new weibull distr.
*
* @param seed the seed
* @param alpha the alpha
* @param beta the beta
*/
public WeibullDistr(Random seed, double alpha, double beta) {
if (alpha <= 0.0 || beta <= 0.0) {
throw new IllegalArgumentException("Alpha and beta must be greater than 0.0");
}
numGen = seed;
this.alpha = alpha;
this.beta = beta;
}
/**
* Instantiates a new weibull distr.
*
* @param alpha the alpha
* @param beta the beta
*/
public WeibullDistr(double alpha, double beta) {
if (alpha <= 0.0 || beta <= 0.0) {
throw new IllegalArgumentException("Alpha and beta must be greater than 0.0");
}
numGen = new Random(System.currentTimeMillis());
this.alpha = alpha;
this.beta = beta;
}
/*
* (non-Javadoc)
* @see cloudsim.distributions.ContinuousDistribution#sample()
*/
@Override
public double sample() {
return beta * Math.pow(-Math.log(numGen.nextDouble()), 1 / alpha);
}
}

View File

@@ -0,0 +1,97 @@
/*
* Title: CloudSim Toolkit
* Descripimport java.util.Random;
mulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.distributions;
import java.util.Random;
/**
* The Class ZipfDistr.
*
* @author Marcos Dias de Assuncao
* @since CloudSim Toolkit 1.0
*/
public class ZipfDistr implements ContinuousDistribution {
/** The num gen. */
private final Random numGen;
/** The shape. */
private final double shape;
/** The den. */
private double den;
/**
* Instantiates a new zipf distr.
*
* @param seed the seed
* @param shape the shape
* @param population the population
*/
public ZipfDistr(long seed, double shape, int population) {
if (shape <= 0.0 || population < 1) {
throw new IllegalArgumentException("Mean must be greater than 0.0 and population greater than 0");
}
numGen = new Random(seed);
this.shape = shape;
computeDen(shape, population);
}
/**
* Instantiates a new zipf distr.
*
* @param shape the shape
* @param population the population
*/
public ZipfDistr(double shape, int population) {
if (shape <= 0.0) {
throw new IllegalArgumentException("Mean must be greated than 0.0 and population greater than 0");
}
numGen = new Random(System.currentTimeMillis());
this.shape = shape;
computeDen(shape, population);
}
/**
* Generate a new random number.
*
* @return the next random number in the sequence
*/
@Override
public double sample() {
double variate = numGen.nextDouble();
double num = 1;
double nextNum = 1 + 1 / Math.pow(2, shape);
double j = 3;
while (variate > nextNum / den) {
num = nextNum;
nextNum += 1 / Math.pow(j, shape);
j++;
}
return num / den;
}
/**
* Compute den.
*
* @param shape the shape
* @param population the population
*/
private void computeDen(double shape, int population) {
den = 0.0;
for (int j = 1; j <= population; j++) {
den += 1 / Math.pow(j, shape);
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.lists;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
/**
* CloudletList is a collection of operations on lists of Cloudlets.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class CloudletList {
/**
* Gets the by id.
*
* @param cloudletList the cloudlet list
* @param id the id
* @return the by id
*/
public static <T extends Cloudlet> T getById(List<T> cloudletList, int id) {
for (T cloudlet : cloudletList) {
if (cloudlet.getCloudletId() == id) {
return cloudlet;
}
}
return null;
}
/**
* Returns the position of the cloudlet with that id, if it exists. Otherwise -1.
* @param cloudletList - the list of cloudlets.
* @param id - the id we search for.
* @return - the position of the cloudlet with that id, or -1 otherwise.
*/
public static <T extends Cloudlet> int getPositionById(List<T> cloudletList, int id) {
int i = 0 ;
for (T cloudlet : cloudletList) {
if (cloudlet.getCloudletId() == id) {
return i;
}
i++;
}
return -1;
}
/**
* Sorts the Cloudlets in a list based on their lengths.
*
* @param cloudletList the cloudlet list
* @pre $none
* @post $none
*/
public static <T extends Cloudlet> void sort(List<T> cloudletList) {
Collections.sort(cloudletList, new Comparator<T>() {
/**
* Compares two objects.
*
* @param a the first Object to be compared
* @param b the second Object to be compared
* @return the value 0 if both Objects are numerically equal; a value less than 0 if the
* first Object is numerically less than the second Object; and a value greater
* than 0 if the first Object is numerically greater than the second Object.
* @throws ClassCastException <tt>a</tt> and <tt>b</tt> are expected to be of type
* <tt>Cloudlet</tt>
* @pre a != null
* @pre b != null
* @post $none
*/
@Override
public int compare(T a, T b) throws ClassCastException {
Double cla = Double.valueOf(a.getCloudletTotalLength());
Double clb = Double.valueOf(b.getCloudletTotalLength());
return cla.compareTo(clb);
}
});
}
}

View File

@@ -0,0 +1,148 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.lists;
import java.util.List;
import org.cloudbus.cloudsim.Host;
/**
* HostList is a collection of operations on lists of hosts.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class HostList {
/**
* Gets the Machine object for a particular ID.
*
* @param <T> the generic type
* @param hostList the host list
* @param id the host ID
* @return the Machine object or <tt>null</tt> if no machine exists
* @see gridsim.Machine
* @pre id >= 0
* @post $none
*/
public static <T extends Host> T getById(List<T> hostList, int id) {
for (T host : hostList) {
if (host.getId() == id) {
return host;
}
}
return null;
}
/**
* Gets the total number of PEs for all Machines.
*
* @param <T> the generic type
* @param hostList the host list
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public static <T extends Host> int getNumberOfPes(List<T> hostList) {
int numberOfPes = 0;
for (T host : hostList) {
numberOfPes += host.getPeList().size();
}
return numberOfPes;
}
/**
* Gets the total number of <tt>FREE</tt> or non-busy PEs for all Machines.
*
* @param <T> the generic type
* @param hostList the host list
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public static <T extends Host> int getNumberOfFreePes(List<T> hostList) {
int numberOfFreePes = 0;
for (T host : hostList) {
numberOfFreePes += PeList.getNumberOfFreePes(host.getPeList());
}
return numberOfFreePes;
}
/**
* Gets the total number of <tt>BUSY</tt> PEs for all Machines.
*
* @param <T> the generic type
* @param hostList the host list
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public static <T extends Host> int getNumberOfBusyPes(List<T> hostList) {
int numberOfBusyPes = 0;
for (T host : hostList) {
numberOfBusyPes += PeList.getNumberOfBusyPes(host.getPeList());
}
return numberOfBusyPes;
}
/**
* Gets a Machine with free Pe.
*
* @param <T> the generic type
* @param hostList the host list
* @return a machine object or <tt>null</tt> if not found
* @pre $none
* @post $none
*/
public static <T extends Host> T getHostWithFreePe(List<T> hostList) {
return getHostWithFreePe(hostList, 1);
}
/**
* Gets a Machine with a specified number of free Pe.
*
* @param <T> the generic type
* @param hostList the host list
* @param pesNumber the pes number
* @return a machine object or <tt>null</tt> if not found
* @pre $none
* @post $none
*/
public static <T extends Host> T getHostWithFreePe(List<T> hostList, int pesNumber) {
for (T host : hostList) {
if (PeList.getNumberOfFreePes(host.getPeList()) >= pesNumber) {
return host;
}
}
return null;
}
/**
* Sets the particular Pe status on a Machine.
*
* @param <T> the generic type
* @param hostList the host list
* @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
* @param hostId the host id
* @param peId the pe id
* @return <tt>true</tt> if the Pe status has changed, <tt>false</tt> otherwise (Machine id or
* Pe id might not be exist)
* @pre machineID >= 0
* @pre peID >= 0
* @post $none
*/
public static <T extends Host> boolean setPeStatus(List<T> hostList, int status, int hostId, int peId) {
T host = getById(hostList, hostId);
if (host == null) {
return false;
}
return host.setPeStatus(peId, status);
}
}

View File

@@ -0,0 +1,230 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.lists;
import java.util.List;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Vm;
/**
* PeList is a collection of operations on lists of PEs.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PeList {
/**
* Gets MIPS Rating for a specified Pe ID.
*
* @param id the Pe ID
* @param peList the pe list
* @return the MIPS rating if exists, otherwise returns -1
* @pre id >= 0
* @post $none
*/
public static <T extends Pe> Pe getById(List<T> peList, int id) {
for (Pe pe : peList) {
if (pe.getId() == id) {
return pe;
}
}
return null;
}
/**
* Gets MIPS Rating for a specified Pe ID.
*
* @param id the Pe ID
* @param peList the pe list
* @return the MIPS rating if exists, otherwise returns -1
* @pre id >= 0
* @post $none
*/
public static <T extends Pe> int getMips(List<T> peList, int id) {
Pe pe = getById(peList, id);
if (pe != null) {
return pe.getMips();
}
return -1;
}
/**
* Gets total MIPS Rating for all PEs.
*
* @param peList the pe list
* @return the total MIPS Rating
* @pre $none
* @post $none
*/
public static <T extends Pe> int getTotalMips(List<T> peList) {
int totalMips = 0;
for (Pe pe : peList) {
totalMips += pe.getMips();
}
return totalMips;
}
/**
* Gets the max utilization among by all PEs.
*
* @param peList the pe list
* @return the utilization
*/
public static <T extends Pe> double getMaxUtilization(List<T> peList) {
double maxUtilization = 0;
for (Pe pe : peList) {
double utilization = pe.getPeProvisioner().getUtilization();
if (utilization > maxUtilization) {
maxUtilization = utilization;
}
}
return maxUtilization;
}
/**
* Gets the max utilization among by all PEs allocated to the VM.
*
* @param vm the vm
* @param peList the pe list
* @return the utilization
*/
public static <T extends Pe> double getMaxUtilizationAmongVmsPes(List<T> peList, Vm vm) {
double maxUtilization = 0;
for (Pe pe : peList) {
if (pe.getPeProvisioner().getAllocatedMipsForVm(vm) == null) {
continue;
}
double utilization = pe.getPeProvisioner().getUtilization();
if (utilization > maxUtilization) {
maxUtilization = utilization;
}
}
return maxUtilization;
}
/**
* Gets a Pe ID which is FREE.
*
* @param peList the pe list
* @return a Pe ID if it is FREE, otherwise returns -1
* @pre $none
* @post $none
*/
public static <T extends Pe> Pe getFreePe(List<T> peList) {
for (Pe pe : peList) {
if (pe.getStatus() == Pe.FREE) {
return pe;
}
}
return null;
}
/**
* Gets the number of <tt>FREE</tt> or non-busy Pe.
*
* @param peList the pe list
* @return number of Pe
* @pre $none
* @post $result >= 0
*/
public static <T extends Pe> int getNumberOfFreePes(List<T> peList) {
int cnt = 0;
for (Pe pe : peList) {
if (pe.getStatus() == Pe.FREE) {
cnt++;
}
}
return cnt;
}
/**
* Sets the Pe status.
*
* @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
* @param id the id
* @param peList the pe list
* @return <tt>true</tt> if the Pe status has been changed, <tt>false</tt> otherwise (Pe id might
* not be exist)
* @pre peID >= 0
* @post $none
*/
public static <T extends Pe> boolean setPeStatus(List<T> peList, int id, int status) {
Pe pe = getById(peList, id);
if (pe != null) {
pe.setStatus(status);
return true;
}
return false;
}
/**
* Gets the number of <tt>BUSY</tt> Pe.
*
* @param peList the pe list
* @return number of Pe
* @pre $none
* @post $result >= 0
*/
public static <T extends Pe> int getNumberOfBusyPes(List<T> peList) {
int cnt = 0;
for (Pe pe : peList) {
if (pe.getStatus() == Pe.BUSY) {
cnt++;
}
}
return cnt;
}
/**
* Sets the status of PEs of this machine to FAILED. NOTE: <tt>resName</tt> and
* <tt>machineID</tt> are used for debugging purposes, which is <b>ON</b> by default. Use
* {@link #setStatusFailed(boolean)} if you do not want this information.
*
* @param resName the name of the resource
* @param hostId the id of this machine
* @param failed the new value for the "failed" parameter
*/
public static <T extends Pe> void setStatusFailed(
List<T> peList,
String resName,
int hostId,
boolean failed) {
String status = null;
if (failed) {
status = "FAILED";
} else {
status = "WORKING";
}
Log.printLine(resName + " - Machine: " + hostId + " is " + status);
setStatusFailed(peList, failed);
}
/**
* Sets the status of PEs of this machine to FAILED.
*
* @param failed the new value for the "failed" parameter
* @param peList the pe list
*/
public static <T extends Pe> void setStatusFailed(List<T> peList, boolean failed) {
// a loop to set the status of all the PEs in this machine
for (Pe pe : peList) {
if (failed) {
pe.setStatus(Pe.FAILED);
} else {
pe.setStatus(Pe.FREE);
}
}
}
}

View File

@@ -0,0 +1,108 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.lists;
import java.util.List;
import org.cloudbus.cloudsim.ResCloudlet;
/**
* ResCloudletList is a collection of operations on lists of ResCloudlets.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class ResCloudletList {
/**
* Returns a given Cloudlet. This method needs a combination of Cloudlet Id and User Id because
* each Cloud Users might have exactly same Cloudlet Ids.
*
* @param cloudletId a Cloudlet Id
* @param userId an User Id
* @param list the list
* @return the Cloudlet.
* @throws IndexOutOfBoundsException - if a Cloudlet with specified Id and user id is not in the
* list.
* @pre cloudletId >= 0
* @pre userId >= 0
* @post $none
*/
public static <T extends ResCloudlet> ResCloudlet getByIdAndUserId(
List<T> list,
int cloudletId,
int userId) {
for (T rcl : list) {
if (rcl.getCloudletId() == cloudletId && rcl.getUserId() == userId) {
return rcl;
}
}
return null;
}
/**
* Finds the index of a Cloudlet inside the list. This method needs a combination of Cloudlet Id
* and User Id because each Cloud User might have exactly the same Cloudlet Id.
*
* @param cloudletId a Cloudlet Id
* @param userId an User Id
* @param list the list
* @return the index in this list of the first occurrence of the specified Cloudlet, or
* <code>-1</code> if the list does not contain this Cloudlet.
* @pre cloudletId >= 0
* @pre userId >= 0
* @post $none
*/
public static <T extends ResCloudlet> int indexOf(List<T> list, int cloudletId, int userId) {
int i = 0;
for (T rcl : list) {
if (rcl.getCloudletId() == cloudletId && rcl.getUserId() == userId) {
return i;
}
i++;
}
return -1;
}
/**
* Move a ResCloudlet object from this linked-list into a specified one.
*
* @param listFrom the list from
* @param listTo the list to
* @param cloudlet the cloudlet
* @return <b>true</b> if the moving operation successful, otherwise return <b>false</b>
* @pre obj != null
* @pre list != null
* @post $result == true || $result == false
*/
public static <T extends ResCloudlet> boolean move(List<T> listFrom, List<T> listTo, T cloudlet) {
if (listFrom.remove(cloudlet)) {
listTo.add(cloudlet);
return true;
}
return false;
}
/**
* Returns the position of the cloudlet with that id, if it exists. Otherwise -1.
* @param cloudletList - the list of cloudlets.
* @param id - the id we search for.
* @return - the position of the cloudlet with that id, or -1 otherwise.
*/
public static <T extends ResCloudlet> int getPositionById(List<T> cloudletList, int id) {
int i = 0 ;
for (T cloudlet : cloudletList) {
if (cloudlet.getCloudletId() == id) {
return i;
}
i++;
}
return -1;
}
}

View File

@@ -0,0 +1,60 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.lists;
import java.util.List;
import org.cloudbus.cloudsim.Vm;
/**
* VmList is a collection of operations on lists of VMs.
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class VmList {
/**
* Return a reference to a Vm object from its ID.
*
* @param id ID of required VM
* @param vmList the vm list
* @return Vm with the given ID, $null if not found
* @pre $none
* @post $none
*/
public static <T extends Vm> T getById(List<T> vmList, int id) {
for (T vm : vmList) {
if (vm.getId() == id) {
return vm;
}
}
return null;
}
/**
* Return a reference to a Vm object from its ID and user ID.
*
* @param id ID of required VM
* @param userId the user ID
* @param vmList the vm list
* @return Vm with the given ID, $null if not found
* @pre $none
* @post $none
*/
public static <T extends Vm> T getByIdAndUserId(List<T> vmList, int id, int userId) {
for (T vm : vmList) {
if (vm.getId() == id && vm.getUserId() == userId) {
return vm;
}
}
return null;
}
}

View File

@@ -0,0 +1,144 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
import java.util.Iterator;
/**
* This class represents an delay-topology storing every distance between connected nodes
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public class DelayMatrix_Float {
/**
* matrix holding delay information between any two nodes
*/
protected float[][] mDelayMatrix = null;
/**
* number of nodes in the distance-aware-topology
*/
protected int mTotalNodeNum = 0;
/**
* private constructor to ensure that only an correct initialized delay-matrix could be created
*/
@SuppressWarnings("unused")
private DelayMatrix_Float() {
};
/**
* this constructor creates an correct initialized Float-Delay-Matrix
*
* @param graph the topological graph as source-information
* @param directed true if an directed matrix should be computed, false otherwise
*/
public DelayMatrix_Float(TopologicalGraph graph, boolean directed) {
// lets preinitialize the Delay-Matrix
createDelayMatrix(graph, directed);
// now its time to calculate all possible connection-delays
calculateShortestPath();
}
/**
* @param srcID the id of the source-node
* @param destID the id of the destination-node
* @return the delay-count between the given two nodes
*/
public float getDelay(int srcID, int destID) {
// check the nodeIDs against internal array-boundarys
if (srcID > mTotalNodeNum || destID > mTotalNodeNum) {
throw new ArrayIndexOutOfBoundsException("srcID or destID is higher than highest stored node-ID!");
}
return mDelayMatrix[srcID][destID];
}
/**
* creates all internal necessary network-distance structures from the given graph for
* similarity we assume all kommunikation-distances are symmetrical thus leads to an undirected
* network
*
* @param graph this graph contains all node and link information
* @param directed defines to preinitialize an directed or undirected Delay-Matrix!
*/
private void createDelayMatrix(TopologicalGraph graph, boolean directed) {
// number of nodes inside the network
mTotalNodeNum = graph.getNumberOfNodes();
mDelayMatrix = new float[mTotalNodeNum][mTotalNodeNum];
// cleanup the complete distance-matrix with "0"s
for (int row = 0; row < mTotalNodeNum; ++row) {
for (int col = 0; col < mTotalNodeNum; ++col) {
mDelayMatrix[row][col] = Float.MAX_VALUE;
}
}
Iterator<TopologicalLink> itr = graph.getLinkIterator();
TopologicalLink edge;
while (itr.hasNext()) {
edge = itr.next();
mDelayMatrix[edge.getSrcNodeID()][edge.getDestNodeID()] = edge.getLinkDelay();
if (!directed) {
// according to aproximity of symmetry to all kommunication-paths
mDelayMatrix[edge.getDestNodeID()][edge.getSrcNodeID()] = edge.getLinkDelay();
}
}
}
/**
* just calculates all pairs shortest paths
*/
private void calculateShortestPath() {
FloydWarshall_Float floyd = new FloydWarshall_Float();
floyd.initialize(mTotalNodeNum);
mDelayMatrix = floyd.allPairsShortestPaths(mDelayMatrix);
}
/**
* this method just creates an string-output from the internal structures... eg. printsout the
* delay-matrix...
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("just a simple printout of the distance-aware-topology-class\n");
buffer.append("delay-matrix is:\n");
for (int column = 0; column < mTotalNodeNum; ++column) {
buffer.append("\t" + column);
}
for (int row = 0; row < mTotalNodeNum; ++row) {
buffer.append("\n" + row);
for (int col = 0; col < mTotalNodeNum; ++col) {
if (mDelayMatrix[row][col] == Float.MAX_VALUE) {
buffer.append("\t" + "-");
} else {
buffer.append("\t" + mDelayMatrix[row][col]);
}
}
}
return buffer.toString();
}
}

View File

@@ -0,0 +1,193 @@
/*
* @(#)FloydWarshall.java ver 1.2 6/20/2005
*
* Modified by Weishuai Yang (wyang@cs.binghamton.edu).
* Originally written by Rahul Simha
*
*/
package org.cloudbus.cloudsim.network;
/**
* FloydWarshall algorithm to calculate all pairs delay and predecessor matrix.
*
* @author Rahul Simha
* @author Weishuai Yang
* @version 1.2, 6/20/2005
* @since CloudSim Toolkit 1.0
*/
public class FloydWarshall_Float {
/**
* Number of vertices (when initialized)
*/
private int numVertices;
// /**
// * The adjacency matrix (given as input),
// * here I use float rather than double to save memory,
// * since there won't be a lot of spilting for delay,
// * and float is accurate enough.
// */
// private float[][] adjMatrix;
/**
* Matrices used in dynamic programming
*/
private float[][] Dk, Dk_minus_one;
/**
* Matrices used in dynamic programming
*/
private int[][] Pk, Pk_minus_one;
/**
* initialization matrix
*
* @param numVertices number of nodes
*/
public void initialize(int numVertices) {
this.numVertices = numVertices;
// Initialize Dk matrices.
Dk = new float[numVertices][];
Dk_minus_one = new float[numVertices][];
for (int i = 0; i < numVertices; i++) {
Dk[i] = new float[numVertices];
Dk_minus_one[i] = new float[numVertices];
}
// Initialize Pk matrices.
Pk = new int[numVertices][];
Pk_minus_one = new int[numVertices][];
for (int i = 0; i < numVertices; i++) {
Pk[i] = new int[numVertices];
Pk_minus_one[i] = new int[numVertices];
}
}
/**
* calculates all pairs delay
*
* @param adjMatrix original delay matrix
* @return all pairs delay matrix
*/
public float[][] allPairsShortestPaths(float[][] adjMatrix) {
// Dk_minus_one = weights when k = -1
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
if (adjMatrix[i][j] != 0) {
Dk_minus_one[i][j] = adjMatrix[i][j];
Pk_minus_one[i][j] = i;
} else {
Dk_minus_one[i][j] = Float.MAX_VALUE;
Pk_minus_one[i][j] = -1;
}
// NOTE: we have set the value to infinity and will exploit
// this to avoid a comparison.
}
}
// Now iterate over k.
for (int k = 0; k < numVertices; k++) {
// Compute Dk[i][j], for each i,j
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
if (i != j) {
// D_k[i][j] = min ( D_k-1[i][j], D_k-1[i][k] + D_k-1[k][j].
if (Dk_minus_one[i][j] <= Dk_minus_one[i][k] + Dk_minus_one[k][j]) {
Dk[i][j] = Dk_minus_one[i][j];
Pk[i][j] = Pk_minus_one[i][j];
} else {
Dk[i][j] = Dk_minus_one[i][k] + Dk_minus_one[k][j];
Pk[i][j] = Pk_minus_one[k][j];
}
} else {
Pk[i][j] = -1;
}
}
}
// Now store current Dk into D_k-1
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
Dk_minus_one[i][j] = Dk[i][j];
Pk_minus_one[i][j] = Pk[i][j];
}
}
} // end-outermost-for
return Dk;
}
/**
* gets predecessor matrix
*
* @return predecessor matrix
*/
public int[][] getPK() {
return Pk;
}
/*
public static void main (String[] argv)
{
// A test case.
*
double[][] adjMatrix = {
{0, 1, 0, 0, 1},
{1, 0, 1, 3, 0},
{0, 1, 0, 2, 0},
{0, 3, 2, 0, 1},
{1, 0, 0, 1, 0},
};
int n = adjMatrix.length;
FloydWarshall fwAlg = new FloydWarshall ();
fwAlg.initialize (n);
adjMatrix=fwAlg.allPairsShortestPaths (adjMatrix);
//debug begin
StringBuffer s0=new StringBuffer("Delay Information before floydwarshall:\n");
for(int i=0;i<n;i++){
s0.append("Node "+i+" to others:");
for(int j=0;j<n;j++){
s0.append(LogFormatter.sprintf(" % 6.1f ", adjMatrix[i][j]));
}
s0.append("\n");
}
Log.printLine(""+s0);
int[][] Pk=fwAlg.getPK();
Log.printLine("Path information");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
Log.print("From "+i+" to "+j+": ");
int pre=Pk[i][j];
while((pre!=-1)&&(pre!=i)){
Log.print(" <- "+ pre);
pre=Pk[i][pre];
if((pre==-1)||(pre==i))
Log.print(" <- "+ pre);
}
Log.printLine("\n");
}
}
}
*/
}

View File

@@ -0,0 +1,204 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* This class is just an file-reader for the special brite-format! the brite-file is structured as
* followed: Node-section: NodeID, xpos, ypos, indegree, outdegree, ASid, type(router/AS)
* Edge-section: EdgeID, fromNode, toNode, euclideanLength, linkDelay, linkBandwith, AS_from, AS_to,
* type
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public class GraphReaderBrite implements GraphReaderIF {
private static final int PARSE_NOTHING = 0;
private static final int PARSE_NODES = 1;
private static final int PARSE_EDGES = 2;
private int state = PARSE_NOTHING;
private TopologicalGraph graph = null;
/**
* this method just reads the file and creates an TopologicalGraph object
*
* @param filename name of the file to read
* @return created TopologicalGraph
* @throws IOException
*/
@Override
public TopologicalGraph readGraphFile(String filename) throws IOException {
graph = new TopologicalGraph();
// lets read the file
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String lineSep = System.getProperty("line.separator");
String nextLine = null;
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine);
//
// note:
// BufferedReader strips the EOL character.
//
sb.append(lineSep);
// functionality to diferentiate between all the parsing-states
// state that should just find the start of node-declaration
if (state == PARSE_NOTHING) {
if (nextLine.contains("Nodes:")) {
// Log.printLine("found start of Nodes... switch to parse nodes!");
state = PARSE_NODES;
}
}
// the state to retrieve all node-information
else if (state == PARSE_NODES) {
// perform the parsing of this node-line
parseNodeString(nextLine);
}
// the state to retrieve all edges-information
else if (state == PARSE_EDGES) {
parseEdgesString(nextLine);
}
}
br.close();
// Log.printLine("read file successfully...");
// Log.printLine(sb.toString());
return graph;
}
private void parseNodeString(String nodeLine) {
StringTokenizer tokenizer = new StringTokenizer(nodeLine);
// number of node parameters to parse (counts at linestart)
int parameters = 3;
// first test to step to the next parsing-state (edges)
if (nodeLine.contains("Edges:")) {
// Log.printLine("found start of Edges... switch to parse edges!");
state = PARSE_EDGES;
return;
}
// test against an empty line
if (!tokenizer.hasMoreElements()) {
// Log.printLine("this line contains no tokens...");
return;
}
// parse this string-line to read all node-parameters
// NodeID, xpos, ypos, indegree, outdegree, ASid, type(router/AS)
int nodeID = 0;
String nodeLabel = "";
int xPos = 0;
int yPos = 0;
for (int actualParam = 0; tokenizer.hasMoreElements() && actualParam < parameters; actualParam++) {
String token = tokenizer.nextToken();
switch (actualParam) {
case 0: // Log.printLine("nodeID: "+token);
// Log.printLine("nodeLabel: "+token);
nodeID = Integer.valueOf(token);
nodeLabel = Integer.toString(nodeID);
break;
case 1: // Log.printLine("x-Pos: "+token);
xPos = Integer.valueOf(token);
break;
case 2: // Log.printLine("y-Pos: "+token);
yPos = Integer.valueOf(token);
break;
}
}
// instanciate an new node-object with previous parsed parameters
TopologicalNode topoNode = new TopologicalNode(nodeID, nodeLabel, xPos, yPos);
graph.addNode(topoNode);
}// parseNodeString-END
private void parseEdgesString(String nodeLine) {
StringTokenizer tokenizer = new StringTokenizer(nodeLine);
// number of node parameters to parse (counts at linestart)
int parameters = 6;
// test against an empty line
if (!tokenizer.hasMoreElements()) {
// Log.printLine("this line contains no tokens...");
return;
}
// parse this string-line to read all node-parameters
// EdgeID, fromNode, toNode, euclideanLength, linkDelay, linkBandwith, AS_from, AS_to, type
// int edgeID = 0;
int fromNode = 0;
int toNode = 0;
// float euclideanLength = 0;
float linkDelay = 0;
int linkBandwith = 0;
for (int actualParam = 0; tokenizer.hasMoreElements() && actualParam < parameters; actualParam++) {
String token = tokenizer.nextToken();
switch (actualParam) {
case 0: // Log.printLine("edgeID: "+token);
// edgeID = Integer.valueOf(token);
break;
case 1: // Log.printLine("fromNode: "+token);
fromNode = Integer.valueOf(token);
break;
case 2: // Log.printLine("toNode: "+token);
toNode = Integer.valueOf(token);
break;
case 3: // Log.printLine("euclideanLength: "+token);
// euclideanLength = Float.valueOf(token);
break;
case 4: // Log.printLine("linkDelay: "+token);
linkDelay = Float.valueOf(token);
break;
case 5: // Log.printLine("linkBandwith: "+token);
linkBandwith = Float.valueOf(token).intValue();
break;
}// switch-END
}// for-END
graph.addLink(new TopologicalLink(fromNode, toNode, linkDelay, linkBandwith));
}
}

View File

@@ -0,0 +1,30 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
import java.io.IOException;
/**
* This interface abstracts an reader for different graph-file-formats
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public interface GraphReaderIF {
/**
* this method just reads the file and creates an TopologicalGraph object
*
* @param filename name of the file to read
* @return created TopologicalGraph
* @throws IOException
*/
TopologicalGraph readGraphFile(String filename) throws IOException;
}

View File

@@ -0,0 +1,113 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* This class represents an graph containing nodes and edges, used for input with an network-layer
* Graphical-Output Restricions! EdgeColors: GraphicalProperties.getColorEdge NodeColors:
* GraphicalProperties.getColorNode
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public class TopologicalGraph {
private List<TopologicalLink> linkList = null;
private List<TopologicalNode> nodeList = null;
/**
* just the constructor to create an empty graph-object
*/
public TopologicalGraph() {
linkList = new LinkedList<TopologicalLink>();
nodeList = new LinkedList<TopologicalNode>();
}
/**
* adds an link between two topological nodes
*
* @param edge the topological link
*/
public void addLink(TopologicalLink edge) {
linkList.add(edge);
}
/**
* adds an Topological Node to this graph
*
* @param node the topological node to add
*/
public void addNode(TopologicalNode node) {
nodeList.add(node);
}
/**
* returns the number of nodes contained inside the topological-graph
*
* @return number of nodes
*/
public int getNumberOfNodes() {
return nodeList.size();
}
/**
* returns the number of links contained inside the topological-graph
*
* @return number of links
*/
public int getNumberOfLinks() {
return linkList.size();
}
/**
* return an iterator through all network-graph links
*
* @return the iterator throug all links
*/
public Iterator<TopologicalLink> getLinkIterator() {
return linkList.iterator();
}
/**
* returns an iterator through all network-graph nodes
*
* @return the iterator through all nodes
*/
public Iterator<TopologicalNode> getNodeIterator() {
return nodeList.iterator();
}
/**
* prints out all internal node and link information
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("topological-node-information: \n");
for (TopologicalNode node : nodeList) {
buffer.append(node.getNodeID() + " | x is: " + node.getCoordinateX() + " y is: "
+ node.getCoordinateY() + "\n");
}
buffer.append("\n\n node-link-information:\n");
for (TopologicalLink link : linkList) {
buffer.append("from: " + link.getSrcNodeID() + " to: " + link.getDestNodeID() + " delay: "
+ link.getLinkDelay() + "\n");
}
return buffer.toString();
}
}

View File

@@ -0,0 +1,83 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
/**
* This class represents an link (edge) from an graph
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public class TopologicalLink {
/**
* id of the link src node-id
*/
private int srcNodeID = 0;
/**
* id of the link dest node-id
*/
private int destNodeID = 0;
/**
* representing the link-delay of the connection
*/
private float linkDelay = 0;
private float linkBw = 0;
/**
* creates an new link-object
*/
public TopologicalLink(int srcNode, int destNode, float delay, float bw) {
// lets initialize all internal attributes
linkDelay = delay;
srcNodeID = srcNode;
destNodeID = destNode;
linkBw = bw;
}
/**
* returns the node-ID from the SrcNode
*
* @return nodeID
*/
public int getSrcNodeID() {
return srcNodeID;
}
/**
* return the node-ID from the DestNode
*
* @return nodeID
*/
public int getDestNodeID() {
return destNodeID;
}
/**
* return the link-delay of the defined linke
*
* @return the delay-amount
*/
public float getLinkDelay() {
return linkDelay;
}
/**
* return the link-bw of the defined linke
*
* @return the bw
*/
public float getLinkBw() {
return linkBw;
}
}

View File

@@ -0,0 +1,104 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network;
/**
* Just represents an topological network node retrieves its information from an
* topological-generated file (eg. topology-generator)
*
* @author Thomas Hohnstein
* @since CloudSim Toolkit 1.0
*/
public class TopologicalNode {
/**
* its the nodes-ID inside this network
*/
private int nodeID = 0;
/**
* describes the nodes-name inside the network
*/
private String nodeName = null;
/**
* representing the x an y world-coordinates
*/
private int worldX = 0;
private int worldY = 0;
/**
* constructs an new node
*/
public TopologicalNode(int nodeID) {
// lets initialize all private class attributes
this.nodeID = nodeID;
nodeName = String.valueOf(nodeID);
}
/**
* constructs an new node including world-coordinates
*/
public TopologicalNode(int nodeID, int x, int y) {
// lets initialize all private class attributes
this.nodeID = nodeID;
nodeName = String.valueOf(nodeID);
worldX = x;
worldY = y;
}
/**
* constructs an new node including world-coordinates and the nodeName
*/
public TopologicalNode(int nodeID, String nodeName, int x, int y) {
// lets initialize all private class attributes
this.nodeID = nodeID;
this.nodeName = nodeName;
worldX = x;
worldY = y;
}
/**
* delivers the nodes id
*
* @return just the nodeID
*/
public int getNodeID() {
return nodeID;
}
/**
* delivers the name of the node
*
* @return name of the node
*/
public String getNodeLabel() {
return nodeName;
}
/**
* returns the x coordinate of this network-node
*
* @return the x coordinate
*/
public int getCoordinateX() {
return worldX;
}
/**
* returns the y coordinate of this network-node
*
* @return the y coordinate
*/
public int getCoordinateY() {
return worldY;
}
}

View File

@@ -0,0 +1,137 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
/**
* This class allows to simulate aggregate switch for Datacenter network. It interacts with other
* switches in order to exchange packets.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class AggregateSwitch extends Switch {
/**
* Constructor for Aggregate Switch We have to specify switches that are connected to its
* downlink and uplink ports, and corresponding bandwidths
*
* @param name Name of the switch
* @param level At which level switch is with respect to hosts.
* @param dc Pointer to Datacenter
*/
public AggregateSwitch(String name, int level, NetworkDatacenter dc) {
super(name, level, dc);
downlinkswitchpktlist = new HashMap<Integer, List<NetworkPacket>>();
uplinkswitchpktlist = new HashMap<Integer, List<NetworkPacket>>();
uplinkbandwidth = NetworkConstants.BandWidthAggRoot;
downlinkbandwidth = NetworkConstants.BandWidthEdgeAgg;
latency = NetworkConstants.SwitchingDelayAgg;
numport = NetworkConstants.AggSwitchPort;
uplinkswitches = new ArrayList<Switch>();
downlinkswitches = new ArrayList<Switch>();
}
/**
* Send Packet to switch connected through a downlink port
*
* @param ev Event/packet to process
*/
@Override
protected void processpacket_down(SimEvent ev) {
// packet coming from up level router.
// has to send downward
// check which switch to forward to
// add packet in the switch list
// add packet in the host list
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), latency, CloudSimTags.Network_Event_send);
if (level == NetworkConstants.Agg_LEVEL) {
// packet is coming from root so need to be sent to edgelevel swich
// find the id for edgelevel switch
int switchid = dc.VmToSwitchid.get(recvVMid);
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(switchid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(switchid, pktlist);
}
pktlist.add(hspkt);
return;
}
}
/**
* Send Packet to switch connected through a uplink port
*
* @param ev Event/packet to process
*/
@Override
protected void processpacket_up(SimEvent ev) {
// packet coming from down level router.
// has to send up
// check which switch to forward to
// add packet in the switch list
//
// int src=ev.getSource();
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), switching_delay, CloudSimTags.Network_Event_send);
if (level == NetworkConstants.Agg_LEVEL) {
// packet is coming from edge level router so need to be sent to
// either root or another edge level swich
// find the id for edgelevel switch
int switchid = dc.VmToSwitchid.get(recvVMid);
boolean flagtoswtich = false;
for (Switch sw : downlinkswitches) {
if (switchid == sw.getId()) {
flagtoswtich = true;
}
}
if (flagtoswtich) {
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(switchid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(switchid, pktlist);
}
pktlist.add(hspkt);
} else// send to up
{
Switch sw = uplinkswitches.get(0);
List<NetworkPacket> pktlist = uplinkswitchpktlist.get(sw.getId());
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
uplinkswitchpktlist.put(sw.getId(), pktlist);
}
pktlist.add(hspkt);
}
}
}
}

View File

@@ -0,0 +1,100 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* AppCloudlet class represents an application which user submit for execution within datacenter. It
* consist of several networkClouds.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class AppCloudlet {
public static final int APP_MC = 1;
public static final int APP_Workflow = 3;
public AppCloudlet(int type, int appID, double deadline, int numbervm, int userId) {
super();
this.type = type;
this.appID = appID;
this.deadline = deadline;
this.numbervm = numbervm;
this.userId = userId;
clist = new ArrayList<NetworkCloudlet>();
}
public int type;
public int appID;
public ArrayList<NetworkCloudlet> clist;
public double deadline;
public double accuracy;
public int numbervm;
public int userId;
public double exeTime;
public int requestclass;
/**
* An example of creating APPcloudlet
*
* @param vmIdList VMs where Cloudlet will be executed
*/
public void createCloudletList(List<Integer> vmIdList) {
for (int i = 0; i < numbervm; i++) {
long length = 4;
long fileSize = 300;
long outputSize = 300;
long memory = 256;
int pesNumber = 4;
UtilizationModel utilizationModel = new UtilizationModelFull();
// HPCCloudlet cl=new HPCCloudlet();
NetworkCloudlet cl = new NetworkCloudlet(
NetworkConstants.currentCloudletId,
length,
pesNumber,
fileSize,
outputSize,
memory,
utilizationModel,
utilizationModel,
utilizationModel);
// setting the owner of these Cloudlets
NetworkConstants.currentCloudletId++;
cl.setUserId(userId);
cl.submittime = CloudSim.clock();
cl.currStagenum = -1;
clist.add(cl);
}
// based on type
}
}

View File

@@ -0,0 +1,160 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
/**
* This class allows to simulate Edge switch for Datacenter network. It interacts with other
* switches in order to exchange packets.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class EdgeSwitch extends Switch {
/**
* Constructor for Edge Switch We have to specify switches that are connected to its downlink
* and uplink ports, and corresponding bandwidths. In this switch downlink ports are connected
* to hosts not to a switch.
*
* @param name Name of the switch
* @param level At which level switch is with respect to hosts.
* @param dc Pointer to Datacenter
*/
public EdgeSwitch(String name, int level, NetworkDatacenter dc) {
super(name, level, dc);
hostlist = new HashMap<Integer, NetworkHost>();
uplinkswitchpktlist = new HashMap<Integer, List<NetworkPacket>>();
packetTohost = new HashMap<Integer, List<NetworkPacket>>();
uplinkbandwidth = NetworkConstants.BandWidthEdgeAgg;
downlinkbandwidth = NetworkConstants.BandWidthEdgeHost;
switching_delay = NetworkConstants.SwitchingDelayEdge;
numport = NetworkConstants.EdgeSwitchPort;
uplinkswitches = new ArrayList<Switch>();
}
/**
* Send Packet to switch connected through a uplink port
*
* @param ev Event/packet to process
*/
@Override
protected void processpacket_up(SimEvent ev) {
// packet coming from down level router/host.
// has to send up
// check which switch to forward to
// add packet in the switch list
//
// int src=ev.getSource();
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), switching_delay, CloudSimTags.Network_Event_send);
// packet is recieved from host
// packet is to be sent to aggregate level or to another host in the same level
int hostid = dc.VmtoHostlist.get(recvVMid);
NetworkHost hs = hostlist.get(hostid);
hspkt.recieverhostid = hostid;
// packet needs to go to a host which is connected directly to switch
if (hs != null) {
// packet to be sent to host connected to the switch
List<NetworkPacket> pktlist = packetTohost.get(hostid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
packetTohost.put(hostid, pktlist);
}
pktlist.add(hspkt);
return;
}
// otherwise
// packet is to be sent to upper switch
// ASSUMPTION EACH EDGE is Connected to one aggregate level switch
// if there are more than one Aggregate level switch one need to modify following code
Switch sw = uplinkswitches.get(0);
List<NetworkPacket> pktlist = uplinkswitchpktlist.get(sw.getId());
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
uplinkswitchpktlist.put(sw.getId(), pktlist);
}
pktlist.add(hspkt);
return;
}
/**
* Send Packet to hosts connected to the switch
*
* @param ev Event/packet to process
*/
@Override
protected void processpacketforward(SimEvent ev) {
// search for the host and packets..send to them
if (uplinkswitchpktlist != null) {
for (Entry<Integer, List<NetworkPacket>> es : uplinkswitchpktlist.entrySet()) {
int tosend = es.getKey();
List<NetworkPacket> hspktlist = es.getValue();
if (!hspktlist.isEmpty()) {
// sharing bandwidth between packets
double avband = uplinkbandwidth / hspktlist.size();
Iterator<NetworkPacket> it = hspktlist.iterator();
while (it.hasNext()) {
NetworkPacket hspkt = it.next();
double delay = 1000 * hspkt.pkt.data / avband;
this.send(tosend, delay, CloudSimTags.Network_Event_UP, hspkt);
}
hspktlist.clear();
}
}
}
if (packetTohost != null) {
for (Entry<Integer, List<NetworkPacket>> es : packetTohost.entrySet()) {
List<NetworkPacket> hspktlist = es.getValue();
if (!hspktlist.isEmpty()) {
double avband = downlinkbandwidth / hspktlist.size();
Iterator<NetworkPacket> it = hspktlist.iterator();
while (it.hasNext()) {
NetworkPacket hspkt = it.next();
// hspkt.recieverhostid=tosend;
// hs.packetrecieved.add(hspkt);
this.send(getId(), hspkt.pkt.data / avband, CloudSimTags.Network_Event_Host, hspkt);
}
hspktlist.clear();
}
}
}
// or to switch at next level.
// clear the list
}
}

View File

@@ -0,0 +1,57 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
/**
* HostPacket represents the packet that travels through the virtual network with a Host. It
* contains information about cloudlets which are communicating
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class HostPacket {
public HostPacket(
int sender,
int reciever,
double data,
double sendtime,
double recievetime,
int vsnd,
int vrvd) {
super();
this.sender = sender;
this.reciever = reciever;
this.data = data;
this.sendtime = sendtime;
this.recievetime = recievetime;
virtualrecvid = vrvd;
virtualsendid = vsnd;
}
int sender;
int virtualrecvid;
int virtualsendid;
int reciever;
double data;
double sendtime;
double recievetime;
}

View File

@@ -0,0 +1,689 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.distributions.UniformDistr;
import org.cloudbus.cloudsim.lists.VmList;
/**
* NetDatacentreBroker represents a broker acting on behalf of Datacenter provider. It hides VM
* management, as vm creation, submission of cloudlets to this VMs and destruction of VMs. NOTE- It
* is an example only. It work on behalf of a provider not for users. One has to implement
* interaction with user broker to this broker.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class NetDatacenterBroker extends SimEntity {
// TODO: remove unnecessary variables
/** The vm list. */
private List<? extends Vm> vmList;
/** The vms created list. */
private List<? extends Vm> vmsCreatedList;
/** The cloudlet list. */
private List<? extends NetworkCloudlet> cloudletList;
private List<? extends AppCloudlet> appCloudletList;
/** The Appcloudlet submitted list. */
private final Map<Integer, Integer> appCloudletRecieved;
private List<? extends Cloudlet> cloudletSubmittedList;
/** The cloudlet received list. */
private List<? extends Cloudlet> cloudletReceivedList;
/** The cloudlets submitted. */
private int cloudletsSubmitted;
/** The vms requested. */
private int vmsRequested;
/** The vms acks. */
private int vmsAcks;
/** The vms destroyed. */
private int vmsDestroyed;
/** The datacenter ids list. */
private List<Integer> datacenterIdsList;
/** The datacenter requested ids list. */
private List<Integer> datacenterRequestedIdsList;
/** The vms to datacenters map. */
private Map<Integer, Integer> vmsToDatacentersMap;
/** The datacenter characteristics list. */
private Map<Integer, DatacenterCharacteristics> datacenterCharacteristicsList;
public static NetworkDatacenter linkDC;
public boolean createvmflag = true;
public static int cachedcloudlet = 0;
/**
* Created a new DatacenterBroker object.
*
* @param name name to be associated with this entity (as required by Sim_entity class from
* simjava package)
*
* @throws Exception the exception
*
* @pre name != null
* @post $none
*/
public NetDatacenterBroker(String name) throws Exception {
super(name);
setVmList(new ArrayList<NetworkVm>());
setVmsCreatedList(new ArrayList<NetworkVm>());
setCloudletList(new ArrayList<NetworkCloudlet>());
setAppCloudletList(new ArrayList<AppCloudlet>());
setCloudletSubmittedList(new ArrayList<Cloudlet>());
setCloudletReceivedList(new ArrayList<Cloudlet>());
appCloudletRecieved = new HashMap<Integer, Integer>();
cloudletsSubmitted = 0;
setVmsRequested(0);
setVmsAcks(0);
setVmsDestroyed(0);
setDatacenterIdsList(new LinkedList<Integer>());
setDatacenterRequestedIdsList(new ArrayList<Integer>());
setVmsToDatacentersMap(new HashMap<Integer, Integer>());
setDatacenterCharacteristicsList(new HashMap<Integer, DatacenterCharacteristics>());
}
/**
* This method is used to send to the broker the list with virtual machines that must be
* created.
*
* @param list the list
*
* @pre list !=null
* @post $none
*/
public void submitVmList(List<? extends Vm> list) {
getVmList().addAll(list);
}
/**
* This method is used to send to the broker the list of cloudlets.
*
* @param list the list
*
* @pre list !=null
* @post $none
*/
public void submitCloudletList(List<? extends NetworkCloudlet> list) {
getCloudletList().addAll(list);
}
public void setLinkDC(NetworkDatacenter alinkDC) {
linkDC = alinkDC;
}
/**
* Processes events available for this Broker.
*
* @param ev a SimEvent object
*
* @pre ev != null
* @post $none
*/
@Override
public void processEvent(SimEvent ev) {
switch (ev.getTag()) {
// Resource characteristics request
case CloudSimTags.RESOURCE_CHARACTERISTICS_REQUEST:
processResourceCharacteristicsRequest(ev);
break;
// Resource characteristics answer
case CloudSimTags.RESOURCE_CHARACTERISTICS:
processResourceCharacteristics(ev);
break;
// VM Creation answer
// A finished cloudlet returned
case CloudSimTags.CLOUDLET_RETURN:
processCloudletReturn(ev);
break;
// if the simulation finishes
case CloudSimTags.END_OF_SIMULATION:
shutdownEntity();
break;
case CloudSimTags.NextCycle:
if (NetworkConstants.BASE) {
createVmsInDatacenterBase(linkDC.getId());
}
break;
// other unknown tags are processed by this method
default:
processOtherEvent(ev);
break;
}
}
/**
* Process the return of a request for the characteristics of a PowerDatacenter.
*
* @param ev a SimEvent object
*
* @pre ev != $null
* @post $none
*/
protected void processResourceCharacteristics(SimEvent ev) {
DatacenterCharacteristics characteristics = (DatacenterCharacteristics) ev.getData();
getDatacenterCharacteristicsList().put(characteristics.getId(), characteristics);
if (getDatacenterCharacteristicsList().size() == getDatacenterIdsList().size()) {
setDatacenterRequestedIdsList(new ArrayList<Integer>());
createVmsInDatacenterBase(getDatacenterIdsList().get(0));
}
}
/**
* Process a request for the characteristics of a PowerDatacenter.
*
* @param ev a SimEvent object
*
* @pre ev != $null
* @post $none
*/
protected void processResourceCharacteristicsRequest(SimEvent ev) {
setDatacenterIdsList(CloudSim.getCloudResourceList());
setDatacenterCharacteristicsList(new HashMap<Integer, DatacenterCharacteristics>());
Log.printLine(CloudSim.clock() + ": " + getName() + ": Cloud Resource List received with "
+ getDatacenterIdsList().size() + " resource(s)");
for (Integer datacenterId : getDatacenterIdsList()) {
sendNow(datacenterId, CloudSimTags.RESOURCE_CHARACTERISTICS, getId());
}
}
/**
* Process the ack received due to a request for VM creation.
*
* @param ev a SimEvent object
*
* @pre ev != null
* @post $none
*/
/**
* Process a cloudlet return event.
*
* @param ev a SimEvent object
*
* @pre ev != $null
* @post $none
*/
protected void processCloudletReturn(SimEvent ev) {
Cloudlet cloudlet = (Cloudlet) ev.getData();
getCloudletReceivedList().add(cloudlet);
cloudletsSubmitted--;
// all cloudlets executed
if (getCloudletList().size() == 0 && cloudletsSubmitted == 0 && NetworkConstants.iteration > 10) {
Log.printLine(CloudSim.clock() + ": " + getName() + ": All Cloudlets executed. Finishing...");
clearDatacenters();
finishExecution();
} else { // some cloudlets haven't finished yet
if (getAppCloudletList().size() > 0 && cloudletsSubmitted == 0) {
// all the cloudlets sent finished. It means that some bount
// cloudlet is waiting its VM be created
clearDatacenters();
createVmsInDatacenterBase(0);
}
}
}
/**
* Overrides this method when making a new and different type of Broker. This method is called
* by {@link #body()} for incoming unknown tags.
*
* @param ev a SimEvent object
*
* @pre ev != null
* @post $none
*/
protected void processOtherEvent(SimEvent ev) {
if (ev == null) {
Log.printLine(getName() + ".processOtherEvent(): " + "Error - an event is null.");
return;
}
Log.printLine(getName() + ".processOtherEvent(): "
+ "Error - event unknown by this DatacenterBroker.");
}
/**
* Create the virtual machines in a datacenter and submit/schedule cloudlets to them.
*
* @param datacenterId Id of the chosen PowerDatacenter
*
* @pre $none
* @post $none
*/
protected void createVmsInDatacenterBase(int datacenterId) {
// send as much vms as possible for this datacenter before trying the
// next one
int requestedVms = 0;
// All host will have two VMs (assumption) VM is the minimum unit
if (createvmflag) {
CreateVMs(datacenterId);
createvmflag = false;
}
// generate Application execution Requests
for (int i = 0; i < 100; i++) {
this.getAppCloudletList().add(
new WorkflowApp(AppCloudlet.APP_Workflow, NetworkConstants.currentAppId, 0, 0, getId()));
NetworkConstants.currentAppId++;
}
int k = 0;
// schedule the application on VMs
for (AppCloudlet app : this.getAppCloudletList()) {
List<Integer> vmids = new ArrayList<Integer>();
int numVms = linkDC.getVmList().size();
UniformDistr ufrnd = new UniformDistr(0, numVms, 5);
for (int i = 0; i < app.numbervm; i++) {
int vmid = (int) ufrnd.sample();
vmids.add(vmid);
}
if (vmids != null) {
if (!vmids.isEmpty()) {
app.createCloudletList(vmids);
for (int i = 0; i < app.numbervm; i++) {
app.clist.get(i).setUserId(getId());
appCloudletRecieved.put(app.appID, app.numbervm);
this.getCloudletSubmittedList().add(app.clist.get(i));
cloudletsSubmitted++;
// Sending cloudlet
sendNow(
getVmsToDatacentersMap().get(this.getVmList().get(0).getId()),
CloudSimTags.CLOUDLET_SUBMIT,
app.clist.get(i));
}
System.out.println("app" + (k++));
}
}
}
setAppCloudletList(new ArrayList<AppCloudlet>());
if (NetworkConstants.iteration < 10) {
NetworkConstants.iteration++;
this.schedule(getId(), NetworkConstants.nexttime, CloudSimTags.NextCycle);
}
setVmsRequested(requestedVms);
setVmsAcks(0);
}
private void CreateVMs(int datacenterId) {
// two VMs per host
int numVM = linkDC.getHostList().size() * NetworkConstants.maxhostVM;
for (int i = 0; i < numVM; i++) {
int vmid = i;
int mips = 1;
long size = 10000; // image size (MB)
int ram = 512; // vm memory (MB)
long bw = 1000;
int pesNumber = NetworkConstants.HOST_PEs / NetworkConstants.maxhostVM;
String vmm = "Xen"; // VMM name
// create VM
NetworkVm vm = new NetworkVm(
vmid,
getId(),
mips,
pesNumber,
ram,
bw,
size,
vmm,
new NetworkCloudletSpaceSharedScheduler());
linkDC.processVmCreateNetwork(vm);
// add the VM to the vmList
getVmList().add(vm);
getVmsToDatacentersMap().put(vmid, datacenterId);
getVmsCreatedList().add(VmList.getById(getVmList(), vmid));
}
}
/**
* Submit cloudlets to the created VMs.
*
* @pre $none
* @post $none /** Destroy the virtual machines running in datacenters.
*
* @pre $none
* @post $none
*/
protected void clearDatacenters() {
for (Vm vm : getVmsCreatedList()) {
Log.printLine(CloudSim.clock() + ": " + getName() + ": Destroying VM #" + vm.getId());
sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.VM_DESTROY, vm);
}
getVmsCreatedList().clear();
}
/**
* Send an internal event communicating the end of the simulation.
*
* @pre $none
* @post $none
*/
private void finishExecution() {
sendNow(getId(), CloudSimTags.END_OF_SIMULATION);
}
/*
* (non-Javadoc)
* @see cloudsim.core.SimEntity#shutdownEntity()
*/
@Override
public void shutdownEntity() {
Log.printLine(getName() + " is shutting down...");
}
/*
* (non-Javadoc)
* @see cloudsim.core.SimEntity#startEntity()
*/
@Override
public void startEntity() {
Log.printLine(getName() + " is starting...");
schedule(getId(), 0, CloudSimTags.RESOURCE_CHARACTERISTICS_REQUEST);
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Vm> List<T> getVmList() {
return (List<T>) vmList;
}
/**
* Sets the vm list.
*
* @param <T> the generic type
* @param vmList the new vm list
*/
protected <T extends Vm> void setVmList(List<T> vmList) {
this.vmList = vmList;
}
/**
* Gets the cloudlet list.
*
* @param <T> the generic type
* @return the cloudlet list
*/
@SuppressWarnings("unchecked")
public <T extends NetworkCloudlet> List<T> getCloudletList() {
return (List<T>) cloudletList;
}
/**
* Sets the cloudlet list.
*
* @param <T> the generic type
* @param cloudletList the new cloudlet list
*/
protected <T extends NetworkCloudlet> void setCloudletList(List<T> cloudletList) {
this.cloudletList = cloudletList;
}
@SuppressWarnings("unchecked")
public <T extends AppCloudlet> List<T> getAppCloudletList() {
return (List<T>) appCloudletList;
}
public <T extends AppCloudlet> void setAppCloudletList(List<T> appCloudletList) {
this.appCloudletList = appCloudletList;
}
/**
* Gets the cloudlet submitted list.
*
* @param <T> the generic type
* @return the cloudlet submitted list
*/
@SuppressWarnings("unchecked")
public <T extends Cloudlet> List<T> getCloudletSubmittedList() {
return (List<T>) cloudletSubmittedList;
}
/**
* Sets the cloudlet submitted list.
*
* @param <T> the generic type
* @param cloudletSubmittedList the new cloudlet submitted list
*/
protected <T extends Cloudlet> void setCloudletSubmittedList(List<T> cloudletSubmittedList) {
this.cloudletSubmittedList = cloudletSubmittedList;
}
/**
* Gets the cloudlet received list.
*
* @param <T> the generic type
* @return the cloudlet received list
*/
@SuppressWarnings("unchecked")
public <T extends Cloudlet> List<T> getCloudletReceivedList() {
return (List<T>) cloudletReceivedList;
}
/**
* Sets the cloudlet received list.
*
* @param <T> the generic type
* @param cloudletReceivedList the new cloudlet received list
*/
protected <T extends Cloudlet> void setCloudletReceivedList(List<T> cloudletReceivedList) {
this.cloudletReceivedList = cloudletReceivedList;
}
/**
* Gets the vm list.
*
* @param <T> the generic type
* @return the vm list
*/
@SuppressWarnings("unchecked")
public <T extends Vm> List<T> getVmsCreatedList() {
return (List<T>) vmsCreatedList;
}
/**
* Sets the vm list.
*
* @param <T> the generic type
* @param vmsCreatedList the vms created list
*/
protected <T extends Vm> void setVmsCreatedList(List<T> vmsCreatedList) {
this.vmsCreatedList = vmsCreatedList;
}
/**
* Gets the vms requested.
*
* @return the vms requested
*/
protected int getVmsRequested() {
return vmsRequested;
}
/**
* Sets the vms requested.
*
* @param vmsRequested the new vms requested
*/
protected void setVmsRequested(int vmsRequested) {
this.vmsRequested = vmsRequested;
}
/**
* Gets the vms acks.
*
* @return the vms acks
*/
protected int getVmsAcks() {
return vmsAcks;
}
/**
* Sets the vms acks.
*
* @param vmsAcks the new vms acks
*/
protected void setVmsAcks(int vmsAcks) {
this.vmsAcks = vmsAcks;
}
/**
* Increment vms acks.
*/
protected void incrementVmsAcks() {
vmsAcks++;
}
/**
* Gets the vms destroyed.
*
* @return the vms destroyed
*/
protected int getVmsDestroyed() {
return vmsDestroyed;
}
/**
* Sets the vms destroyed.
*
* @param vmsDestroyed the new vms destroyed
*/
protected void setVmsDestroyed(int vmsDestroyed) {
this.vmsDestroyed = vmsDestroyed;
}
/**
* Gets the datacenter ids list.
*
* @return the datacenter ids list
*/
protected List<Integer> getDatacenterIdsList() {
return datacenterIdsList;
}
/**
* Sets the datacenter ids list.
*
* @param datacenterIdsList the new datacenter ids list
*/
protected void setDatacenterIdsList(List<Integer> datacenterIdsList) {
this.datacenterIdsList = datacenterIdsList;
}
/**
* Gets the vms to datacenters map.
*
* @return the vms to datacenters map
*/
protected Map<Integer, Integer> getVmsToDatacentersMap() {
return vmsToDatacentersMap;
}
/**
* Sets the vms to datacenters map.
*
* @param vmsToDatacentersMap the vms to datacenters map
*/
protected void setVmsToDatacentersMap(Map<Integer, Integer> vmsToDatacentersMap) {
this.vmsToDatacentersMap = vmsToDatacentersMap;
}
/**
* Gets the datacenter characteristics list.
*
* @return the datacenter characteristics list
*/
protected Map<Integer, DatacenterCharacteristics> getDatacenterCharacteristicsList() {
return datacenterCharacteristicsList;
}
/**
* Sets the datacenter characteristics list.
*
* @param datacenterCharacteristicsList the datacenter characteristics list
*/
protected void setDatacenterCharacteristicsList(
Map<Integer, DatacenterCharacteristics> datacenterCharacteristicsList) {
this.datacenterCharacteristicsList = datacenterCharacteristicsList;
}
/**
* Gets the datacenter requested ids list.
*
* @return the datacenter requested ids list
*/
protected List<Integer> getDatacenterRequestedIdsList() {
return datacenterRequestedIdsList;
}
/**
* Sets the datacenter requested ids list.
*
* @param datacenterRequestedIdsList the new datacenter requested ids list
*/
protected void setDatacenterRequestedIdsList(List<Integer> datacenterRequestedIdsList) {
this.datacenterRequestedIdsList = datacenterRequestedIdsList;
}
}

View File

@@ -0,0 +1,90 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.Map;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.UtilizationModel;
/**
* NetworkCloudlet class extends Cloudlet to support simulation of complex applications. Each such
* network Cloudlet represents a task of the application. Each task consists of several stages.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class NetworkCloudlet extends Cloudlet implements Comparable<Object> {
long memory;
public NetworkCloudlet(
int cloudletId,
long cloudletLength,
int pesNumber,
long cloudletFileSize,
long cloudletOutputSize,
long memory,
UtilizationModel utilizationModelCpu,
UtilizationModel utilizationModelRam,
UtilizationModel utilizationModelBw) {
super(
cloudletId,
cloudletLength,
pesNumber,
cloudletFileSize,
cloudletOutputSize,
utilizationModelCpu,
utilizationModelRam,
utilizationModelBw);
currStagenum = -1;
this.memory = memory;
stages = new ArrayList<TaskStage>();
}
public double submittime; // time when cloudlet will be submitted
public double finishtime; // time when cloudlet finish execution
public double exetime; // execution time for cloudlet
public double numStage;// number of stages in cloudlet
public int currStagenum; // current stage of cloudlet execution
public double timetostartStage;
public double timespentInStage; // how much time spent in particular stage
public Map<Double, HostPacket> timeCommunicate;
public ArrayList<TaskStage> stages; // all stages which cloudlet execution
// consists of.
public double starttime;
@Override
public int compareTo(Object arg0) {
return 0;
}
public double getSubmittime() {
return submittime;
}
}

View File

@@ -0,0 +1,797 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.ResCloudlet;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
/**
* CloudletSchedulerSpaceShared implements a policy of scheduling performed by a virtual machine. It
* consider that there will be only one cloudlet per VM. Other cloudlets will be in a waiting list.
* We consider that file transfer from cloudlets waiting happens before cloudlet execution. I.e.,
* even though cloudlets must wait for CPU, data transfer happens as soon as cloudlets are
* submitted.
*
* @author Saurabh Kumar Garg
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class NetworkCloudletSpaceSharedScheduler extends CloudletScheduler {
/** The cloudlet waiting list. */
private List<? extends ResCloudlet> cloudletWaitingList;
/** The cloudlet exec list. */
private List<? extends ResCloudlet> cloudletExecList;
/** The cloudlet paused list. */
private List<? extends ResCloudlet> cloudletPausedList;
/** The cloudlet finished list. */
private List<? extends ResCloudlet> cloudletFinishedList;
/** The current CPUs. */
protected int currentCpus;
/** The used PEs. */
protected int usedPes;
// for network
public Map<Integer, List<HostPacket>> pkttosend;
public Map<Integer, List<HostPacket>> pktrecv;
/**
* Creates a new CloudletSchedulerSpaceShared object. This method must be invoked before
* starting the actual simulation.
*
* @pre $none
* @post $none
*/
public NetworkCloudletSpaceSharedScheduler() {
super();
cloudletWaitingList = new ArrayList<ResCloudlet>();
cloudletExecList = new ArrayList<ResCloudlet>();
cloudletPausedList = new ArrayList<ResCloudlet>();
cloudletFinishedList = new ArrayList<ResCloudlet>();
usedPes = 0;
currentCpus = 0;
pkttosend = new HashMap<Integer, List<HostPacket>>();
pktrecv = new HashMap<Integer, List<HostPacket>>();
}
/**
* Updates the processing of cloudlets running under management of this scheduler.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each processor available to the scheduler
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is
* no next events
* @pre currentTime >= 0
* @post $none
*/
@Override
public double updateVmProcessing(double currentTime, List<Double> mipsShare) {
setCurrentMipsShare(mipsShare);
// update
double capacity = 0.0;
int cpus = 0;
for (Double mips : mipsShare) { // count the CPUs available to the VMM
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus; // average capacity of each cpu
for (ResCloudlet rcl : getCloudletExecList()) { // each machine in the
// exec list has the
// same amount of cpu
NetworkCloudlet cl = (NetworkCloudlet) rcl.getCloudlet();
// check status
// if execution stage
// update the cloudlet finishtime
// CHECK WHETHER IT IS WAITING FOR THE PACKET
// if packet received change the status of job and update the time.
//
if ((cl.currStagenum != -1)) {
if (cl.currStagenum == NetworkConstants.FINISH) {
break;
}
TaskStage st = cl.stages.get(cl.currStagenum);
if (st.type == NetworkConstants.EXECUTION) {
// update the time
cl.timespentInStage = Math.round(CloudSim.clock() - cl.timetostartStage);
if (cl.timespentInStage >= st.time) {
changetonextstage(cl, st);
// change the stage
}
}
if (st.type == NetworkConstants.WAIT_RECV) {
List<HostPacket> pktlist = pktrecv.get(st.peer);
List<HostPacket> pkttoremove = new ArrayList<HostPacket>();
if (pktlist != null) {
Iterator<HostPacket> it = pktlist.iterator();
HostPacket pkt = null;
if (it.hasNext()) {
pkt = it.next();
// Asumption packet will not arrive in the same cycle
if (pkt.reciever == cl.getVmId()) {
pkt.recievetime = CloudSim.clock();
st.time = CloudSim.clock() - pkt.sendtime;
changetonextstage(cl, st);
pkttoremove.add(pkt);
}
}
pktlist.removeAll(pkttoremove);
// if(pkt!=null)
// else wait for recieving the packet
}
}
} else {
cl.currStagenum = 0;
cl.timetostartStage = CloudSim.clock();
if (cl.stages.get(0).type == NetworkConstants.EXECUTION) {
NetDatacenterBroker.linkDC.schedule(
NetDatacenterBroker.linkDC.getId(),
cl.stages.get(0).time,
CloudSimTags.VM_DATACENTER_EVENT);
} else {
NetDatacenterBroker.linkDC.schedule(
NetDatacenterBroker.linkDC.getId(),
0.0001,
CloudSimTags.VM_DATACENTER_EVENT);
// /sendstage///
}
}
}
if (getCloudletExecList().size() == 0 && getCloudletWaitingList().size() == 0) { // no
// more cloudlets in this scheduler
setPreviousTime(currentTime);
return 0.0;
}
// update each cloudlet
int finished = 0;
List<ResCloudlet> toRemove = new ArrayList<ResCloudlet>();
for (ResCloudlet rcl : getCloudletExecList()) {
// rounding issue...
if (((NetworkCloudlet) (rcl.getCloudlet())).currStagenum == NetworkConstants.FINISH) {
// stage is changed and packet to send
((NetworkCloudlet) (rcl.getCloudlet())).finishtime = CloudSim.clock();
toRemove.add(rcl);
cloudletFinish(rcl);
finished++;
}
}
getCloudletExecList().removeAll(toRemove);
// add all the CloudletExecList in waitingList.
// sort the waitinglist
// for each finished cloudlet, add a new one from the waiting list
if (!getCloudletWaitingList().isEmpty()) {
for (int i = 0; i < finished; i++) {
toRemove.clear();
for (ResCloudlet rcl : getCloudletWaitingList()) {
if ((currentCpus - usedPes) >= rcl.getNumberOfPes()) {
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int k = 0; k < rcl.getNumberOfPes(); k++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
usedPes += rcl.getNumberOfPes();
toRemove.add(rcl);
break;
}
}
getCloudletWaitingList().removeAll(toRemove);
}// for(cont)
}
// estimate finish time of cloudlets in the execution queue
double nextEvent = Double.MAX_VALUE;
for (ResCloudlet rcl : getCloudletExecList()) {
double remainingLength = rcl.getRemainingCloudletLength();
double estimatedFinishTime = currentTime + (remainingLength / (capacity * rcl.getNumberOfPes()));
if (estimatedFinishTime - currentTime < CloudSim.getMinTimeBetweenEvents()) {
estimatedFinishTime = currentTime + CloudSim.getMinTimeBetweenEvents();
}
if (estimatedFinishTime < nextEvent) {
nextEvent = estimatedFinishTime;
}
}
setPreviousTime(currentTime);
return nextEvent;
}
private void changetonextstage(NetworkCloudlet cl, TaskStage st) {
cl.timespentInStage = 0;
cl.timetostartStage = CloudSim.clock();
int currstage = cl.currStagenum;
if (currstage >= (cl.stages.size() - 1)) {
cl.currStagenum = NetworkConstants.FINISH;
} else {
cl.currStagenum = currstage + 1;
int i = 0;
for (i = cl.currStagenum; i < cl.stages.size(); i++) {
if (cl.stages.get(i).type == NetworkConstants.WAIT_SEND) {
HostPacket pkt = new HostPacket(
cl.getVmId(),
cl.stages.get(i).peer,
cl.stages.get(i).data,
CloudSim.clock(),
-1,
cl.getCloudletId(),
cl.stages.get(i).vpeer);
List<HostPacket> pktlist = pkttosend.get(cl.getVmId());
if (pktlist == null) {
pktlist = new ArrayList<HostPacket>();
}
pktlist.add(pkt);
pkttosend.put(cl.getVmId(), pktlist);
} else {
break;
}
}
NetDatacenterBroker.linkDC.schedule(
NetDatacenterBroker.linkDC.getId(),
0.0001,
CloudSimTags.VM_DATACENTER_EVENT);
if (i == cl.stages.size()) {
cl.currStagenum = NetworkConstants.FINISH;
} else {
cl.currStagenum = i;
if (cl.stages.get(i).type == NetworkConstants.EXECUTION) {
NetDatacenterBroker.linkDC.schedule(
NetDatacenterBroker.linkDC.getId(),
cl.stages.get(i).time,
CloudSimTags.VM_DATACENTER_EVENT);
}
}
}
}
/**
* Cancels execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being cancealed
* @return the canceled cloudlet, $null if not found
* @pre $none
* @post $none
*/
@Override
public Cloudlet cloudletCancel(int cloudletId) {
// First, looks in the finished queue
for (ResCloudlet rcl : getCloudletFinishedList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletFinishedList().remove(rcl);
return rcl.getCloudlet();
}
}
// Then searches in the exec list
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletExecList().remove(rcl);
if (rcl.getRemainingCloudletLength() == 0.0) {
cloudletFinish(rcl);
} else {
rcl.setCloudletStatus(Cloudlet.CANCELED);
}
return rcl.getCloudlet();
}
}
// Now, looks in the paused queue
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
getCloudletPausedList().remove(rcl);
return rcl.getCloudlet();
}
}
// Finally, looks in the waiting list
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
rcl.setCloudletStatus(Cloudlet.CANCELED);
getCloudletWaitingList().remove(rcl);
return rcl.getCloudlet();
}
}
return null;
}
/**
* Pauses execution of a cloudlet.
*
* @param cloudletId ID of the cloudlet being paused
* @return $true if cloudlet paused, $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean cloudletPause(int cloudletId) {
boolean found = false;
int position = 0;
// first, looks for the cloudlet in the exec list
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
// moves to the paused list
ResCloudlet rgl = getCloudletExecList().remove(position);
if (rgl.getRemainingCloudletLength() == 0.0) {
cloudletFinish(rgl);
} else {
rgl.setCloudletStatus(Cloudlet.PAUSED);
getCloudletPausedList().add(rgl);
}
return true;
}
// now, look for the cloudlet in the waiting list
position = 0;
found = false;
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
// moves to the paused list
ResCloudlet rgl = getCloudletWaitingList().remove(position);
if (rgl.getRemainingCloudletLength() == 0.0) {
cloudletFinish(rgl);
} else {
rgl.setCloudletStatus(Cloudlet.PAUSED);
getCloudletPausedList().add(rgl);
}
return true;
}
return false;
}
/**
* Processes a finished cloudlet.
*
* @param rcl finished cloudlet
* @pre rgl != $null
* @post $none
*/
@Override
public void cloudletFinish(ResCloudlet rcl) {
rcl.setCloudletStatus(Cloudlet.SUCCESS);
rcl.finalizeCloudlet();
getCloudletFinishedList().add(rcl);
usedPes -= rcl.getNumberOfPes();
}
/**
* Resumes execution of a paused cloudlet.
*
* @param cloudletId ID of the cloudlet being resumed
* @return $true if the cloudlet was resumed, $false otherwise
* @pre $none
* @post $none
*/
@Override
public double cloudletResume(int cloudletId) {
boolean found = false;
int position = 0;
// look for the cloudlet in the paused list
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
found = true;
break;
}
position++;
}
if (found) {
ResCloudlet rcl = getCloudletPausedList().remove(position);
// it can go to the exec list
if ((currentCpus - usedPes) >= rcl.getNumberOfPes()) {
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < rcl.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
long size = rcl.getRemainingCloudletLength();
size *= rcl.getNumberOfPes();
rcl.getCloudlet().setCloudletLength(size);
getCloudletExecList().add(rcl);
usedPes += rcl.getNumberOfPes();
// calculate the expected time for cloudlet completion
double capacity = 0.0;
int cpus = 0;
for (Double mips : getCurrentMipsShare()) {
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus;
long remainingLength = rcl.getRemainingCloudletLength();
double estimatedFinishTime = CloudSim.clock()
+ (remainingLength / (capacity * rcl.getNumberOfPes()));
return estimatedFinishTime;
} else {// no enough free PEs: go to the waiting queue
rcl.setCloudletStatus(Cloudlet.QUEUED);
long size = rcl.getRemainingCloudletLength();
size *= rcl.getNumberOfPes();
rcl.getCloudlet().setCloudletLength(size);
getCloudletWaitingList().add(rcl);
return 0.0;
}
}
// not found in the paused list: either it is in in the queue, executing
// or not exist
return 0.0;
}
/**
* Receives an cloudlet to be executed in the VM managed by this scheduler.
*
* @param cloudlet the submited cloudlet
* @param fileTransferTime time required to move the required files from the SAN to the VM
* @return expected finish time of this cloudlet, or 0 if it is in the waiting queue
* @pre gl != null
* @post $none
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet, double fileTransferTime) {
// it can go to the exec list
if ((currentCpus - usedPes) >= cloudlet.getNumberOfPes()) {
ResCloudlet rcl = new ResCloudlet(cloudlet);
rcl.setCloudletStatus(Cloudlet.INEXEC);
for (int i = 0; i < cloudlet.getNumberOfPes(); i++) {
rcl.setMachineAndPeId(0, i);
}
getCloudletExecList().add(rcl);
usedPes += cloudlet.getNumberOfPes();
} else {// no enough free PEs: go to the waiting queue
ResCloudlet rcl = new ResCloudlet(cloudlet);
rcl.setCloudletStatus(Cloudlet.QUEUED);
getCloudletWaitingList().add(rcl);
return 0.0;
}
// calculate the expected time for cloudlet completion
double capacity = 0.0;
int cpus = 0;
for (Double mips : getCurrentMipsShare()) {
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus;
// use the current capacity to estimate the extra amount of
// time to file transferring. It must be added to the cloudlet length
double extraSize = capacity * fileTransferTime;
long length = cloudlet.getCloudletLength();
length += extraSize;
cloudlet.setCloudletLength(length);
return cloudlet.getCloudletLength() / capacity;
}
/*
* (non-Javadoc)
* @see cloudsim.CloudletScheduler#cloudletSubmit(cloudsim.Cloudlet)
*/
@Override
public double cloudletSubmit(Cloudlet cloudlet) {
cloudletSubmit(cloudlet, 0);
return 0;
}
/**
* Gets the status of a cloudlet.
*
* @param cloudletId ID of the cloudlet
* @return status of the cloudlet, -1 if cloudlet not found
* @pre $none
* @post $none
*/
@Override
public int getCloudletStatus(int cloudletId) {
for (ResCloudlet rcl : getCloudletExecList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
for (ResCloudlet rcl : getCloudletPausedList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
for (ResCloudlet rcl : getCloudletWaitingList()) {
if (rcl.getCloudletId() == cloudletId) {
return rcl.getCloudletStatus();
}
}
return -1;
}
/**
* Get utilization created by all cloudlets.
*
* @param time the time
* @return total utilization
*/
@Override
public double getTotalUtilizationOfCpu(double time) {
double totalUtilization = 0;
for (ResCloudlet gl : getCloudletExecList()) {
totalUtilization += gl.getCloudlet().getUtilizationOfCpu(time);
}
return totalUtilization;
}
/**
* Informs about completion of some cloudlet in the VM managed by this scheduler.
*
* @return $true if there is at least one finished cloudlet; $false otherwise
* @pre $none
* @post $none
*/
@Override
public boolean isFinishedCloudlets() {
return getCloudletFinishedList().size() > 0;
}
/**
* Returns the next cloudlet in the finished list, $null if this list is empty.
*
* @return a finished cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet getNextFinishedCloudlet() {
if (getCloudletFinishedList().size() > 0) {
return getCloudletFinishedList().remove(0).getCloudlet();
}
return null;
}
/**
* Returns the number of cloudlets runnning in the virtual machine.
*
* @return number of cloudlets runnning
* @pre $none
* @post $none
*/
@Override
public int runningCloudlets() {
return getCloudletExecList().size();
}
/**
* Returns one cloudlet to migrate to another vm.
*
* @return one running cloudlet
* @pre $none
* @post $none
*/
@Override
public Cloudlet migrateCloudlet() {
ResCloudlet rcl = getCloudletExecList().remove(0);
rcl.finalizeCloudlet();
Cloudlet cl = rcl.getCloudlet();
usedPes -= cl.getNumberOfPes();
return cl;
}
/**
* Gets the cloudlet waiting list.
*
* @param <T> the generic type
* @return the cloudlet waiting list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletWaitingList() {
return (List<T>) cloudletWaitingList;
}
/**
* Cloudlet waiting list.
*
* @param <T> the generic type
* @param cloudletWaitingList the cloudlet waiting list
*/
protected <T extends ResCloudlet> void cloudletWaitingList(List<T> cloudletWaitingList) {
this.cloudletWaitingList = cloudletWaitingList;
}
/**
* Gets the cloudlet exec list.
*
* @param <T> the generic type
* @return the cloudlet exec list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletExecList() {
return (List<T>) cloudletExecList;
}
/**
* Sets the cloudlet exec list.
*
* @param <T> the generic type
* @param cloudletExecList the new cloudlet exec list
*/
protected <T extends ResCloudlet> void setCloudletExecList(List<T> cloudletExecList) {
this.cloudletExecList = cloudletExecList;
}
/**
* Gets the cloudlet paused list.
*
* @param <T> the generic type
* @return the cloudlet paused list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletPausedList() {
return (List<T>) cloudletPausedList;
}
/**
* Sets the cloudlet paused list.
*
* @param <T> the generic type
* @param cloudletPausedList the new cloudlet paused list
*/
protected <T extends ResCloudlet> void setCloudletPausedList(List<T> cloudletPausedList) {
this.cloudletPausedList = cloudletPausedList;
}
/**
* Gets the cloudlet finished list.
*
* @param <T> the generic type
* @return the cloudlet finished list
*/
@SuppressWarnings("unchecked")
protected <T extends ResCloudlet> List<T> getCloudletFinishedList() {
return (List<T>) cloudletFinishedList;
}
/**
* Sets the cloudlet finished list.
*
* @param <T> the generic type
* @param cloudletFinishedList the new cloudlet finished list
*/
protected <T extends ResCloudlet> void setCloudletFinishedList(List<T> cloudletFinishedList) {
this.cloudletFinishedList = cloudletFinishedList;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.CloudletScheduler#getCurrentRequestedMips()
*/
@Override
public List<Double> getCurrentRequestedMips() {
List<Double> mipsShare = new ArrayList<Double>();
if (getCurrentMipsShare() != null) {
for (Double mips : getCurrentMipsShare()) {
mipsShare.add(mips);
}
}
return mipsShare;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.CloudletScheduler# getTotalCurrentAvailableMipsForCloudlet
* (org.cloudbus.cloudsim.ResCloudlet, java.util.List)
*/
@Override
public double getTotalCurrentAvailableMipsForCloudlet(ResCloudlet rcl, List<Double> mipsShare) {
double capacity = 0.0;
int cpus = 0;
for (Double mips : mipsShare) { // count the cpus available to the vmm
capacity += mips;
if (mips > 0) {
cpus++;
}
}
currentCpus = cpus;
capacity /= cpus; // average capacity of each cpu
return capacity;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.CloudletScheduler# getTotalCurrentAllocatedMipsForCloudlet
* (org.cloudbus.cloudsim.ResCloudlet, double)
*/
@Override
public double getTotalCurrentAllocatedMipsForCloudlet(ResCloudlet rcl, double time) {
return 0.0;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.CloudletScheduler# getTotalCurrentRequestedMipsForCloudlet
* (org.cloudbus.cloudsim.ResCloudlet, double)
*/
@Override
public double getTotalCurrentRequestedMipsForCloudlet(ResCloudlet rcl, double time) {
return 0.0;
}
@Override
public double getCurrentRequestedUtilizationOfBw() {
return 0;
}
@Override
public double getCurrentRequestedUtilizationOfRam() {
return 0;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
public class NetworkConstants {
public static int maxhostVM = 2;
public static int HOST_PEs = 8;
public static double maxMemperVM = 1024 * 1024;// kb
public static int currentCloudletId = 0;
public static int currentAppId = 0;
// stage type
public static final int EXECUTION = 0;
public static final int WAIT_SEND = 1;
public static final int WAIT_RECV = 2;
public static final int FINISH = -2;
// number of switches at each level
public static final int ROOT_LEVEL = 0;
public static final int Agg_LEVEL = 1;
public static final int EDGE_LEVEL = 2;
public static final int PES_NUMBER = 4;
public static final int FILE_SIZE = 300;
public static final int OUTPUT_SIZE = 300;
public static final int COMMUNICATION_LENGTH = 1;
public static boolean BASE = true;
public static long BandWidthEdgeAgg = 100 * 1024 * 1024;// 100 Megabits
public static long BandWidthEdgeHost = 100 * 1024 * 1024;//
public static long BandWidthAggRoot = 20 * 1024 * 1024 * 2;// 40gb
public static double SwitchingDelayRoot = .00285;
public static double SwitchingDelayAgg = .00245;// .00245
public static double SwitchingDelayEdge = .00157;// ms
public static double EdgeSwitchPort = 4;// number of host
public static double AggSwitchPort = 1;// number of Edge
public static double RootSwitchPort = 1;// number of Agg
public static double seed = 199;
public static boolean logflag = false;
public static int iteration = 10;
public static int nexttime = 1000;
public static int totaldatatransfer = 0;
}

View File

@@ -0,0 +1,221 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* NetworkDatacenter class is a Datacenter whose hostList are virtualized and networked. It contains
* all the information about internal network. For example, which VM is connected to Switch etc. It
* deals with processing of VM queries (i.e., handling of VMs) instead of processing
* Cloudlet-related queries. So, even though an AllocPolicy will be instantiated (in the init()
* method of the superclass, it will not be used, as processing of cloudlets are handled by the
* CloudletScheduler and processing of VirtualMachines are handled by the VmAllocationPolicy.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class NetworkDatacenter extends Datacenter {
/**
* Allocates a new NetworkDatacenter object.
*
* @param name the name to be associated with this entity (as required by Sim_entity class from
* simjava package)
* @param characteristics an object of DatacenterCharacteristics
* @param storageList a LinkedList of storage elements, for data simulation
* @param vmAllocationPolicy the vmAllocationPolicy
*
* @throws Exception This happens when one of the following scenarios occur:
* <ul>
* <li>creating this entity before initializing CloudSim package
* <li>this entity name is <tt>null</tt> or empty
* <li>this entity has <tt>zero</tt> number of PEs (Processing Elements). <br>
* No PEs mean the Cloudlets can't be processed. A CloudResource must contain one or
* more Machines. A Machine must contain one or more PEs.
* </ul>
*
* @pre name != null
* @pre resource != null
* @post $none
*/
public NetworkDatacenter(
String name,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
VmToSwitchid = new HashMap<Integer, Integer>();
HostToSwitchid = new HashMap<Integer, Integer>();
VmtoHostlist = new HashMap<Integer, Integer>();
Switchlist = new HashMap<Integer, Switch>();
}
public Map<Integer, Integer> VmToSwitchid;
public Map<Integer, Integer> HostToSwitchid;
public Map<Integer, Switch> Switchlist;
public Map<Integer, Integer> VmtoHostlist;
/**
* Get list of all EdgeSwitches in the Datacenter network One can design similar functions for
* other type of switches.
*
*/
public Map<Integer, Switch> getEdgeSwitch() {
Map<Integer, Switch> edgeswitch = new HashMap<Integer, Switch>();
for (Entry<Integer, Switch> es : Switchlist.entrySet()) {
if (es.getValue().level == NetworkConstants.EDGE_LEVEL) {
edgeswitch.put(es.getKey(), es.getValue());
}
}
return edgeswitch;
}
/**
* Create the VM within the NetworkDatacenter. It can be directly accessed by Datacenter Broker
* which manage allocation of Cloudlets.
*
*
*/
public boolean processVmCreateNetwork(Vm vm) {
boolean result = getVmAllocationPolicy().allocateHostForVm(vm);
if (result) {
VmToSwitchid.put(vm.getId(), ((NetworkHost) vm.getHost()).sw.getId());
VmtoHostlist.put(vm.getId(), vm.getHost().getId());
System.out.println(vm.getId() + " VM is created on " + vm.getHost().getId());
getVmList().add(vm);
vm.updateVmProcessing(CloudSim.clock(), getVmAllocationPolicy().getHost(vm).getVmScheduler()
.getAllocatedMipsForVm(vm));
}
return result;
}
/**
* Processes a Cloudlet submission.
*
* @param ev a SimEvent object
* @param ack an acknowledgement
*
* @pre ev != null
* @post $none
*/
@Override
protected void processCloudletSubmit(SimEvent ev, boolean ack) {
updateCloudletProcessing();
try {
// gets the Cloudlet object
Cloudlet cl = (Cloudlet) ev.getData();
// checks whether this Cloudlet has finished or not
if (cl.isFinished()) {
String name = CloudSim.getEntityName(cl.getUserId());
Log.printLine(getName() + ": Warning - Cloudlet #" + cl.getCloudletId() + " owned by " + name
+ " is already completed/finished.");
Log.printLine("Therefore, it is not being executed again");
Log.printLine();
// NOTE: If a Cloudlet has finished, then it won't be processed.
// So, if ack is required, this method sends back a result.
// If ack is not required, this method don't send back a result.
// Hence, this might cause CloudSim to be hanged since waiting
// for this Cloudlet back.
if (ack) {
int[] data = new int[3];
data[0] = getId();
data[1] = cl.getCloudletId();
data[2] = CloudSimTags.FALSE;
// unique tag = operation tag
int tag = CloudSimTags.CLOUDLET_SUBMIT_ACK;
sendNow(cl.getUserId(), tag, data);
}
sendNow(cl.getUserId(), CloudSimTags.CLOUDLET_RETURN, cl);
return;
}
// process this Cloudlet to this CloudResource
cl.setResourceParameter(getId(), getCharacteristics().getCostPerSecond(), getCharacteristics()
.getCostPerBw());
int userId = cl.getUserId();
int vmId = cl.getVmId();
// time to transfer the files
double fileTransferTime = predictFileTransferTime(cl.getRequiredFiles());
Host host = getVmAllocationPolicy().getHost(vmId, userId);
Vm vm = host.getVm(vmId, userId);
CloudletScheduler scheduler = vm.getCloudletScheduler();
double estimatedFinishTime = scheduler.cloudletSubmit(cl, fileTransferTime);
if (estimatedFinishTime > 0.0) { // if this cloudlet is in the exec
// time to process the cloudlet
estimatedFinishTime += fileTransferTime;
send(getId(), estimatedFinishTime, CloudSimTags.VM_DATACENTER_EVENT);
// event to update the stages
send(getId(), 0.0001, CloudSimTags.VM_DATACENTER_EVENT);
}
if (ack) {
int[] data = new int[3];
data[0] = getId();
data[1] = cl.getCloudletId();
data[2] = CloudSimTags.TRUE;
// unique tag = operation tag
int tag = CloudSimTags.CLOUDLET_SUBMIT_ACK;
sendNow(cl.getUserId(), tag, data);
}
} catch (ClassCastException c) {
Log.printLine(getName() + ".processCloudletSubmit(): " + "ClassCastException error.");
c.printStackTrace();
} catch (Exception e) {
Log.printLine(getName() + ".processCloudletSubmit(): " + "Exception error.");
e.printStackTrace();
}
checkCloudletCompletion();
}
}

View File

@@ -0,0 +1,202 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmScheduler;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.lists.PeList;
import org.cloudbus.cloudsim.lists.VmList;
import org.cloudbus.cloudsim.provisioners.BwProvisioner;
import org.cloudbus.cloudsim.provisioners.RamProvisioner;
/**
* NetworkHost class extends Host to support simulation of networked datacenters. It executes
* actions related to management of packets (send and receive)other than that of virtual machines
* (e.g., creation and destruction). A host has a defined policy for provisioning memory and bw, as
* well as an allocation policy for Pe's to virtual machines.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class NetworkHost extends Host {
public List<NetworkPacket> packetTosendLocal;
public List<NetworkPacket> packetTosendGlobal;
public List<NetworkPacket> packetrecieved;
public double memory;
public Switch sw; // Edge switch in general
public double bandwidth;// latency
/** time when last job will finish on CPU1 **/
public List<Double> CPUfinTimeCPU = new ArrayList<Double>();
public double fintime = 0;
public NetworkHost(
int id,
RamProvisioner ramProvisioner,
BwProvisioner bwProvisioner,
long storage,
List<? extends Pe> peList,
VmScheduler vmScheduler) {
super(id, ramProvisioner, bwProvisioner, storage, peList, vmScheduler);
packetrecieved = new ArrayList<NetworkPacket>();
packetTosendGlobal = new ArrayList<NetworkPacket>();
packetTosendLocal = new ArrayList<NetworkPacket>();
}
/**
* Requests updating of processing of cloudlets in the VMs running in this host.
*
* @param currentTime the current time
*
* @return expected time of completion of the next cloudlet in all VMs in this host.
* Double.MAX_VALUE if there is no future events expected in th is host
*
* @pre currentTime >= 0.0
* @post $none
*/
@Override
public double updateVmsProcessing(double currentTime) {
double smallerTime = Double.MAX_VALUE;
// insert in each vm packet recieved
recvpackets();
for (Vm vm : super.getVmList()) {
double time = ((NetworkVm) vm).updateVmProcessing(currentTime, getVmScheduler()
.getAllocatedMipsForVm(vm));
if (time > 0.0 && time < smallerTime) {
smallerTime = time;
}
}
// send the packets to other hosts/VMs
sendpackets();
return smallerTime;
}
/**
* Receives packet and forward it to the corresponding VM for processing host.
*
*
*/
private void recvpackets() {
for (NetworkPacket hs : packetrecieved) {
hs.pkt.recievetime = CloudSim.clock();
// insertthe packet in recievedlist of VM
Vm vm = VmList.getById(getVmList(), hs.pkt.reciever);
List<HostPacket> pktlist = ((NetworkCloudletSpaceSharedScheduler) vm.getCloudletScheduler()).pktrecv
.get(hs.pkt.sender);
if (pktlist == null) {
pktlist = new ArrayList<HostPacket>();
((NetworkCloudletSpaceSharedScheduler) vm.getCloudletScheduler()).pktrecv.put(
hs.pkt.sender,
pktlist);
}
pktlist.add(hs.pkt);
}
packetrecieved.clear();
}
/**
* Send packet check whether a packet belongs to a local VM or to a VM hosted on other machine.
*
*
*/
private void sendpackets() {
for (Vm vm : super.getVmList()) {
for (Entry<Integer, List<HostPacket>> es : ((NetworkCloudletSpaceSharedScheduler) vm
.getCloudletScheduler()).pkttosend.entrySet()) {
List<HostPacket> pktlist = es.getValue();
for (HostPacket pkt : pktlist) {
NetworkPacket hpkt = new NetworkPacket(getId(), pkt, vm.getId(), pkt.sender);
Vm vm2 = VmList.getById(this.getVmList(), hpkt.recievervmid);
if (vm2 != null) {
packetTosendLocal.add(hpkt);
} else {
packetTosendGlobal.add(hpkt);
}
}
pktlist.clear();
}
}
boolean flag = false;
for (NetworkPacket hs : packetTosendLocal) {
flag = true;
hs.stime = hs.rtime;
hs.pkt.recievetime = CloudSim.clock();
// insertthe packet in recievedlist
Vm vm = VmList.getById(getVmList(), hs.pkt.reciever);
List<HostPacket> pktlist = ((NetworkCloudletSpaceSharedScheduler) vm.getCloudletScheduler()).pktrecv
.get(hs.pkt.sender);
if (pktlist == null) {
pktlist = new ArrayList<HostPacket>();
((NetworkCloudletSpaceSharedScheduler) vm.getCloudletScheduler()).pktrecv.put(
hs.pkt.sender,
pktlist);
}
pktlist.add(hs.pkt);
}
if (flag) {
for (Vm vm : super.getVmList()) {
vm.updateVmProcessing(CloudSim.clock(), getVmScheduler().getAllocatedMipsForVm(vm));
}
}
// Sending packet to other VMs therefore packet is forwarded to a Edge switch
packetTosendLocal.clear();
double avband = bandwidth / packetTosendGlobal.size();
for (NetworkPacket hs : packetTosendGlobal) {
double delay = (1000 * hs.pkt.data) / avband;
NetworkConstants.totaldatatransfer += hs.pkt.data;
CloudSim.send(getDatacenter().getId(), sw.getId(), delay, CloudSimTags.Network_Event_UP, hs);
// send to switch with delay
}
packetTosendGlobal.clear();
}
public double getMaxUtilizationAmongVmsPes(Vm vm) {
return PeList.getMaxUtilizationAmongVmsPes(getPeList(), vm);
}
}

View File

@@ -0,0 +1,52 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
/**
* NewtorkPacket represents the packet which travel from one server to another. Each packet contains
* ids of the sender VM and receiver VM, time at which it is send and received, type and virtual ids
* of tasks, which are communicating.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class NetworkPacket {
public NetworkPacket(int id, HostPacket pkt2, int vmid, int cloudletid) {
pkt = pkt2;
sendervmid = vmid;
this.cloudletid = cloudletid;
senderhostid = id;
stime = pkt.sendtime;
recievervmid = pkt2.reciever;
}
HostPacket pkt;
int senderhostid;
int recieverhostid;
int sendervmid;
int recievervmid;
int cloudletid;
double stime;// time when sent
double rtime;// time when received
}

View File

@@ -0,0 +1,73 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.Vm;
/**
* NetworkVm class extends Vm to support simulation of networked datacenters. It executes actions
* related to management of packets (send and receive).
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class NetworkVm extends Vm implements Comparable<Object> {
public NetworkVm(
int id,
int userId,
double mips,
int pesNumber,
int ram,
long bw,
long size,
String vmm,
CloudletScheduler cloudletScheduler) {
super(id, userId, mips, pesNumber, ram, bw, size, vmm, cloudletScheduler);
cloudletlist = new ArrayList<NetworkCloudlet>();
}
public ArrayList<NetworkCloudlet> cloudletlist;
int type;
public ArrayList<HostPacket> recvPktlist;
public double memory;
public boolean flagfree;// if true it is free
public double finishtime;
public boolean isFree() {
return flagfree;
}
@Override
public int compareTo(Object arg0) {
NetworkVm hs = (NetworkVm) arg0;
if (hs.finishtime > finishtime) {
return -1;
}
if (hs.finishtime < finishtime) {
return 1;
}
return 0;
}
}

View File

@@ -0,0 +1,277 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* NetworkVmAllocationPolicy is an VmAllocationPolicy that chooses, as the host for a VM, the host
* with less PEs in use.
*
* @author Rodrigo N. Calheiros
* @author Anton Beloglazov
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class NetworkVmAllocationPolicy extends VmAllocationPolicy {
/** The vm table. */
private Map<String, Host> vmTable;
/** The used pes. */
private Map<String, Integer> usedPes;
/** The free pes. */
private List<Integer> freePes;
/**
* Creates the new VmAllocationPolicySimple object.
*
* @param list the list
*
* @pre $none
* @post $none
*/
public NetworkVmAllocationPolicy(List<? extends Host> list) {
super(list);
setFreePes(new ArrayList<Integer>());
for (Host host : getHostList()) {
getFreePes().add(host.getNumberOfPes());
}
setVmTable(new HashMap<String, Host>());
setUsedPes(new HashMap<String, Integer>());
}
/**
* Allocates a host for a given VM.
*
* @param vm VM specification
*
* @return $true if the host could be allocated; $false otherwise
*
* @pre $none
* @post $none
*/
@Override
public boolean allocateHostForVm(Vm vm) {
int requiredPes = vm.getNumberOfPes();
boolean result = false;
int tries = 0;
List<Integer> freePesTmp = new ArrayList<Integer>();
for (Integer freePes : getFreePes()) {
freePesTmp.add(freePes);
}
if (!getVmTable().containsKey(vm.getUid())) { // if this vm was not created
do {// we still trying until we find a host or until we try all of them
int moreFree = Integer.MIN_VALUE;
int idx = -1;
// we want the host with less pes in use
for (int i = 0; i < freePesTmp.size(); i++) {
if (freePesTmp.get(i) > moreFree) {
moreFree = freePesTmp.get(i);
idx = i;
}
}
NetworkHost host = this.<NetworkHost> getHostList().get(idx);
result = host.vmCreate(vm);
if (result) { // if vm were succesfully created in the host
getVmTable().put(vm.getUid(), host);
getUsedPes().put(vm.getUid(), requiredPes);
getFreePes().set(idx, getFreePes().get(idx) - requiredPes);
result = true;
break;
} else {
freePesTmp.set(idx, Integer.MIN_VALUE);
}
tries++;
} while (!result && tries < getFreePes().size());
}
return result;
}
protected double getMaxUtilizationAfterAllocation(NetworkHost host, Vm vm) {
List<Double> allocatedMipsForVm = null;
NetworkHost allocatedHost = (NetworkHost) vm.getHost();
if (allocatedHost != null) {
allocatedMipsForVm = vm.getHost().getAllocatedMipsForVm(vm);
}
if (!host.allocatePesForVm(vm, vm.getCurrentRequestedMips())) {
return -1;
}
double maxUtilization = host.getMaxUtilizationAmongVmsPes(vm);
host.deallocatePesForVm(vm);
if (allocatedHost != null && allocatedMipsForVm != null) {
vm.getHost().allocatePesForVm(vm, allocatedMipsForVm);
}
return maxUtilization;
}
/**
* Releases the host used by a VM.
*
* @param vm the vm
*
* @pre $none
* @post none
*/
@Override
public void deallocateHostForVm(Vm vm) {
Host host = getVmTable().remove(vm.getUid());
int idx = getHostList().indexOf(host);
int pes = getUsedPes().remove(vm.getUid());
if (host != null) {
host.vmDestroy(vm);
getFreePes().set(idx, getFreePes().get(idx) + pes);
}
}
/**
* Gets the host that is executing the given VM belonging to the given user.
*
* @param vm the vm
*
* @return the Host with the given vmID and userID; $null if not found
*
* @pre $none
* @post $none
*/
@Override
public Host getHost(Vm vm) {
return getVmTable().get(vm.getUid());
}
/**
* Gets the host that is executing the given VM belonging to the given user.
*
* @param vmId the vm id
* @param userId the user id
*
* @return the Host with the given vmID and userID; $null if not found
*
* @pre $none
* @post $none
*/
@Override
public Host getHost(int vmId, int userId) {
return getVmTable().get(Vm.getUid(userId, vmId));
}
/**
* Gets the vm table.
*
* @return the vm table
*/
public Map<String, Host> getVmTable() {
return vmTable;
}
/**
* Sets the vm table.
*
* @param vmTable the vm table
*/
protected void setVmTable(Map<String, Host> vmTable) {
this.vmTable = vmTable;
}
/**
* Gets the used pes.
*
* @return the used pes
*/
protected Map<String, Integer> getUsedPes() {
return usedPes;
}
/**
* Sets the used pes.
*
* @param usedPes the used pes
*/
protected void setUsedPes(Map<String, Integer> usedPes) {
this.usedPes = usedPes;
}
/**
* Gets the free pes.
*
* @return the free pes
*/
protected List<Integer> getFreePes() {
return freePes;
}
/**
* Sets the free pes.
*
* @param freePes the new free pes
*/
protected void setFreePes(List<Integer> freePes) {
this.freePes = freePes;
}
/*
* (non-Javadoc)
* @see cloudsim.VmAllocationPolicy#optimizeAllocation(double, cloudsim.VmList, double)
*/
@Override
public List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#allocateHostForVm(org.cloudbus.cloudsim.Vm,
* org.cloudbus.cloudsim.Host)
*/
@Override
public boolean allocateHostForVm(Vm vm, Host host) {
if (host.vmCreate(vm)) { // if vm has been succesfully created in the host
getVmTable().put(vm.getUid(), host);
int requiredPes = vm.getNumberOfPes();
int idx = getHostList().indexOf(host);
getUsedPes().put(vm.getUid(), requiredPes);
getFreePes().set(idx, getFreePes().get(idx) - requiredPes);
Log.formatLine(
"%.2f: VM #" + vm.getId() + " has been allocated to the host #" + host.getId(),
CloudSim.clock());
return true;
}
return false;
}
}

View File

@@ -0,0 +1,97 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
/**
* This class allows to simulate Root switch which connects Datacenter to external network. It
* interacts with other switches in order to exchange packets.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 3.0
*/
public class RootSwitch extends Switch {
/**
* Constructor for Root Switch We have to specify switches that are connected to its downlink
* ports, and corresponding bandwidths
*
* @param name Name of the switch
* @param level At which level switch is with respect to hosts.
* @param dc Pointer to Datacenter
*/
public RootSwitch(String name, int level, NetworkDatacenter dc) {
super(name, level, dc);
downlinkswitchpktlist = new HashMap<Integer, List<NetworkPacket>>();
downlinkswitches = new ArrayList<Switch>();
downlinkbandwidth = NetworkConstants.BandWidthAggRoot;
latency = NetworkConstants.SwitchingDelayRoot;
numport = NetworkConstants.RootSwitchPort;
}
/**
* Send Packet to switch connected through a downlink port
*
* @param ev Event/packet to process
*/
@Override
protected void processpacket_up(SimEvent ev) {
// packet coming from down level router.
// has to send up
// check which switch to forward to
// add packet in the switch list
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), switching_delay, CloudSimTags.Network_Event_send);
if (level == NetworkConstants.ROOT_LEVEL) {
// get id of edge router
int edgeswitchid = dc.VmToSwitchid.get(recvVMid);
// search which aggregate switch has it
int aggSwtichid = -1;
;
for (Switch sw : downlinkswitches) {
for (Switch edge : sw.downlinkswitches) {
if (edge.getId() == edgeswitchid) {
aggSwtichid = sw.getId();
break;
}
}
}
if (aggSwtichid < 0) {
System.out.println(" No destination for this packet");
} else {
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(aggSwtichid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(aggSwtichid, pktlist);
}
pktlist.add(hspkt);
}
}
}
}

View File

@@ -0,0 +1,386 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
import org.cloudbus.cloudsim.lists.VmList;
public class Switch extends SimEntity {
// switch level
public int id;
public int level;// three levels
public int datacenterid;
public Map<Integer, List<NetworkPacket>> uplinkswitchpktlist;
public Map<Integer, List<NetworkPacket>> downlinkswitchpktlist;
public Map<Integer, NetworkHost> hostlist;
public List<Switch> uplinkswitches;
public List<Switch> downlinkswitches;
public Map<Integer, List<NetworkPacket>> packetTohost;
int type;// edge switch or aggregation switch
public double uplinkbandwidth;
public double downlinkbandwidth;
public double latency;
public double numport;
public NetworkDatacenter dc;
// something is running on these hosts
public SortedMap<Double, List<NetworkHost>> fintimelistHost = new TreeMap<Double, List<NetworkHost>>();
// something is running on these hosts
public SortedMap<Double, List<NetworkVm>> fintimelistVM = new TreeMap<Double, List<NetworkVm>>();
public ArrayList<NetworkPacket> pktlist;
public List<Vm> BagofTaskVm = new ArrayList<Vm>();
public double switching_delay;
public Map<Integer, NetworkVm> Vmlist;
public Switch(String name, int level, NetworkDatacenter dc) {
super(name);
this.level = level;
this.dc = dc;
}
@Override
public void startEntity() {
Log.printLine(getName() + " is starting...");
schedule(getId(), 0, CloudSimTags.RESOURCE_CHARACTERISTICS_REQUEST);
}
@Override
public void processEvent(SimEvent ev) {
// Log.printLine(CloudSim.clock()+"[Broker]: event received:"+ev.getTag());
switch (ev.getTag()) {
// Resource characteristics request
case CloudSimTags.Network_Event_UP:
// process the packet from down switch or host
processpacket_up(ev);
break;
case CloudSimTags.Network_Event_DOWN:
// process the packet from uplink
processpacket_down(ev);
break;
case CloudSimTags.Network_Event_send:
processpacketforward(ev);
break;
case CloudSimTags.Network_Event_Host:
processhostpacket(ev);
break;
// Resource characteristics answer
case CloudSimTags.RESOURCE_Register:
registerHost(ev);
break;
// other unknown tags are processed by this method
default:
processOtherEvent(ev);
break;
}
}
protected void processhostpacket(SimEvent ev) {
// Send packet to host
NetworkPacket hspkt = (NetworkPacket) ev.getData();
NetworkHost hs = hostlist.get(hspkt.recieverhostid);
hs.packetrecieved.add(hspkt);
}
protected void processpacket_down(SimEvent ev) {
// packet coming from up level router.
// has to send downward
// check which switch to forward to
// add packet in the switch list
// add packet in the host list
// int src=ev.getSource();
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), latency, CloudSimTags.Network_Event_send);
if (level == NetworkConstants.EDGE_LEVEL) {
// packet is to be recieved by host
int hostid = dc.VmtoHostlist.get(recvVMid);
hspkt.recieverhostid = hostid;
List<NetworkPacket> pktlist = packetTohost.get(hostid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
packetTohost.put(hostid, pktlist);
}
pktlist.add(hspkt);
return;
}
if (level == NetworkConstants.Agg_LEVEL) {
// packet is coming from root so need to be sent to edgelevel swich
// find the id for edgelevel switch
int switchid = dc.VmToSwitchid.get(recvVMid);
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(switchid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(switchid, pktlist);
}
pktlist.add(hspkt);
return;
}
}
protected void processpacket_up(SimEvent ev) {
// packet coming from down level router.
// has to send up
// check which switch to forward to
// add packet in the switch list
//
// int src=ev.getSource();
NetworkPacket hspkt = (NetworkPacket) ev.getData();
int recvVMid = hspkt.pkt.reciever;
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_send));
schedule(getId(), switching_delay, CloudSimTags.Network_Event_send);
if (level == NetworkConstants.EDGE_LEVEL) {
// packet is recieved from host
// packet is to be sent to aggregate level or to another host in the
// same level
int hostid = dc.VmtoHostlist.get(recvVMid);
NetworkHost hs = hostlist.get(hostid);
hspkt.recieverhostid = hostid;
if (hs != null) {
// packet to be sent to host connected to the switch
List<NetworkPacket> pktlist = packetTohost.get(hostid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
packetTohost.put(hostid, pktlist);
}
pktlist.add(hspkt);
return;
}
// packet is to be sent to upper switch
// ASSUMPTION EACH EDGE is Connected to one aggregate level switch
Switch sw = uplinkswitches.get(0);
List<NetworkPacket> pktlist = uplinkswitchpktlist.get(sw.getId());
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
uplinkswitchpktlist.put(sw.getId(), pktlist);
}
pktlist.add(hspkt);
return;
}
if (level == NetworkConstants.Agg_LEVEL) {
// packet is coming from edge level router so need to be sent to
// either root or another edge level swich
// find the id for edgelevel switch
int switchid = dc.VmToSwitchid.get(recvVMid);
boolean flagtoswtich = false;
for (Switch sw : downlinkswitches) {
if (switchid == sw.getId()) {
flagtoswtich = true;
}
}
if (flagtoswtich) {
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(switchid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(switchid, pktlist);
}
pktlist.add(hspkt);
} else// send to up
{
Switch sw = uplinkswitches.get(0);
List<NetworkPacket> pktlist = uplinkswitchpktlist.get(sw.getId());
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
uplinkswitchpktlist.put(sw.getId(), pktlist);
}
pktlist.add(hspkt);
}
}
if (level == NetworkConstants.ROOT_LEVEL) {
// get id of edge router
int edgeswitchid = dc.VmToSwitchid.get(recvVMid);
// search which aggregate switch has it
int aggSwtichid = -1;
;
for (Switch sw : downlinkswitches) {
for (Switch edge : sw.downlinkswitches) {
if (edge.getId() == edgeswitchid) {
aggSwtichid = sw.getId();
break;
}
}
}
if (aggSwtichid < 0) {
System.out.println(" No destination for this packet");
} else {
List<NetworkPacket> pktlist = downlinkswitchpktlist.get(aggSwtichid);
if (pktlist == null) {
pktlist = new ArrayList<NetworkPacket>();
downlinkswitchpktlist.put(aggSwtichid, pktlist);
}
pktlist.add(hspkt);
}
}
}
private void registerHost(SimEvent ev) {
NetworkHost hs = (NetworkHost) ev.getData();
hostlist.put(hs.getId(), (NetworkHost) ev.getData());
}
protected void processpacket(SimEvent ev) {
// send packet to itself with switching delay (discarding other)
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.Network_Event_UP));
schedule(getId(), switching_delay, CloudSimTags.Network_Event_UP);
pktlist.add((NetworkPacket) ev.getData());
// add the packet in the list
}
private void processOtherEvent(SimEvent ev) {
}
protected void processpacketforward(SimEvent ev) {
// search for the host and packets..send to them
if (downlinkswitchpktlist != null) {
for (Entry<Integer, List<NetworkPacket>> es : downlinkswitchpktlist.entrySet()) {
int tosend = es.getKey();
List<NetworkPacket> hspktlist = es.getValue();
if (!hspktlist.isEmpty()) {
double avband = downlinkbandwidth / hspktlist.size();
Iterator<NetworkPacket> it = hspktlist.iterator();
while (it.hasNext()) {
NetworkPacket hspkt = it.next();
double delay = 1000 * hspkt.pkt.data / avband;
this.send(tosend, delay, CloudSimTags.Network_Event_DOWN, hspkt);
}
hspktlist.clear();
}
}
}
if (uplinkswitchpktlist != null) {
for (Entry<Integer, List<NetworkPacket>> es : uplinkswitchpktlist.entrySet()) {
int tosend = es.getKey();
List<NetworkPacket> hspktlist = es.getValue();
if (!hspktlist.isEmpty()) {
double avband = uplinkbandwidth / hspktlist.size();
Iterator<NetworkPacket> it = hspktlist.iterator();
while (it.hasNext()) {
NetworkPacket hspkt = it.next();
double delay = 1000 * hspkt.pkt.data / avband;
this.send(tosend, delay, CloudSimTags.Network_Event_UP, hspkt);
}
hspktlist.clear();
}
}
}
if (packetTohost != null) {
for (Entry<Integer, List<NetworkPacket>> es : packetTohost.entrySet()) {
List<NetworkPacket> hspktlist = es.getValue();
if (!hspktlist.isEmpty()) {
double avband = downlinkbandwidth / hspktlist.size();
Iterator<NetworkPacket> it = hspktlist.iterator();
while (it.hasNext()) {
NetworkPacket hspkt = it.next();
// hspkt.recieverhostid=tosend;
// hs.packetrecieved.add(hspkt);
this.send(getId(), hspkt.pkt.data / avband, CloudSimTags.Network_Event_Host, hspkt);
}
hspktlist.clear();
}
}
}
// or to switch at next level.
// clear the list
}
//
// R: We changed visibility of the below methods from private to protected.
//
protected NetworkHost getHostwithVM(int vmid) {
for (Entry<Integer, NetworkHost> es : hostlist.entrySet()) {
Vm vm = VmList.getById(es.getValue().getVmList(), vmid);
if (vm != null) {
return es.getValue();
}
}
return null;
}
protected List<NetworkVm> getfreeVmlist(int numVMReq) {
List<NetworkVm> freehostls = new ArrayList<NetworkVm>();
for (Entry<Integer, NetworkVm> et : Vmlist.entrySet()) {
if (et.getValue().isFree()) {
freehostls.add(et.getValue());
}
if (freehostls.size() == numVMReq) {
break;
}
}
return freehostls;
}
protected List<NetworkHost> getfreehostlist(int numhost) {
List<NetworkHost> freehostls = new ArrayList<NetworkHost>();
for (Entry<Integer, NetworkHost> et : hostlist.entrySet()) {
if (et.getValue().getNumberOfFreePes() == et.getValue().getNumberOfPes()) {
freehostls.add(et.getValue());
}
if (freehostls.size() == numhost) {
break;
}
}
return freehostls;
}
@Override
public void shutdownEntity() {
Log.printLine(getName() + " is shutting down...");
}
}

View File

@@ -0,0 +1,52 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
/**
* Taskstage represents various stages a networkCloudlet can have during execution. Four stage types
* which are possible-> EXECUTION=0; WAIT_SEND=1; WAIT_RECV=2; FINISH=-2; Check NeworkConstants.java
* file for that.
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class TaskStage {
public TaskStage(int type, double data, double time, double stageid, long memory, int peer, int vpeer) {
super();
this.type = type;
this.data = data;
this.time = time;
this.stageid = stageid;
this.memory = memory;
this.peer = peer;
this.vpeer = vpeer;
}
int vpeer;
int type;// execution, recv, send,
double data;// data generated or send or recv
double time;// execution time for this stage
double stageid;
long memory;
int peer;// from whom data needed to be recieved or send
}

View File

@@ -0,0 +1,138 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.List;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* WorkflowApp is an example of AppCloudlet having three communicating tasks. Task A and B sends the
* data (packet) while Task C receives them
*
* Please refer to following publication for more details:
*
* Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
*/
public class WorkflowApp extends AppCloudlet {
public WorkflowApp(int type, int appID, double deadline, int numbervm, int userId) {
super(type, appID, deadline, numbervm, userId);
exeTime = 100;
this.numbervm = 3;
}
@Override
public void createCloudletList(List<Integer> vmIdList) {
long fileSize = NetworkConstants.FILE_SIZE;
long outputSize = NetworkConstants.OUTPUT_SIZE;
int memory = 100;
UtilizationModel utilizationModel = new UtilizationModelFull();
int i = 0;
// Task A
NetworkCloudlet cl = new NetworkCloudlet(
NetworkConstants.currentCloudletId,
0,
1,
fileSize,
outputSize,
memory,
utilizationModel,
utilizationModel,
utilizationModel);
cl.numStage = 2;
NetworkConstants.currentCloudletId++;
cl.setUserId(userId);
cl.submittime = CloudSim.clock();
cl.currStagenum = -1;
cl.setVmId(vmIdList.get(i));
// first stage: big computation
cl.stages.add(new TaskStage(NetworkConstants.EXECUTION, 0, 1000 * 0.8, 0, memory, vmIdList.get(0), cl
.getCloudletId()));
cl.stages.add(new TaskStage(NetworkConstants.WAIT_SEND, 1000, 0, 1, memory, vmIdList.get(2), cl
.getCloudletId() + 2));
clist.add(cl);
i++;
// Task B
NetworkCloudlet clb = new NetworkCloudlet(
NetworkConstants.currentCloudletId,
0,
1,
fileSize,
outputSize,
memory,
utilizationModel,
utilizationModel,
utilizationModel);
clb.numStage = 2;
NetworkConstants.currentCloudletId++;
clb.setUserId(userId);
clb.submittime = CloudSim.clock();
clb.currStagenum = -1;
clb.setVmId(vmIdList.get(i));
// first stage: big computation
clb.stages.add(new TaskStage(
NetworkConstants.EXECUTION,
0,
1000 * 0.8,
0,
memory,
vmIdList.get(1),
clb.getCloudletId()));
clb.stages.add(new TaskStage(NetworkConstants.WAIT_SEND, 1000, 0, 1, memory, vmIdList.get(2), clb
.getCloudletId() + 1));
clist.add(clb);
i++;
// Task C
NetworkCloudlet clc = new NetworkCloudlet(
NetworkConstants.currentCloudletId,
0,
1,
fileSize,
outputSize,
memory,
utilizationModel,
utilizationModel,
utilizationModel);
clc.numStage = 2;
NetworkConstants.currentCloudletId++;
clc.setUserId(userId);
clc.submittime = CloudSim.clock();
clc.currStagenum = -1;
clc.setVmId(vmIdList.get(i));
// first stage: big computation
clc.stages.add(new TaskStage(NetworkConstants.WAIT_RECV, 1000, 0, 0, memory, vmIdList.get(0), cl
.getCloudletId()));
clc.stages.add(new TaskStage(NetworkConstants.WAIT_RECV, 1000, 0, 1, memory, vmIdList.get(1), cl
.getCloudletId() + 1));
clc.stages.add(new TaskStage(
NetworkConstants.EXECUTION,
0,
1000 * 0.8,
1,
memory,
vmIdList.get(0),
clc.getCloudletId()));
clist.add(clc);
}
}

View File

@@ -0,0 +1,368 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
/**
* PowerDatacenter is a class that enables simulation of power-aware data centers.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerDatacenter extends Datacenter {
/** The power. */
private double power;
/** The disable migrations. */
private boolean disableMigrations;
/** The cloudlet submited. */
private double cloudletSubmitted;
/** The migration count. */
private int migrationCount;
/**
* Instantiates a new datacenter.
*
* @param name the name
* @param characteristics the res config
* @param schedulingInterval the scheduling interval
* @param utilizationBound the utilization bound
* @param vmAllocationPolicy the vm provisioner
* @param storageList the storage list
* @throws Exception the exception
*/
public PowerDatacenter(
String name,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
setPower(0.0);
setDisableMigrations(false);
setCloudletSubmitted(-1);
setMigrationCount(0);
}
/**
* Updates processing of each cloudlet running in this PowerDatacenter. It is necessary because
* Hosts and VirtualMachines are simple objects, not entities. So, they don't receive events and
* updating cloudlets inside them must be called from the outside.
*
* @pre $none
* @post $none
*/
@Override
protected void updateCloudletProcessing() {
if (getCloudletSubmitted() == -1 || getCloudletSubmitted() == CloudSim.clock()) {
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.VM_DATACENTER_EVENT));
schedule(getId(), getSchedulingInterval(), CloudSimTags.VM_DATACENTER_EVENT);
return;
}
double currentTime = CloudSim.clock();
// if some time passed since last processing
if (currentTime > getLastProcessTime()) {
double minTime = updateCloudetProcessingWithoutSchedulingFutureEventsForce();
if (!isDisableMigrations()) {
List<Map<String, Object>> migrationMap = getVmAllocationPolicy().optimizeAllocation(
getVmList());
if (migrationMap != null) {
for (Map<String, Object> migrate : migrationMap) {
Vm vm = (Vm) migrate.get("vm");
PowerHost targetHost = (PowerHost) migrate.get("host");
PowerHost oldHost = (PowerHost) vm.getHost();
if (oldHost == null) {
Log.formatLine(
"%.2f: Migration of VM #%d to Host #%d is started",
currentTime,
vm.getId(),
targetHost.getId());
} else {
Log.formatLine(
"%.2f: Migration of VM #%d from Host #%d to Host #%d is started",
currentTime,
vm.getId(),
oldHost.getId(),
targetHost.getId());
}
targetHost.addMigratingInVm(vm);
incrementMigrationCount();
/** VM migration delay = RAM / bandwidth **/
// we use BW / 2 to model BW available for migration purposes, the other
// half of BW is for VM communication
// around 16 seconds for 1024 MB using 1 Gbit/s network
send(
getId(),
vm.getRam() / ((double) targetHost.getBw() / (2 * 8000)),
CloudSimTags.VM_MIGRATE,
migrate);
}
}
}
// schedules an event to the next time
if (minTime != Double.MAX_VALUE) {
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.VM_DATACENTER_EVENT));
send(getId(), getSchedulingInterval(), CloudSimTags.VM_DATACENTER_EVENT);
}
setLastProcessTime(currentTime);
}
}
/**
* Update cloudet processing without scheduling future events.
*
* @return the double
*/
protected double updateCloudetProcessingWithoutSchedulingFutureEvents() {
if (CloudSim.clock() > getLastProcessTime()) {
return updateCloudetProcessingWithoutSchedulingFutureEventsForce();
}
return 0;
}
/**
* Update cloudet processing without scheduling future events.
*
* @return the double
*/
protected double updateCloudetProcessingWithoutSchedulingFutureEventsForce() {
double currentTime = CloudSim.clock();
double minTime = Double.MAX_VALUE;
double timeDiff = currentTime - getLastProcessTime();
double timeFrameDatacenterEnergy = 0.0;
Log.printLine("\n\n--------------------------------------------------------------\n\n");
Log.formatLine("New resource usage for the time frame starting at %.2f:", currentTime);
for (PowerHost host : this.<PowerHost> getHostList()) {
Log.printLine();
double time = host.updateVmsProcessing(currentTime); // inform VMs to update processing
if (time < minTime) {
minTime = time;
}
Log.formatLine(
"%.2f: [Host #%d] utilization is %.2f%%",
currentTime,
host.getId(),
host.getUtilizationOfCpu() * 100);
}
if (timeDiff > 0) {
Log.formatLine(
"\nEnergy consumption for the last time frame from %.2f to %.2f:",
getLastProcessTime(),
currentTime);
for (PowerHost host : this.<PowerHost> getHostList()) {
double previousUtilizationOfCpu = host.getPreviousUtilizationOfCpu();
double utilizationOfCpu = host.getUtilizationOfCpu();
double timeFrameHostEnergy = host.getEnergyLinearInterpolation(
previousUtilizationOfCpu,
utilizationOfCpu,
timeDiff);
timeFrameDatacenterEnergy += timeFrameHostEnergy;
Log.printLine();
Log.formatLine(
"%.2f: [Host #%d] utilization at %.2f was %.2f%%, now is %.2f%%",
currentTime,
host.getId(),
getLastProcessTime(),
previousUtilizationOfCpu * 100,
utilizationOfCpu * 100);
Log.formatLine(
"%.2f: [Host #%d] energy is %.2f W*sec",
currentTime,
host.getId(),
timeFrameHostEnergy);
}
Log.formatLine(
"\n%.2f: Data center's energy is %.2f W*sec\n",
currentTime,
timeFrameDatacenterEnergy);
}
setPower(getPower() + timeFrameDatacenterEnergy);
checkCloudletCompletion();
/** Remove completed VMs **/
for (PowerHost host : this.<PowerHost> getHostList()) {
for (Vm vm : host.getCompletedVms()) {
getVmAllocationPolicy().deallocateHostForVm(vm);
getVmList().remove(vm);
Log.printLine("VM #" + vm.getId() + " has been deallocated from host #" + host.getId());
}
}
Log.printLine();
setLastProcessTime(currentTime);
return minTime;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.Datacenter#processVmMigrate(org.cloudbus.cloudsim.core.SimEvent,
* boolean)
*/
@Override
protected void processVmMigrate(SimEvent ev, boolean ack) {
updateCloudetProcessingWithoutSchedulingFutureEvents();
super.processVmMigrate(ev, ack);
SimEvent event = CloudSim.findFirstDeferred(getId(), new PredicateType(CloudSimTags.VM_MIGRATE));
if (event == null || event.eventTime() > CloudSim.clock()) {
updateCloudetProcessingWithoutSchedulingFutureEventsForce();
}
}
/*
* (non-Javadoc)
* @see cloudsim.Datacenter#processCloudletSubmit(cloudsim.core.SimEvent, boolean)
*/
@Override
protected void processCloudletSubmit(SimEvent ev, boolean ack) {
super.processCloudletSubmit(ev, ack);
setCloudletSubmitted(CloudSim.clock());
}
/**
* Gets the power.
*
* @return the power
*/
public double getPower() {
return power;
}
/**
* Sets the power.
*
* @param power the new power
*/
protected void setPower(double power) {
this.power = power;
}
/**
* Checks if PowerDatacenter is in migration.
*
* @return true, if PowerDatacenter is in migration
*/
protected boolean isInMigration() {
boolean result = false;
for (Vm vm : getVmList()) {
if (vm.isInMigration()) {
result = true;
break;
}
}
return result;
}
/**
* Checks if is disable migrations.
*
* @return true, if is disable migrations
*/
public boolean isDisableMigrations() {
return disableMigrations;
}
/**
* Sets the disable migrations.
*
* @param disableMigrations the new disable migrations
*/
public void setDisableMigrations(boolean disableMigrations) {
this.disableMigrations = disableMigrations;
}
/**
* Checks if is cloudlet submited.
*
* @return true, if is cloudlet submited
*/
protected double getCloudletSubmitted() {
return cloudletSubmitted;
}
/**
* Sets the cloudlet submited.
*
* @param cloudletSubmitted the new cloudlet submited
*/
protected void setCloudletSubmitted(double cloudletSubmitted) {
this.cloudletSubmitted = cloudletSubmitted;
}
/**
* Gets the migration count.
*
* @return the migration count
*/
public int getMigrationCount() {
return migrationCount;
}
/**
* Sets the migration count.
*
* @param migrationCount the new migration count
*/
protected void setMigrationCount(int migrationCount) {
this.migrationCount = migrationCount;
}
/**
* Increment migration count.
*/
protected void incrementMigrationCount() {
setMigrationCount(getMigrationCount() + 1);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
/**
* A broker for the power package.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerDatacenterBroker extends DatacenterBroker {
/**
* Instantiates a new power datacenter broker.
*
* @param name the name
* @throws Exception the exception
*/
public PowerDatacenterBroker(String name) throws Exception {
super(name);
}
/*
* (non-Javadoc)
* @see
* org.cloudbus.cloudsim.DatacenterBroker#processVmCreate(org.cloudbus.cloudsim.core.SimEvent)
*/
@Override
protected void processVmCreate(SimEvent ev) {
int[] data = (int[]) ev.getData();
int result = data[2];
if (result != CloudSimTags.TRUE) {
int datacenterId = data[0];
int vmId = data[1];
System.out.println(CloudSim.clock() + ": " + getName() + ": Creation of VM #" + vmId
+ " failed in Datacenter #" + datacenterId);
System.exit(0);
}
super.processVmCreate(ev);
}
}

View File

@@ -0,0 +1,187 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.predicates.PredicateType;
/**
* PowerDatacenterNonPowerAware is a class that represents a non-power aware data center in the
* context of power-aware simulations.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerDatacenterNonPowerAware extends PowerDatacenter {
/**
* Instantiates a new datacenter.
*
* @param name the name
* @param characteristics the res config
* @param schedulingInterval the scheduling interval
* @param utilizationBound the utilization bound
* @param vmAllocationPolicy the vm provisioner
* @param storageList the storage list
*
* @throws Exception the exception
*/
public PowerDatacenterNonPowerAware(
String name,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
}
/**
* Updates processing of each cloudlet running in this PowerDatacenter. It is necessary because
* Hosts and VirtualMachines are simple objects, not entities. So, they don't receive events and
* updating cloudlets inside them must be called from the outside.
*
* @pre $none
* @post $none
*/
@Override
protected void updateCloudletProcessing() {
if (getCloudletSubmitted() == -1 || getCloudletSubmitted() == CloudSim.clock()) {
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.VM_DATACENTER_EVENT));
schedule(getId(), getSchedulingInterval(), CloudSimTags.VM_DATACENTER_EVENT);
return;
}
double currentTime = CloudSim.clock();
double timeframePower = 0.0;
if (currentTime > getLastProcessTime()) {
double timeDiff = currentTime - getLastProcessTime();
double minTime = Double.MAX_VALUE;
Log.printLine("\n");
for (PowerHost host : this.<PowerHost> getHostList()) {
Log.formatLine("%.2f: Host #%d", CloudSim.clock(), host.getId());
double hostPower = 0.0;
try {
hostPower = host.getMaxPower() * timeDiff;
timeframePower += hostPower;
} catch (Exception e) {
e.printStackTrace();
}
Log.formatLine(
"%.2f: Host #%d utilization is %.2f%%",
CloudSim.clock(),
host.getId(),
host.getUtilizationOfCpu() * 100);
Log.formatLine(
"%.2f: Host #%d energy is %.2f W*sec",
CloudSim.clock(),
host.getId(),
hostPower);
}
Log.formatLine("\n%.2f: Consumed energy is %.2f W*sec\n", CloudSim.clock(), timeframePower);
Log.printLine("\n\n--------------------------------------------------------------\n\n");
for (PowerHost host : this.<PowerHost> getHostList()) {
Log.formatLine("\n%.2f: Host #%d", CloudSim.clock(), host.getId());
double time = host.updateVmsProcessing(currentTime); // inform VMs to update
// processing
if (time < minTime) {
minTime = time;
}
}
setPower(getPower() + timeframePower);
checkCloudletCompletion();
/** Remove completed VMs **/
for (PowerHost host : this.<PowerHost> getHostList()) {
for (Vm vm : host.getCompletedVms()) {
getVmAllocationPolicy().deallocateHostForVm(vm);
getVmList().remove(vm);
Log.printLine("VM #" + vm.getId() + " has been deallocated from host #" + host.getId());
}
}
Log.printLine();
if (!isDisableMigrations()) {
List<Map<String, Object>> migrationMap = getVmAllocationPolicy().optimizeAllocation(
getVmList());
if (migrationMap != null) {
for (Map<String, Object> migrate : migrationMap) {
Vm vm = (Vm) migrate.get("vm");
PowerHost targetHost = (PowerHost) migrate.get("host");
PowerHost oldHost = (PowerHost) vm.getHost();
if (oldHost == null) {
Log.formatLine(
"%.2f: Migration of VM #%d to Host #%d is started",
CloudSim.clock(),
vm.getId(),
targetHost.getId());
} else {
Log.formatLine(
"%.2f: Migration of VM #%d from Host #%d to Host #%d is started",
CloudSim.clock(),
vm.getId(),
oldHost.getId(),
targetHost.getId());
}
targetHost.addMigratingInVm(vm);
incrementMigrationCount();
/** VM migration delay = RAM / bandwidth + C (C = 10 sec) **/
send(
getId(),
vm.getRam() / ((double) vm.getBw() / 8000) + 10,
CloudSimTags.VM_MIGRATE,
migrate);
}
}
}
// schedules an event to the next time
if (minTime != Double.MAX_VALUE) {
CloudSim.cancelAll(getId(), new PredicateType(CloudSimTags.VM_DATACENTER_EVENT));
// CloudSim.cancelAll(getId(), CloudSim.SIM_ANY);
send(getId(), getSchedulingInterval(), CloudSimTags.VM_DATACENTER_EVENT);
}
setLastProcessTime(currentTime);
}
}
}

View File

@@ -0,0 +1,138 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import org.cloudbus.cloudsim.HostDynamicWorkload;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.VmScheduler;
import org.cloudbus.cloudsim.power.models.PowerModel;
import org.cloudbus.cloudsim.provisioners.BwProvisioner;
import org.cloudbus.cloudsim.provisioners.RamProvisioner;
/**
* PowerHost class enables simulation of power-aware hosts.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerHost extends HostDynamicWorkload {
/** The power model. */
private PowerModel powerModel;
/**
* Instantiates a new host.
*
* @param id the id
* @param ramProvisioner the ram provisioner
* @param bwProvisioner the bw provisioner
* @param storage the storage
* @param peList the pe list
* @param vmScheduler the VM scheduler
*/
public PowerHost(
int id,
RamProvisioner ramProvisioner,
BwProvisioner bwProvisioner,
long storage,
List<? extends Pe> peList,
VmScheduler vmScheduler,
PowerModel powerModel) {
super(id, ramProvisioner, bwProvisioner, storage, peList, vmScheduler);
setPowerModel(powerModel);
}
/**
* Gets the power. For this moment only consumed by all PEs.
*
* @return the power
*/
public double getPower() {
return getPower(getUtilizationOfCpu());
}
/**
* Gets the power. For this moment only consumed by all PEs.
*
* @param utilization the utilization
* @return the power
*/
protected double getPower(double utilization) {
double power = 0;
try {
power = getPowerModel().getPower(utilization);
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
return power;
}
/**
* Gets the max power that can be consumed by the host.
*
* @return the max power
*/
public double getMaxPower() {
double power = 0;
try {
power = getPowerModel().getPower(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
return power;
}
/**
* Gets the energy consumption using linear interpolation of the utilization change.
*
* @param fromUtilization the from utilization
* @param toUtilization the to utilization
* @param time the time
* @return the energy
*/
public double getEnergyLinearInterpolation(double fromUtilization, double toUtilization, double time) {
if (fromUtilization == 0) {
return 0;
}
double fromPower = getPower(fromUtilization);
double toPower = getPower(toUtilization);
return (fromPower + (toPower - fromPower) / 2) * time;
}
/**
* Sets the power model.
*
* @param powerModel the new power model
*/
protected void setPowerModel(PowerModel powerModel) {
this.powerModel = powerModel;
}
/**
* Gets the power model.
*
* @return the power model
*/
public PowerModel getPowerModel() {
return powerModel;
}
}

View File

@@ -0,0 +1,75 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.VmScheduler;
import org.cloudbus.cloudsim.power.models.PowerModel;
import org.cloudbus.cloudsim.provisioners.BwProvisioner;
import org.cloudbus.cloudsim.provisioners.RamProvisioner;
import org.cloudbus.cloudsim.util.MathUtil;
/**
* The class of a host that stores its CPU utilization history. The history is used by VM allocation
* and selection policies.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerHostUtilizationHistory extends PowerHost {
/**
* Instantiates a new power host utilization history.
*
* @param id the id
* @param ramProvisioner the ram provisioner
* @param bwProvisioner the bw provisioner
* @param storage the storage
* @param peList the pe list
* @param vmScheduler the vm scheduler
* @param powerModel the power model
*/
public PowerHostUtilizationHistory(
int id,
RamProvisioner ramProvisioner,
BwProvisioner bwProvisioner,
long storage,
List<? extends Pe> peList,
VmScheduler vmScheduler,
PowerModel powerModel) {
super(id, ramProvisioner, bwProvisioner, storage, peList, vmScheduler, powerModel);
}
/**
* Gets the host utilization history.
*
* @return the host utilization history
*/
protected double[] getUtilizationHistory() {
double[] utilizationHistory = new double[PowerVm.HISTORY_LENGTH];
double hostMips = getTotalMips();
for (PowerVm vm : this.<PowerVm> getVmList()) {
for (int i = 0; i < vm.getUtilizationHistory().size(); i++) {
utilizationHistory[i] += vm.getUtilizationHistory().get(i) * vm.getMips() / hostMips;
}
}
return MathUtil.trimZeroTail(utilizationHistory);
}
}

View File

@@ -0,0 +1,225 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.util.MathUtil;
/**
* The class of a VM that stores its CPU utilization history. The history is used by VM allocation
* and selection policies.
*
* If you are using any algorithms, policies or workload included in the power package please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class PowerVm extends Vm {
/** The Constant HISTORY_LENGTH. */
public static final int HISTORY_LENGTH = 30;
/** The utilization history. */
private final List<Double> utilizationHistory = new LinkedList<Double>();
/** The previous time. */
private double previousTime;
/** The scheduling interval. */
private double schedulingInterval;
/**
* Instantiates a new power vm.
*
* @param id the id
* @param userId the user id
* @param mips the mips
* @param pesNumber the pes number
* @param ram the ram
* @param bw the bw
* @param size the size
* @param priority the priority
* @param vmm the vmm
* @param cloudletScheduler the cloudlet scheduler
* @param schedulingInterval the scheduling interval
*/
public PowerVm(
final int id,
final int userId,
final double mips,
final int pesNumber,
final int ram,
final long bw,
final long size,
final int priority,
final String vmm,
final CloudletScheduler cloudletScheduler,
final double schedulingInterval) {
super(id, userId, mips, pesNumber, ram, bw, size, vmm, cloudletScheduler);
setSchedulingInterval(schedulingInterval);
}
/**
* Updates the processing of cloudlets running on this VM.
*
* @param currentTime current simulation time
* @param mipsShare array with MIPS share of each Pe available to the scheduler
*
* @return time predicted completion time of the earliest finishing cloudlet, or 0 if there is
* no next events
*
* @pre currentTime >= 0
* @post $none
*/
@Override
public double updateVmProcessing(final double currentTime, final List<Double> mipsShare) {
double time = super.updateVmProcessing(currentTime, mipsShare);
if (currentTime > getPreviousTime() && (currentTime - 0.1) % getSchedulingInterval() == 0) {
double utilization = getTotalUtilizationOfCpu(getCloudletScheduler().getPreviousTime());
if (CloudSim.clock() != 0 || utilization != 0) {
addUtilizationHistoryValue(utilization);
}
setPreviousTime(currentTime);
}
return time;
}
/**
* Gets the utilization MAD in MIPS.
*
* @return the utilization mean in MIPS
*/
public double getUtilizationMad() {
double mad = 0;
if (!getUtilizationHistory().isEmpty()) {
int n = HISTORY_LENGTH;
if (HISTORY_LENGTH > getUtilizationHistory().size()) {
n = getUtilizationHistory().size();
}
double median = MathUtil.median(getUtilizationHistory());
double[] deviationSum = new double[n];
for (int i = 0; i < n; i++) {
deviationSum[i] = Math.abs(median - getUtilizationHistory().get(i));
}
mad = MathUtil.median(deviationSum);
}
return mad;
}
/**
* Gets the utilization mean in percents.
*
* @return the utilization mean in MIPS
*/
public double getUtilizationMean() {
double mean = 0;
if (!getUtilizationHistory().isEmpty()) {
int n = HISTORY_LENGTH;
if (HISTORY_LENGTH > getUtilizationHistory().size()) {
n = getUtilizationHistory().size();
}
for (int i = 0; i < n; i++) {
mean += getUtilizationHistory().get(i);
}
mean /= n;
}
return mean * getMips();
}
/**
* Gets the utilization variance in MIPS.
*
* @return the utilization variance in MIPS
*/
public double getUtilizationVariance() {
double mean = getUtilizationMean();
double variance = 0;
if (!getUtilizationHistory().isEmpty()) {
int n = HISTORY_LENGTH;
if (HISTORY_LENGTH > getUtilizationHistory().size()) {
n = getUtilizationHistory().size();
}
for (int i = 0; i < n; i++) {
double tmp = getUtilizationHistory().get(i) * getMips() - mean;
variance += tmp * tmp;
}
variance /= n;
}
return variance;
}
/**
* Adds the utilization history value.
*
* @param utilization the utilization
*/
public void addUtilizationHistoryValue(final double utilization) {
getUtilizationHistory().add(0, utilization);
if (getUtilizationHistory().size() > HISTORY_LENGTH) {
getUtilizationHistory().remove(HISTORY_LENGTH);
}
}
/**
* Gets the utilization history.
*
* @return the utilization history
*/
protected List<Double> getUtilizationHistory() {
return utilizationHistory;
}
/**
* Gets the previous time.
*
* @return the previous time
*/
public double getPreviousTime() {
return previousTime;
}
/**
* Sets the previous time.
*
* @param previousTime the new previous time
*/
public void setPreviousTime(final double previousTime) {
this.previousTime = previousTime;
}
/**
* Gets the scheduling interval.
*
* @return the schedulingInterval
*/
public double getSchedulingInterval() {
return schedulingInterval;
}
/**
* Sets the scheduling interval.
*
* @param schedulingInterval the schedulingInterval to set
*/
protected void setSchedulingInterval(final double schedulingInterval) {
this.schedulingInterval = schedulingInterval;
}
}

View File

@@ -0,0 +1,136 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* The class of an abstract power-aware VM allocation policy.
*
* If you are using any algorithms, policies or workload included in the power package, please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 3.0
*/
public abstract class PowerVmAllocationPolicyAbstract extends VmAllocationPolicy {
/** The vm table. */
private final Map<String, Host> vmTable = new HashMap<String, Host>();
/**
* Instantiates a new power vm allocation policy abstract.
*
* @param list the list
*/
public PowerVmAllocationPolicyAbstract(List<? extends Host> list) {
super(list);
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#allocateHostForVm(org.cloudbus.cloudsim.Vm)
*/
@Override
public boolean allocateHostForVm(Vm vm) {
return allocateHostForVm(vm, findHostForVm(vm));
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#allocateHostForVm(org.cloudbus.cloudsim.Vm,
* org.cloudbus.cloudsim.Host)
*/
@Override
public boolean allocateHostForVm(Vm vm, Host host) {
if (host == null) {
Log.formatLine("%.2f: No suitable host found for VM #" + vm.getId() + "\n", CloudSim.clock());
return false;
}
if (host.vmCreate(vm)) { // if vm has been succesfully created in the host
getVmTable().put(vm.getUid(), host);
Log.formatLine(
"%.2f: VM #" + vm.getId() + " has been allocated to the host #" + host.getId(),
CloudSim.clock());
return true;
}
Log.formatLine(
"%.2f: Creation of VM #" + vm.getId() + " on the host #" + host.getId() + " failed\n",
CloudSim.clock());
return false;
}
/**
* Find host for vm.
*
* @param vm the vm
* @return the power host
*/
public PowerHost findHostForVm(Vm vm) {
for (PowerHost host : this.<PowerHost> getHostList()) {
if (host.isSuitableForVm(vm)) {
return host;
}
}
return null;
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#deallocateHostForVm(org.cloudbus.cloudsim.Vm)
*/
@Override
public void deallocateHostForVm(Vm vm) {
Host host = getVmTable().remove(vm.getUid());
if (host != null) {
host.vmDestroy(vm);
}
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#getHost(org.cloudbus.cloudsim.Vm)
*/
@Override
public Host getHost(Vm vm) {
return getVmTable().get(vm.getUid());
}
/*
* (non-Javadoc)
* @see org.cloudbus.cloudsim.VmAllocationPolicy#getHost(int, int)
*/
@Override
public Host getHost(int vmId, int userId) {
return getVmTable().get(Vm.getUid(userId, vmId));
}
/**
* Gets the vm table.
*
* @return the vm table
*/
public Map<String, Host> getVmTable() {
return vmTable;
}
}

View File

@@ -0,0 +1,674 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.HostDynamicWorkload;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.lists.PowerVmList;
import org.cloudbus.cloudsim.util.ExecutionTimeMeasurer;
/**
* The class of an abstract power-aware VM allocation policy that dynamically optimizes the VM
* allocation using migration.
*
* If you are using any algorithms, policies or workload included in the power package, please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 3.0
*/
public abstract class PowerVmAllocationPolicyMigrationAbstract extends PowerVmAllocationPolicyAbstract {
/** The vm selection policy. */
private PowerVmSelectionPolicy vmSelectionPolicy;
/** The saved allocation. */
private final List<Map<String, Object>> savedAllocation = new ArrayList<Map<String, Object>>();
/** The utilization history. */
private final Map<Integer, List<Double>> utilizationHistory = new HashMap<Integer, List<Double>>();
/** The metric history. */
private final Map<Integer, List<Double>> metricHistory = new HashMap<Integer, List<Double>>();
/** The time history. */
private final Map<Integer, List<Double>> timeHistory = new HashMap<Integer, List<Double>>();
/** The execution time history vm selection. */
private final List<Double> executionTimeHistoryVmSelection = new LinkedList<Double>();
/** The execution time history host selection. */
private final List<Double> executionTimeHistoryHostSelection = new LinkedList<Double>();
/** The execution time history vm reallocation. */
private final List<Double> executionTimeHistoryVmReallocation = new LinkedList<Double>();
/** The execution time history total. */
private final List<Double> executionTimeHistoryTotal = new LinkedList<Double>();
/**
* Instantiates a new power vm allocation policy migration abstract.
*
* @param hostList the host list
* @param vmSelectionPolicy the vm selection policy
*/
public PowerVmAllocationPolicyMigrationAbstract(
List<? extends Host> hostList,
PowerVmSelectionPolicy vmSelectionPolicy) {
super(hostList);
setVmSelectionPolicy(vmSelectionPolicy);
}
/**
* Optimize allocation of the VMs according to current utilization.
*
* @param vmList the vm list
*
* @return the array list< hash map< string, object>>
*/
@Override
public List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList) {
ExecutionTimeMeasurer.start("optimizeAllocationTotal");
ExecutionTimeMeasurer.start("optimizeAllocationHostSelection");
List<PowerHostUtilizationHistory> overUtilizedHosts = getOverUtilizedHosts();
getExecutionTimeHistoryHostSelection().add(
ExecutionTimeMeasurer.end("optimizeAllocationHostSelection"));
printOverUtilizedHosts(overUtilizedHosts);
saveAllocation();
ExecutionTimeMeasurer.start("optimizeAllocationVmSelection");
List<? extends Vm> vmsToMigrate = getVmsToMigrateFromHosts(overUtilizedHosts);
getExecutionTimeHistoryVmSelection().add(ExecutionTimeMeasurer.end("optimizeAllocationVmSelection"));
Log.printLine("Reallocation of VMs from the over-utilized hosts:");
ExecutionTimeMeasurer.start("optimizeAllocationVmReallocation");
List<Map<String, Object>> migrationMap = getNewVmPlacement(vmsToMigrate, new HashSet<Host>(
overUtilizedHosts));
getExecutionTimeHistoryVmReallocation().add(
ExecutionTimeMeasurer.end("optimizeAllocationVmReallocation"));
Log.printLine();
migrationMap.addAll(getMigrationMapFromUnderUtilizedHosts(overUtilizedHosts));
restoreAllocation();
getExecutionTimeHistoryTotal().add(ExecutionTimeMeasurer.end("optimizeAllocationTotal"));
return migrationMap;
}
/**
* Gets the migration map from under utilized hosts.
*
* @param overUtilizedHosts the over utilized hosts
* @return the migration map from under utilized hosts
*/
protected List<Map<String, Object>> getMigrationMapFromUnderUtilizedHosts(
List<PowerHostUtilizationHistory> overUtilizedHosts) {
List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();
List<PowerHost> switchedOffHosts = getSwitchedOffHosts();
// over-utilized hosts + hosts that are selected to migrate VMs to from over-utilized hosts
Set<PowerHost> excludedHostsForFindingUnderUtilizedHost = new HashSet<PowerHost>();
excludedHostsForFindingUnderUtilizedHost.addAll(overUtilizedHosts);
excludedHostsForFindingUnderUtilizedHost.addAll(switchedOffHosts);
excludedHostsForFindingUnderUtilizedHost.addAll(extractHostListFromMigrationMap(migrationMap));
// over-utilized + under-utilized hosts
Set<PowerHost> excludedHostsForFindingNewVmPlacement = new HashSet<PowerHost>();
excludedHostsForFindingNewVmPlacement.addAll(overUtilizedHosts);
excludedHostsForFindingNewVmPlacement.addAll(switchedOffHosts);
int numberOfHosts = getHostList().size();
while (true) {
if (numberOfHosts == excludedHostsForFindingUnderUtilizedHost.size()) {
break;
}
PowerHost underUtilizedHost = getUnderUtilizedHost(excludedHostsForFindingUnderUtilizedHost);
if (underUtilizedHost == null) {
break;
}
Log.printLine("Under-utilized host: host #" + underUtilizedHost.getId() + "\n");
excludedHostsForFindingUnderUtilizedHost.add(underUtilizedHost);
excludedHostsForFindingNewVmPlacement.add(underUtilizedHost);
List<? extends Vm> vmsToMigrateFromUnderUtilizedHost = getVmsToMigrateFromUnderUtilizedHost(underUtilizedHost);
if (vmsToMigrateFromUnderUtilizedHost.isEmpty()) {
continue;
}
Log.print("Reallocation of VMs from the under-utilized host: ");
if (!Log.isDisabled()) {
for (Vm vm : vmsToMigrateFromUnderUtilizedHost) {
Log.print(vm.getId() + " ");
}
}
Log.printLine();
List<Map<String, Object>> newVmPlacement = getNewVmPlacementFromUnderUtilizedHost(
vmsToMigrateFromUnderUtilizedHost,
excludedHostsForFindingNewVmPlacement);
excludedHostsForFindingUnderUtilizedHost.addAll(extractHostListFromMigrationMap(newVmPlacement));
migrationMap.addAll(newVmPlacement);
Log.printLine();
}
return migrationMap;
}
/**
* Prints the over utilized hosts.
*
* @param overUtilizedHosts the over utilized hosts
*/
protected void printOverUtilizedHosts(List<PowerHostUtilizationHistory> overUtilizedHosts) {
if (!Log.isDisabled()) {
Log.printLine("Over-utilized hosts:");
for (PowerHostUtilizationHistory host : overUtilizedHosts) {
Log.printLine("Host #" + host.getId());
}
Log.printLine();
}
}
/**
* Find host for vm.
*
* @param vm the vm
* @param excludedHosts the excluded hosts
* @return the power host
*/
public PowerHost findHostForVm(Vm vm, Set<? extends Host> excludedHosts) {
double minPower = Double.MAX_VALUE;
PowerHost allocatedHost = null;
for (PowerHost host : this.<PowerHost> getHostList()) {
if (excludedHosts.contains(host)) {
continue;
}
if (host.isSuitableForVm(vm)) {
if (getUtilizationOfCpuMips(host) != 0 && isHostOverUtilizedAfterAllocation(host, vm)) {
continue;
}
try {
double powerAfterAllocation = getPowerAfterAllocation(host, vm);
if (powerAfterAllocation != -1) {
double powerDiff = powerAfterAllocation - host.getPower();
if (powerDiff < minPower) {
minPower = powerDiff;
allocatedHost = host;
}
}
} catch (Exception e) {
}
}
}
return allocatedHost;
}
/**
* Checks if is host over utilized after allocation.
*
* @param host the host
* @param vm the vm
* @return true, if is host over utilized after allocation
*/
protected boolean isHostOverUtilizedAfterAllocation(PowerHost host, Vm vm) {
boolean isHostOverUtilizedAfterAllocation = true;
if (host.vmCreate(vm)) {
isHostOverUtilizedAfterAllocation = isHostOverUtilized(host);
host.vmDestroy(vm);
}
return isHostOverUtilizedAfterAllocation;
}
/**
* Find host for vm.
*
* @param vm the vm
* @return the power host
*/
@Override
public PowerHost findHostForVm(Vm vm) {
Set<Host> excludedHosts = new HashSet<Host>();
if (vm.getHost() != null) {
excludedHosts.add(vm.getHost());
}
return findHostForVm(vm, excludedHosts);
}
/**
* Extract host list from migration map.
*
* @param migrationMap the migration map
* @return the list
*/
protected List<PowerHost> extractHostListFromMigrationMap(List<Map<String, Object>> migrationMap) {
List<PowerHost> hosts = new LinkedList<PowerHost>();
for (Map<String, Object> map : migrationMap) {
hosts.add((PowerHost) map.get("host"));
}
return hosts;
}
/**
* Gets the new vm placement.
*
* @param vmsToMigrate the vms to migrate
* @param excludedHosts the excluded hosts
* @return the new vm placement
*/
protected List<Map<String, Object>> getNewVmPlacement(
List<? extends Vm> vmsToMigrate,
Set<? extends Host> excludedHosts) {
List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();
PowerVmList.sortByCpuUtilization(vmsToMigrate);
for (Vm vm : vmsToMigrate) {
PowerHost allocatedHost = findHostForVm(vm, excludedHosts);
if (allocatedHost != null) {
allocatedHost.vmCreate(vm);
Log.printLine("VM #" + vm.getId() + " allocated to host #" + allocatedHost.getId());
Map<String, Object> migrate = new HashMap<String, Object>();
migrate.put("vm", vm);
migrate.put("host", allocatedHost);
migrationMap.add(migrate);
}
}
return migrationMap;
}
/**
* Gets the new vm placement from under utilized host.
*
* @param vmsToMigrate the vms to migrate
* @param excludedHosts the excluded hosts
* @return the new vm placement from under utilized host
*/
protected List<Map<String, Object>> getNewVmPlacementFromUnderUtilizedHost(
List<? extends Vm> vmsToMigrate,
Set<? extends Host> excludedHosts) {
List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();
PowerVmList.sortByCpuUtilization(vmsToMigrate);
for (Vm vm : vmsToMigrate) {
PowerHost allocatedHost = findHostForVm(vm, excludedHosts);
if (allocatedHost != null) {
allocatedHost.vmCreate(vm);
Log.printLine("VM #" + vm.getId() + " allocated to host #" + allocatedHost.getId());
Map<String, Object> migrate = new HashMap<String, Object>();
migrate.put("vm", vm);
migrate.put("host", allocatedHost);
migrationMap.add(migrate);
} else {
Log.printLine("Not all VMs can be reallocated from the host, reallocation cancelled");
for (Map<String, Object> map : migrationMap) {
((Host) map.get("host")).vmDestroy((Vm) map.get("vm"));
}
migrationMap.clear();
break;
}
}
return migrationMap;
}
/**
* Gets the vms to migrate from hosts.
*
* @param overUtilizedHosts the over utilized hosts
* @return the vms to migrate from hosts
*/
protected
List<? extends Vm>
getVmsToMigrateFromHosts(List<PowerHostUtilizationHistory> overUtilizedHosts) {
List<Vm> vmsToMigrate = new LinkedList<Vm>();
for (PowerHostUtilizationHistory host : overUtilizedHosts) {
while (true) {
Vm vm = getVmSelectionPolicy().getVmToMigrate(host);
if (vm == null) {
break;
}
vmsToMigrate.add(vm);
host.vmDestroy(vm);
if (!isHostOverUtilized(host)) {
break;
}
}
}
return vmsToMigrate;
}
/**
* Gets the vms to migrate from under utilized host.
*
* @param host the host
* @return the vms to migrate from under utilized host
*/
protected List<? extends Vm> getVmsToMigrateFromUnderUtilizedHost(PowerHost host) {
List<Vm> vmsToMigrate = new LinkedList<Vm>();
for (Vm vm : host.getVmList()) {
if (!vm.isInMigration()) {
vmsToMigrate.add(vm);
}
}
return vmsToMigrate;
}
/**
* Gets the over utilized hosts.
*
* @return the over utilized hosts
*/
protected List<PowerHostUtilizationHistory> getOverUtilizedHosts() {
List<PowerHostUtilizationHistory> overUtilizedHosts = new LinkedList<PowerHostUtilizationHistory>();
for (PowerHostUtilizationHistory host : this.<PowerHostUtilizationHistory> getHostList()) {
if (isHostOverUtilized(host)) {
overUtilizedHosts.add(host);
}
}
return overUtilizedHosts;
}
/**
* Gets the switched off host.
*
* @return the switched off host
*/
protected List<PowerHost> getSwitchedOffHosts() {
List<PowerHost> switchedOffHosts = new LinkedList<PowerHost>();
for (PowerHost host : this.<PowerHost> getHostList()) {
if (host.getUtilizationOfCpu() == 0) {
switchedOffHosts.add(host);
}
}
return switchedOffHosts;
}
/**
* Gets the under utilized host.
*
* @param excludedHosts the excluded hosts
* @return the under utilized host
*/
protected PowerHost getUnderUtilizedHost(Set<? extends Host> excludedHosts) {
double minUtilization = 1;
PowerHost underUtilizedHost = null;
for (PowerHost host : this.<PowerHost> getHostList()) {
if (excludedHosts.contains(host)) {
continue;
}
double utilization = host.getUtilizationOfCpu();
if (utilization > 0 && utilization < minUtilization
&& !areAllVmsMigratingOutOrAnyVmMigratingIn(host)) {
minUtilization = utilization;
underUtilizedHost = host;
}
}
return underUtilizedHost;
}
/**
* Checks whether all vms are in migration.
*
* @param host the host
* @return true, if successful
*/
protected boolean areAllVmsMigratingOutOrAnyVmMigratingIn(PowerHost host) {
for (PowerVm vm : host.<PowerVm> getVmList()) {
if (!vm.isInMigration()) {
return false;
}
if (host.getVmsMigratingIn().contains(vm)) {
return true;
}
}
return true;
}
/**
* Checks if is host over utilized.
*
* @param host the host
* @return true, if is host over utilized
*/
protected abstract boolean isHostOverUtilized(PowerHost host);
/**
* Adds the history value.
*
* @param host the host
* @param metric the metric
*/
protected void addHistoryEntry(HostDynamicWorkload host, double metric) {
int hostId = host.getId();
if (!getTimeHistory().containsKey(hostId)) {
getTimeHistory().put(hostId, new LinkedList<Double>());
}
if (!getUtilizationHistory().containsKey(hostId)) {
getUtilizationHistory().put(hostId, new LinkedList<Double>());
}
if (!getMetricHistory().containsKey(hostId)) {
getMetricHistory().put(hostId, new LinkedList<Double>());
}
if (!getTimeHistory().get(hostId).contains(CloudSim.clock())) {
getTimeHistory().get(hostId).add(CloudSim.clock());
getUtilizationHistory().get(hostId).add(host.getUtilizationOfCpu());
getMetricHistory().get(hostId).add(metric);
}
}
/**
* Save allocation.
*/
protected void saveAllocation() {
getSavedAllocation().clear();
for (Host host : getHostList()) {
for (Vm vm : host.getVmList()) {
if (host.getVmsMigratingIn().contains(vm)) {
continue;
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("host", host);
map.put("vm", vm);
getSavedAllocation().add(map);
}
}
}
/**
* Restore allocation.
*/
protected void restoreAllocation() {
for (Host host : getHostList()) {
host.vmDestroyAll();
host.reallocateMigratingInVms();
}
for (Map<String, Object> map : getSavedAllocation()) {
Vm vm = (Vm) map.get("vm");
PowerHost host = (PowerHost) map.get("host");
if (!host.vmCreate(vm)) {
Log.printLine("Couldn't restore VM #" + vm.getId() + " on host #" + host.getId());
System.exit(0);
}
getVmTable().put(vm.getUid(), host);
}
}
/**
* Gets the power after allocation.
*
* @param host the host
* @param vm the vm
*
* @return the power after allocation
*/
protected double getPowerAfterAllocation(PowerHost host, Vm vm) {
double power = 0;
try {
power = host.getPowerModel().getPower(getMaxUtilizationAfterAllocation(host, vm));
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
return power;
}
/**
* Gets the power after allocation. We assume that load is balanced between PEs. The only
* restriction is: VM's max MIPS < PE's MIPS
*
* @param host the host
* @param vm the vm
*
* @return the power after allocation
*/
protected double getMaxUtilizationAfterAllocation(PowerHost host, Vm vm) {
double requestedTotalMips = vm.getCurrentRequestedTotalMips();
double hostUtilizationMips = getUtilizationOfCpuMips(host);
double hostPotentialUtilizationMips = hostUtilizationMips + requestedTotalMips;
double pePotentialUtilization = hostPotentialUtilizationMips / host.getTotalMips();
return pePotentialUtilization;
}
/**
* Gets the utilization of the CPU in MIPS for the current potentially allocated VMs.
*
* @param host the host
*
* @return the utilization of the CPU in MIPS
*/
protected double getUtilizationOfCpuMips(PowerHost host) {
double hostUtilizationMips = 0;
for (Vm vm2 : host.getVmList()) {
if (host.getVmsMigratingIn().contains(vm2)) {
// calculate additional potential CPU usage of a migrating in VM
hostUtilizationMips += host.getTotalAllocatedMipsForVm(vm2) * 0.9 / 0.1;
}
hostUtilizationMips += host.getTotalAllocatedMipsForVm(vm2);
}
return hostUtilizationMips;
}
/**
* Gets the saved allocation.
*
* @return the saved allocation
*/
protected List<Map<String, Object>> getSavedAllocation() {
return savedAllocation;
}
/**
* Sets the vm selection policy.
*
* @param vmSelectionPolicy the new vm selection policy
*/
protected void setVmSelectionPolicy(PowerVmSelectionPolicy vmSelectionPolicy) {
this.vmSelectionPolicy = vmSelectionPolicy;
}
/**
* Gets the vm selection policy.
*
* @return the vm selection policy
*/
protected PowerVmSelectionPolicy getVmSelectionPolicy() {
return vmSelectionPolicy;
}
/**
* Gets the utilization history.
*
* @return the utilization history
*/
public Map<Integer, List<Double>> getUtilizationHistory() {
return utilizationHistory;
}
/**
* Gets the metric history.
*
* @return the metric history
*/
public Map<Integer, List<Double>> getMetricHistory() {
return metricHistory;
}
/**
* Gets the time history.
*
* @return the time history
*/
public Map<Integer, List<Double>> getTimeHistory() {
return timeHistory;
}
/**
* Gets the execution time history vm selection.
*
* @return the execution time history vm selection
*/
public List<Double> getExecutionTimeHistoryVmSelection() {
return executionTimeHistoryVmSelection;
}
/**
* Gets the execution time history host selection.
*
* @return the execution time history host selection
*/
public List<Double> getExecutionTimeHistoryHostSelection() {
return executionTimeHistoryHostSelection;
}
/**
* Gets the execution time history vm reallocation.
*
* @return the execution time history vm reallocation
*/
public List<Double> getExecutionTimeHistoryVmReallocation() {
return executionTimeHistoryVmReallocation;
}
/**
* Gets the execution time history total.
*
* @return the execution time history total
*/
public List<Double> getExecutionTimeHistoryTotal() {
return executionTimeHistoryTotal;
}
}

View File

@@ -0,0 +1,157 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.power;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.util.MathUtil;
/**
* The Inter Quartile Range (IQR) VM allocation policy.
*
* If you are using any algorithms, policies or workload included in the power package, please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 3.0
*/
public class PowerVmAllocationPolicyMigrationInterQuartileRange extends
PowerVmAllocationPolicyMigrationAbstract {
/** The safety parameter. */
private double safetyParameter = 0;
/** The fallback vm allocation policy. */
private PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy;
/**
* Instantiates a new power vm allocation policy migration mad.
*
* @param hostList the host list
* @param vmSelectionPolicy the vm selection policy
* @param safetyParameter the safety parameter
* @param utilizationThreshold the utilization threshold
*/
public PowerVmAllocationPolicyMigrationInterQuartileRange(
List<? extends Host> hostList,
PowerVmSelectionPolicy vmSelectionPolicy,
double safetyParameter,
PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy,
double utilizationThreshold) {
super(hostList, vmSelectionPolicy);
setSafetyParameter(safetyParameter);
setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
}
/**
* Instantiates a new power vm allocation policy migration mad.
*
* @param hostList the host list
* @param vmSelectionPolicy the vm selection policy
* @param safetyParameter the safety parameter
*/
public PowerVmAllocationPolicyMigrationInterQuartileRange(
List<? extends Host> hostList,
PowerVmSelectionPolicy vmSelectionPolicy,
double safetyParameter,
PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
super(hostList, vmSelectionPolicy);
setSafetyParameter(safetyParameter);
setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
}
/**
* Checks if is host over utilized.
*
* @param _host the _host
* @return true, if is host over utilized
*/
@Override
protected boolean isHostOverUtilized(PowerHost host) {
PowerHostUtilizationHistory _host = (PowerHostUtilizationHistory) host;
double upperThreshold = 0;
try {
upperThreshold = 1 - getSafetyParameter() * getHostUtilizationIqr(_host);
} catch (IllegalArgumentException e) {
return getFallbackVmAllocationPolicy().isHostOverUtilized(host);
}
addHistoryEntry(host, upperThreshold);
double totalRequestedMips = 0;
for (Vm vm : host.getVmList()) {
totalRequestedMips += vm.getCurrentRequestedTotalMips();
}
double utilization = totalRequestedMips / host.getTotalMips();
return utilization > upperThreshold;
}
/**
* Gets the host utilization iqr.
*
* @param host the host
* @return the host utilization iqr
*/
protected double getHostUtilizationIqr(PowerHostUtilizationHistory host) throws IllegalArgumentException {
double[] data = host.getUtilizationHistory();
if (MathUtil.countNonZeroBeginning(data) >= 12) { // 12 has been suggested as a safe value
return MathUtil.iqr(data);
}
throw new IllegalArgumentException();
}
/**
* Sets the safety parameter.
*
* @param safetyParameter the new safety parameter
*/
protected void setSafetyParameter(double safetyParameter) {
if (safetyParameter < 0) {
Log.printLine("The safety parameter cannot be less than zero. The passed value is: "
+ safetyParameter);
System.exit(0);
}
this.safetyParameter = safetyParameter;
}
/**
* Gets the safety parameter.
*
* @return the safety parameter
*/
protected double getSafetyParameter() {
return safetyParameter;
}
/**
* Sets the fallback vm allocation policy.
*
* @param fallbackVmAllocationPolicy the new fallback vm allocation policy
*/
public void setFallbackVmAllocationPolicy(
PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
this.fallbackVmAllocationPolicy = fallbackVmAllocationPolicy;
}
/**
* Gets the fallback vm allocation policy.
*
* @return the fallback vm allocation policy
*/
public PowerVmAllocationPolicyMigrationAbstract getFallbackVmAllocationPolicy() {
return fallbackVmAllocationPolicy;
}
}

Some files were not shown because too many files have changed in this diff Show More