CloudSim云仿真平台,随手搭个1数据中心,2主机,5不同规格虚拟机。并简单修改调度算法。

cloudsim的源代码里的调度算法都是只建立了一个主机,且调度算法是按照空闲核数最多的主机进行调度,我稍微改了改,改为1数据中心,2主机,5不同规格虚拟机,并随手把调度算法改为单机填满再填下一个主机
5种虚机:
在这里插入图片描述
先看结果:
在这里插入图片描述
上代码:
新建一个CloudSimExampleTest:

package org.cloudbus.cloudsim.examples;

import org.cloudbus.cloudsim.*;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 1 datacenter
 * 2 host
 * each host 10 pe(cpu)
 * allocate 4 vm
 * 4 cloudlet
 **/

public class CloudSimExmapleHWH_diff_Vm {
    /**
     * cloudlet list
     **/
    private static List<Cloudlet> cloudletList;

    /**
     * vm list
     **/
    private static List<Vm> vmList;


    public static void main(String[] args) {
        Log.printLine("start processer");
        try {
            int num_user = 1;
            Calendar instance = Calendar.getInstance();
            boolean trace_flag = false;

            CloudSim.init(num_user, instance, trace_flag);

            Datacenter datacenter1 = createDatacenter("tianjin01");
            DatacenterBroker datacenterBroker1 = createBroker();
            int brokerId = datacenterBroker1.getId();

            //创建vm
            List<Vm> vmList = new ArrayList<Vm>();
            //VM description

            int vmid;
            int mips = 250;
            long size = 10000; //image size (MB)
            int ram = 2048; //vm memory (MB)
            long bw = 1000;
            int pesNumber = 1; //number of cpus
            String vmm = "Xen"; //VMM name

            // alt shift insert 竖直选中粘贴,用完记得 alt shift insert取消该模式
            Vm vm1= new Vm(0,brokerId, mips, 3, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
            Vm vm2= new Vm(1,brokerId, mips, 2, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
            Vm vm3= new Vm(2,brokerId, mips, 1, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
            Vm vm4= new Vm(3,brokerId, mips, 3, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
            Vm vm5= new Vm(4,brokerId, mips, 3, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
            vmList.add(vm1);
            vmList.add(vm2);
            vmList.add(vm3);
            vmList.add(vm4);
            vmList.add(vm5);

            for (Vm vm : vmList) {
                System.out.println("VM列表:"+vm.toString());
            }
            //把vmlist给代理
            datacenterBroker1.submitVmList(vmList);

            cloudletList = new ArrayList<Cloudlet>();
            //Cloudlet properties
            int id;
            long length = 40000;
            long fileSize = 300;
            long outputSize = 300;
            UtilizationModel utilizationModel = new UtilizationModelFull();
            for (int i = 0; i < 4; i++) {
                Cloudlet cloudlet1 = new Cloudlet(i, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
                cloudlet1.setUserId(brokerId);
                cloudletList.add(cloudlet1);
            }
            //submit cloudlet list to the broker
            datacenterBroker1.submitCloudletList(cloudletList);

            for (int i = 0; i < 4; i++) {
                datacenterBroker1.bindCloudletToVm(cloudletList.get(i).getCloudletId(),vmList.get(i).getId());
            }

            // Sixth step: Starts the simulation
            CloudSim.startSimulation();
            // Final step: Print results when simulation is over
            List<Cloudlet> newList = datacenterBroker1.getCloudletReceivedList();
            CloudSim.stopSimulation();
            printCloudletList(newList);
            Log.printLine("CloudSimExampleHWH  finished!");


        } catch (Exception e) {
            e.printStackTrace();
            Log.print("unknow error");
        }
    }


    private static Datacenter createDatacenter(String name) {
        List<Host> hostList = new ArrayList<Host>();
        List<Pe> peList = new ArrayList<Pe>();
        int mips = 1000;
        for (int i = 0; i < 10; i++) {
            peList.add(new Pe(i, new PeProvisionerSimple(mips)));
        }

        int ram = 8192; //host memory (MB)
        long storage = 1000000; //host storage
        int bw = 10000;
        Log.printLine("start make 2 hosts");
        for (int i = 0; i < 2; i++) {
            //拷贝新的pelist
            List<Pe> pelistNew = peList.stream().collect(Collectors.toList());
            hostList.add(new Host(i, new RamProvisionerSimple(ram),
                    new BwProvisionerSimple(bw), storage, pelistNew, new VmSchedulerTimeShared(pelistNew)));
        }
        for (Host host : hostList) {
            System.out.println("host列表");
            System.out.println(host.toString());
        }
        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.001;    // the cost of using storage in this resource
        double costPerBw = 0.0;            // the cost of using bw in this resource
        List<Storage> storageList = new ArrayList<Storage>();
        DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
                arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage, costPerBw);

        Datacenter datacenter = null;
        try {
            //VmAllocationPolicySimple_Mine(hostList)             VmAllocationPolicySimple(hostList)
            datacenter = new Datacenter(name, characteristics, new VmAllocationPolicySimple_Mine(hostList),
                    storageList, 0);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return datacenter;
    }


    private static DatacenterBroker createBroker() {
        DatacenterBroker broker = null;
        try {
            broker = new DatacenterBroker("Broker");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return broker;
    }



    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 + "Time" + indent + "Start Time" + indent + "Finish Time");

        DecimalFormat dft = new DecimalFormat("###.##");
        for (int i = 0; i < size; i++) {
            cloudlet = list.get(i);
            Log.print(indent + cloudlet.getCloudletId() + indent + indent);

            if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS){
                Log.print("SUCCESS");

                Log.printLine( indent + indent + cloudlet.getResourceId() + indent + indent + indent + cloudlet.getVmId() +
                        indent + indent + dft.format(cloudlet.getActualCPUTime()) + indent + indent + dft.format(cloudlet.getExecStartTime())+
                        indent + indent + dft.format(cloudlet.getFinishTime()));
            }
        }

    }
}

注意其中注入的调度算法为我们自己改过的:
VmAllocationPolicySimple:

/*
 * 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. It is therefore a Worst Fit policy, allocating VMs into the 
 * host with most available PE.
 * 
 * @author Rodrigo N. Calheiros
 * @author Anton Beloglazov
 * @since CloudSim Toolkit 1.0
 */
public class VmAllocationPolicySimple_Mine extends VmAllocationPolicy {

	/** The map between each VM and its allocated host.
         * The map key is a VM UID and the value is the allocated host for that VM. */
	private Map<String, Host> vmTable;

	/** The map between each VM and the number of Pes used.
         * The map key is a VM UID and the value is the number of used Pes for that VM. */
	private Map<String, Integer> usedPes;

	/** The number of free Pes for each host from {@link #getHostList() }. */
	private List<Integer> freePes;

	/**
	 * Creates a new VmAllocationPolicySimple object.
	 *
	 * @param list the list of hosts
	 * @pre $none
	 * @post $none
	 */
	public VmAllocationPolicySimple_Mine(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 the host with less PEs in use for a given VM.
	 *
	 * @param vm {@inheritDoc}
	 * @return {@inheritDoc}
	 * @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 = freePesTmp.get(0);
				int idx = 0;

				for (int i = 0; i < freePesTmp.size(); i++) {
					if(requiredPes>freePesTmp.get(i)){
						continue;
					}else if (freePesTmp.get(i)>moreFree){
						continue;
					}else {
						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;
	}



	@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);
		}
	}

	@Override
	public Host getHost(Vm vm) {
		return getVmTable().get(vm.getUid());
	}

	@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;
	}

	@Override
	public List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList) {
		// TODO Auto-generated method stub
		return null;
	}

	@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;
	}
}

