Skip to content

Instantly share code, notes, and snippets.

@Farwa-Rajput
Last active June 15, 2023 01:24
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Farwa-Rajput/3bb3f69aa985bf4587edfa5612925fed to your computer and use it in GitHub Desktop.
Shortest Job First (SJF) Task scheduling algorithm implementation in cloudsim
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;
List <Cloudlet> sortList= new ArrayList<Cloudlet>();
ArrayList<Cloudlet> tempList = new ArrayList<Cloudlet>();
for(Cloudlet cloudlet: getCloudletList())
{
tempList.add(cloudlet);
}
int totalCloudlets= tempList.size();
for(int i=0;i<totalCloudlets;i++)
{
Cloudlet smallestCloudlet= tempList.get(0);
for(Cloudlet checkCloudlet: tempList)
{
if(smallestCloudlet.getCloudletLength()>checkCloudlet.getCloudletLength())
{
smallestCloudlet= checkCloudlet;
}
}
sortList.add(smallestCloudlet);
tempList.remove(smallestCloudlet);
}
int count=1;
for(Cloudlet printCloudlet: sortList)
{
Log.printLine(count+".Cloudler Id:"+printCloudlet.getCloudletId()+",Cloudlet Length:"+printCloudlet.getCloudletLength());
count++;
}
for (Cloudlet cloudlet : sortList) {
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;
}
}
package examples.org.cloudbus.cloudsim.examples;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletSchedulerSpaceShared;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
/**
* An example showing how to create
* scalable simulations.
*/
public class Simulation {
/** The cloudlet list. */
private static List<Cloudlet> cloudletList;
/** The vmlist. */
private static List<Vm> vmlist;
private static List<Vm> createVM(int userId, int vms) {
//Creates a container to store VMs. This list is passed to the broker later
LinkedList<Vm> list = new LinkedList<Vm>();
//VM Parameters
long size = 10000; //image size (MB)
int ram = 512; //vm memory (MB)
int mips = 1000;
long bw = 1000;
int pesNumber = 1; //number of cpus
String vmm = "Xen"; //VMM name
//create VMs
Vm[] vm = new Vm[vms];
for(int i=0;i<vms;i++){
vm[i] = new Vm(i, userId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerSpaceShared());
//for creating a VM with a space shared scheduling policy for cloudlets:
//vm[i] = Vm(i, userId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerSpaceShared());
list.add(vm[i]);
}
return list;
}
private static List<Cloudlet> createCloudlet(int userId, int cloudlets){
// Creates a container to store Cloudlets
LinkedList<Cloudlet> list = new LinkedList<Cloudlet>();
//cloudlet parameters
long length = 1000;
long fileSize = 300;
long outputSize = 300;
int pesNumber = 1;
UtilizationModel utilizationModel = new UtilizationModelFull();
Cloudlet[] cloudlet = new Cloudlet[cloudlets];
for(int i=0;i<cloudlets;i++){
Random r= new Random();
cloudlet[i] = new Cloudlet(i, length +r.nextInt(2000), pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
// setting the owner of these Cloudlets
cloudlet[i].setUserId(userId);
list.add(cloudlet[i]);
}
return list;
}
////////////////////////// STATIC METHODS ///////////////////////
/**
* Creates main() to run this example
*/
public static void main(String[] args) {
Log.printLine("Starting CloudSimExample6...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities.
int num_user = 3; // number of grid users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
// Initialize the CloudSim library
CloudSim.init(num_user, calendar, trace_flag);
// Second step: Create Datacenters
//Datacenters are the resource providers in CloudSim. We need at list one of them to run a CloudSim simulation
Datacenter datacenter0 = createDatacenter("Datacenter_0");
Datacenter datacenter1 = createDatacenter("Datacenter_1");
//Third step: Create Broker
DatacenterBroker broker = createBroker();
int brokerId = broker.getId();
//Fourth step: Create VMs and Cloudlets and send them to broker
vmlist = createVM(brokerId,10); //creating 20 vms
cloudletList = createCloudlet(brokerId,40); // creating 40 cloudlets
broker.submitVmList(vmlist);
broker.submitCloudletList(cloudletList);
// Fifth step: Starts the simulation
CloudSim.startSimulation();
// Final step: Print results when simulation is over
List<Cloudlet> newList = broker.getCloudletReceivedList();
CloudSim.stopSimulation();
printCloudletList(newList);
//Print the debt of each user to each datacenter
datacenter0.printDebts();
datacenter1.printDebts();
Log.printLine("CloudSimExample6 finished!");
}
catch (Exception e)
{
e.printStackTrace();
Log.printLine("The simulation has been terminated due to an unexpected error");
}
}
private static Datacenter createDatacenter(String name){
// Here are the steps needed to create a PowerDatacenter:
// 1. We need to create a list to store one or more
// Machines
List<Host> hostList = new ArrayList<Host>();
// 2. A Machine contains one or more PEs or CPUs/Cores. Therefore, should
// create a list to store these PEs before creating
// a Machine.
List<Pe> peList1 = new ArrayList<Pe>();
int mips = 1000;
// 3. Create PEs and add these into the list.
//for a quad-core machine, a list of 4 PEs is required:
peList1.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating
peList1.add(new Pe(1, new PeProvisionerSimple(mips)));
peList1.add(new Pe(2, new PeProvisionerSimple(mips)));
peList1.add(new Pe(3, new PeProvisionerSimple(mips)));
//Another list, for a dual-core machine
List<Pe> peList2 = new ArrayList<Pe>();
peList2.add(new Pe(0, new PeProvisionerSimple(mips)));
peList2.add(new Pe(1, new PeProvisionerSimple(mips)));
//4. Create Hosts with its id and list of PEs and add them to the list of machines
int hostId=0;
int ram = 2048; //host memory (MB)
long storage = 1000000; //host storage
int bw = 10000;
hostList.add(
new Host(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerSimple(bw),
storage,
peList1,
new VmSchedulerTimeShared(peList1)
)
); // This is our first machine
hostId++;
hostList.add(
new Host(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerSimple(bw),
storage,
peList2,
new VmSchedulerTimeShared(peList2)
)
); // Second machine
//To create a host with a space-shared allocation policy for PEs to VMs:
//hostList.add(
// new Host(
// hostId,
// new CpuProvisionerSimple(peList1),
// new RamProvisionerSimple(ram),
// new BwProvisionerSimple(bw),
// storage,
// new VmSchedulerSpaceShared(peList1)
// )
// );
//To create a host with a oportunistic space-shared allocation policy for PEs to VMs:
//hostList.add(
// new Host(
// hostId,
// new CpuProvisionerSimple(peList1),
// new RamProvisionerSimple(ram),
// new BwProvisionerSimple(bw),
// storage,
// new VmSchedulerOportunisticSpaceShared(peList1)
// )
// );
// 5. Create a DatacenterCharacteristics object that stores the
// properties of a data center: architecture, OS, list of
// Machines, allocation policy: time- or space-shared, time zone
// and its price (G$/Pe time unit).
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.1; // the cost of using storage in this resource
double costPerBw = 0.1; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); //we are not adding SAN devices by now
DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage, costPerBw);
// 6. Finally, we need to create a PowerDatacenter object.
Datacenter datacenter = null;
try {
datacenter = new Datacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0);
} catch (Exception e) {
e.printStackTrace();
}
return datacenter;
}
//We strongly encourage users to develop their own broker policies, to submit vms and cloudlets according
//to the specific rules of the simulated scenario
private static DatacenterBroker createBroker(){
DatacenterBroker broker = null;
try {
broker = new DatacenterBroker("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return broker;
}
/**
* Prints the Cloudlet objects
* @param list list of Cloudlets
*/
@SuppressWarnings("deprecation")
private static void printCloudletList(List<Cloudlet> list) {
int size = list.size();
Cloudlet cloudlet;
String indent = " ";
Log.printLine();
Log.printLine("========== OUTPUT ==========");
Log.printLine("Cloudlet ID" + indent + "STATUS" + indent +
"Data center ID" + indent + "VM ID" + indent + indent + "Time" + indent + "Start Time" + indent + "Finish Time" +indent+"user id"+indent);
DecimalFormat dft = new DecimalFormat("###.##");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
Log.print(indent + cloudlet.getCloudletId() + indent + indent);
if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS){
Log.print("SUCCESS");
Log.printLine( indent + indent + cloudlet.getResourceId() + indent + indent + indent + cloudlet.getVmId() +
indent + indent + indent + dft.format(cloudlet.getActualCPUTime()) +
indent + indent + dft.format(cloudlet.getExecStartTime())+ indent + indent + indent + dft.format(cloudlet.getFinishTime())+indent +cloudlet.getUserId());
}
}
}
}
@Murta90
Copy link