就ok了 ovo

  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
为了模拟不同负载情况下的虚拟机调度算法,并记录相关指标,你可以使用CloudSim框架来实现。以下是一个示例代码,展示了如何模拟低、中、高三种负载情况下的虚拟机调度,并记录相关指标: ```java import org.cloudbus.cloudsim.*; import org.cloudbus.cloudsim.core.CloudSim; import java.util.ArrayList; import java.util.List; public class CloudSimExample { public static void main(String[] args) { int numHosts = 10; int numVMsLowLoad = 3; int numVMsMediumLoad = 6; int numVMsHighLoad = 9; List<Host> hostList = new ArrayList<>(); List<Vm> vmList = new ArrayList<>(); // 创建主机 for (int i = 0; i < numHosts; i++) { List<Pe> peList = new ArrayList<>(); for (int j = 0; j < 4; j++) { peList.add(new Pe(j, new PeProvisionerSimple(1000))); // 4个CPU,每个CPU 1000 MIPS } int ram = 8192; // 8GB内存 long storage = 100000; // 100GB存储空间 int bw = 10000; // 带宽 hostList.add(new Host(i, new RamProvisionerSimple(ram), new BwProvisionerSimple(bw), storage, peList, new CloudletSchedulerTimeShared())); } // 创建低负载下的虚拟机 for (int i = 0; i < numVMsLowLoad; i++) { int mips = 1000; // 1个CPU,每个CPU 1000 MIPS int ram = 2048; // 2GB内存 long storage = 20000; // 20GB存储空间 int bw = 1000; // 带宽 Vm vm = new Vm(i, 0, mips, 1, ram, bw, storage, "Xen", new CloudletSchedulerTimeShared()); vmList.add(vm); } // 创建中等负载下的虚拟机 for (int i = numVMsLowLoad; i < numVMsLowLoad + numVMsMediumLoad; i++) { int mips = 1000; // 1个CPU,每个CPU 1000 MIPS int ram = 2048; // 2GB内存 long storage = 20000; // 20GB存储空间 int bw = 1000; // 带宽 Vm vm = new Vm(i, 0, mips, 1, ram, bw, storage, "Xen", new CloudletSchedulerTimeShared()); vmList.add(vm); } // 创建高负载下的虚拟机 for (int i = numVMsLowLoad + numVMsMediumLoad; i < numVMsLowLoad + numVMsMediumLoad + numVMsHighLoad; i++) { int mips = 1000; // 1个CPU,每个CPU 1000 MIPS int ram = 2048; // 2GB内存 long storage = 20000; // 20GB存储空间 int bw = 1000; // 带宽 Vm vm = new Vm(i, 0, mips, 1, ram, bw, storage, "Xen", new CloudletSchedulerTimeShared()); vmList.add(vm); } // 创建CloudSim仿真对象 CloudSim simulation = new CloudSim(); // 创建数据中心对象 Datacenter datacenter = createDatacenter(simulation, hostList); // 创建虚拟机管理器对象 VmAllocationPolicy vmAllocationPolicy = new VmAllocationPolicyQoS(hostList); DatacenterBroker broker = createBroker(simulation, vmList, vmAllocationPolicy); // 启动仿真 simulation.startSimulation(); // 获取实验结果 List<Vm> vmsInDatacenter = broker.getVmList(); for (int i = 0; i < vmsInDatacenter.size(); i++) { Vm vm = vmsInDatacenter.get(i); System.out.println("VM #" + vm.getId() + ":"); System.out.println(" Startup Time: " + vm.getVmStartTime()); System.out.println(" Migration Time: " + vm.getMigrationTime()); System.out.println(" Network Bandwidth: " + vm.getCloudletScheduler().getNetServiceLevel()); System.out.println(" Resource Utilization: " + vm.getTotalUtilizationOfCpu(simulation.clock())); System.out.println(" Response Time: " + vm.getResponseTime()); } // 停止仿真 simulation.stopSimulation(); } private static Datacenter createDatacenter(CloudSim simulation, List<Host> hostList) { // 创建数据中心特性对象 String arch = "x86"; String os = "Linux"; String vmm = "Xen"; double timeZone = 10.0; double costPerSec = 3.0; double costPerMem = 0.05; double costPerStorage = 0.1; double costPerBw = 0.1; DatacenterCharacteristics characteristics = new DatacenterCharacteristics(arch, os, vmm, hostList, timeZone, costPerSec, costPerMem, costPerStorage, costPerBw); // 创建数据中心对象 Datacenter datacenter = null; try { datacenter = new Datacenter("Datacenter", characteristics, new VmAllocationPolicySimple(hostList), new ArrayList<Storage>(), 0); } catch (Exception e) { e.printStackTrace(); } // 将数据中心添加到仿真对象 simulation.add(datacenter); return datacenter; } private static DatacenterBroker createBroker(CloudSim simulation, List<Vm> vmList, VmAllocationPolicy vmAllocationPolicy) { // 创建虚拟机管理器对象 DatacenterBroker broker = null; try { broker = new DatacenterBroker("Broker", vmAllocationPolicy); } catch (Exception e) { e.printStackTrace(); } // 将虚拟机列表添加到虚拟机管理器 broker.submitVmList(vmList); // 将虚拟机管理器添加到仿真对象 simulation.add(broker); return broker; } } ``` 上述代码中,我们首先通过`createDatacenter`方法创建了一个数据中心对象,并使用`createBroker`方法创建了一个虚拟机管理器对象。然后,我们将主机列表和虚拟机列表分别传递给数据中心虚拟机管理器。在仿真过程中,CloudSim会自动分配和调度虚拟机主机上,并记录相关指标。最后,我们通过遍历虚拟机列表,打印了每个虚拟机的指标信息。 请注意,在代码中我使用了`VmAllocationPolicyQoS`作为虚拟机分配策略,你可以根据你的需求自定义或使用其他虚拟机分配策略。 此外,请确保你已经正确导入所需的CloudSim类和包。你可以根据CloudSim的文档或示例代码进行进一步的学习和修改,以满足你的实验需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值