Murta90 commented Jun 6, 2020

Excuse me, I need Meta-Heuristic Algorithmsfor Training
Thanks

@Farwa-Rajput
Copy link
Author

Thanks, Farwa

welcome

@Farwa-Rajput
Copy link
Author

Thanks, Farwa
I get the same error with printDebt();
I check the datacenter class but I don't see any function in that name, what should I do there?
thanks
for a time being just comment the printline function of printDebt

@Murta90
Copy link

Murta90 commented Jun 7, 2020

Excuse me Farwa,
In SJF I need to use 2 vm
and need to get the average of them and compare each cloudlet with the avg
if cloudlet < avg
the Broker will give that cloudlet to the lower vm
and if the cloudlet > avg
the Broker will give that cloudlet to the Higher vm
so, in which class should I put these changes to get Improved SJF?

Thanks

@joze-jb
Copy link

joze-jb commented Jun 11, 2020

Hi Farwa,
I am new to cloud sim. Could you please tell me how to run this program in cloud sim?. I have installed eclipse and cloudsim. How SJF is working cloudsim? . Please Give some idea.
Thanks.

@Farwa-Rajput
Copy link
Author

Excuse me Farwa,
In SJF I need to use 2 vm
and need to get the average of them and compare each cloudlet with the avg
if cloudlet < avg
the Broker will give that cloudlet to the lower vm
and if the cloudlet > avg
the Broker will give that cloudlet to the Higher vm
so, in which class should I put these changes to get Improved SJF?

Thanks

Definitely you can create no. of VMs on host but it always relies on the configuration of hosts and VMs. According to their capacity Mips you can use any broker strategy of your need
you can Use Cloudsim.VM constructor for making multiple VMs

public void bindCloudletToVm(int cloudletId, int vmId) {
CloudletList.getById(getCloudletList(), cloudletId).setVmId(vmId);
}
In the function you can set specific if of VM to some specific type of VM

@Farwa-Rajput
Copy link
Author

Hi Farwa,
I am new to cloud sim. Could you please tell me how to run this program in cloud sim?. I have installed eclipse and cloudsim. How SJF is working cloudsim? . Please Give some idea.
Thanks.

After Finishing the IDE, you can simply replace the files DatacenterBroker and your main file by the above

@Farwa-Rajput
Copy link
Author

Excuse me Farwa,
In SJF I need to use 2 vm
and need to get the average of them and compare each cloudlet with the avg
if cloudlet < avg
the Broker will give that cloudlet to the lower vm
and if the cloudlet > avg
the Broker will give that cloudlet to the Higher vm
so, in which class should I put these changes to get Improved SJF?

Thanks

Or YOU CAN ALSO MAKE LIKE THIS

//Third step: Create Brokers
vmlist1 = new ArrayList();
vmlist2 = new ArrayList();
vmlist3 = new ArrayList();
vmlist4 = new ArrayList();
vmlist5 = new ArrayList();

		//create VMs
		Vm vm1 = new Vm(0, brokerId1, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		///Vm vm1_1 = new Vm(1, brokerId1, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		Vm vm2 = new Vm(1, brokerId2, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		Vm vm3 = new Vm(2, brokerId3, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		Vm vm4 = new Vm(3, brokerId4, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		Vm vm5 = new Vm(4, brokerId5, mips, pesNumber, ram, bw, size, vmm, vmm, bw, new CloudletSchedulerTimeShared());
		//add the VMs to the vmlists
		vmlist1.add(vm1);
		//vmlist1.add(vm1_1);
		vmlist2.add(vm2);
		vmlist3.add(vm3);
		vmlist4.add(vm4);
		vmlist5.add(vm5);
		//submit vm list to the broker
		broker1.submitVmList(vmlist1);
		broker2.submitVmList(vmlist2);
		broker3.submitVmList(vmlist3);
		broker4.submitVmList(vmlist4);
		broker5.submitVmList(vmlist5);

@archit-bhatia
Copy link

Sure. I am exploring to implement the SJF algorithm in Fog Device(mini datacenter) using iFogsim.

Hey @Farwa-Rajput, @sujannou, were you able to implement SJF or any other algorithm in iFogsim. I needed help in this and their aren't any good resources available for iFogsim.

@syedrizwanhassan
Copy link

@Farwa-Rajput : Madam I need some help can you share your email address.

Thanks

@Farwa-Rajput
Copy link
Author

Sure. I am exploring to implement the SJF algorithm in Fog Device(mini datacenter) using iFogsim.

Hey @Farwa-Rajput, @sujannou, were you able to implement SJF or any other algorithm in iFogsim. I needed help in this and their aren't any good resources available for iFogsim.

No dear

@Farwa-Rajput
Copy link
Author

@Farwa-Rajput : Madam I need some help can you share your email address.

Thanks

yes you can ask here

@pistacchi
Copy link

pistacchi commented Oct 18, 2020

Hello Farwa, do you have the code for max-max algorithm in cloudsim?
If yes, would you mind sharing please
@Farwa-Rajput

@Farwa-Rajput
Copy link
Author

Hello Farwa, do you have the code for max-max algorithm in cloudsim?
If yes, would you mind sharing please
@Farwa-Rajput

package MaxMin;

import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.Vm;

import Indepnd_job_generator.Job_Generator;
import Indepnd_job_generator.MapUtil;

/**
public class Max_min {

Job_Generator job;
public int [][]ScheduledList;
public double SL;
public Max_min(Job_Generator newjob) {
super();
job=newjob;
ScheduledList=new int [job.No_cloudlets][2];
}
private final List hasChecked = new ArrayList<>();
public void run() {

    //Log.printLine("Schedulin Cycle");
    int size = job.No_cloudlets;
    hasChecked.clear();
    for (int t = 0; t < size; t++) {
        hasChecked.add(false);
    }
    for (int i = 0; i < size; i++) {
        int maxIndex = 0;
        Cloudlet maxCloudlet = null;
        for (int j = 0; j < size; j++) {
            Cloudlet cloudlet = (Cloudlet) job.CloudLet_list.get(j);
            if (!hasChecked.get(j)) {
                maxCloudlet = cloudlet;
                maxIndex = j;
                break;
            }
        }
        if (maxCloudlet == null) {
            break;
        }

        for (int j = 0; j < size; j++) {
            Cloudlet cloudlet = (Cloudlet) job.CloudLet_list.get(j);
            if (hasChecked.get(j)) {
                continue;
            }
            long length = cloudlet.getCloudletLength();
            if (length > maxCloudlet.getCloudletLength()) {
                maxCloudlet = cloudlet;
                maxIndex = j;
            }
        }
        hasChecked.set(maxIndex, true);
        int vmSize = job.VM_list.size();
        Vm firstIdleVm = null;//(CondorVM)getVmList().get(0);
        for (int j = 0; j < vmSize; j++) {
        	Vm vm =  job.VM_list.get(j);
                firstIdleVm = vm;
                break;
             }
        if (firstIdleVm == null) {
            break;
        }
        for (int j = 0; j < vmSize; j++) {
            Vm vm =  job.VM_list.get(j);
            
            double length=maxCloudlet.getCloudletLength();
            if ((vm.time +(length/vm.getMips()))
            		< (firstIdleVm.time+(length/firstIdleVm.getMips())))
            {
                firstIdleVm = vm;

            } }
        firstIdleVm.time=firstIdleVm.time +
        		(maxCloudlet.getCloudletLength()/firstIdleVm.getMips());
        maxCloudlet.setVmId(firstIdleVm.getId());
        ScheduledList[i][0]=maxCloudlet.getCloudletId();
        ScheduledList[i][1]=firstIdleVm.getId();
        
    }
    Calculate_SL();
}
public void Calculate_SL() {
	// TODO Auto-generated method stub
	double []VM_Tims=new double [job.No_VMs];
	int task,vm;
		for(int t=0;t<ScheduledList.length;t++)
		{
			task=ScheduledList[t][0];
			vm=ScheduledList[t][1];
			VM_Tims[vm]+=job.CloudletExeTim(job.CloudLet_list.get(task).getCloudletLength())[vm];
		}
		SL=MapUtil.Get_Max_Min_Array(VM_Tims)[0];
	}

}

Copy link

ghost commented Nov 18, 2020

HI, can you collaborate with me in my research work?

Ali
www.alitariq.net

@alitariqnet
Copy link

alitariqnet commented Dec 9, 2020

HI, can you collaborate with me in my research work?

Ali
www.alitariq.net

That account was mine but I deleted it and made a new one. Can you please delete that comment for me because I don't have that domain anymore.

@aseel-thamer
Copy link

In cloudSim! is it possible to execute the code of a specific parallel problem and get the result of it?

@Riya144
Copy link

Riya144 commented May 21, 2021

how can i run this code can anyone help me please

@Muller33
Copy link

i want to do dynamic resource allocation can anyone help me please

@ABDUR-AR17
Copy link

nice code Farwa....now in this example, if i need to get the power consumption...how would I be able to achieve this

@SriLiptaSwain
Copy link

Hello Farwa ma'am and everyone who have already implemented this on their personal system, can anyone please help me out with the implementation, cause I'm unable to build and run the files.

@Farwa-Rajput
Copy link
Author

@SriLiptaSwain All you need to modify your current submitCloudlets() function in DatacenterBroker.java class
CHECK LINE NO 335

@mkgaganr
Copy link

Hi can I get priority scheduling algorithm

@mkgaganr
Copy link

Is there no full code🥲

@pushkar7570
Copy link

I am trying to create VMs more than 20, but still only 11 are created. Please help.

@Memoona787
Copy link

Can you plz help me about SRTF algorithm in cloudsim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment