CloudSim 學習實例1

CloudSim Example 1

cloudsim 教程例1解讀

創建一個含一臺主機的數據中心,並在其上運行一個雲任務

代碼

package org.cloudbus.cloudsim.examples;

/*
 * 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, The University of Melbourne, Australia
 */

import java.text.DecimalFormat; //處理文本、日期、數字和消息的類和接口
import java.util.ArrayList; 	//Java的實用工具類庫java.util包
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.cloudbus.cloudsim.Cloudlet;
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;
//cloudsim相關包

public class CloudSimExample1 {
	/** The cloudlet list. */ 雲任務列表
	private static List<Cloudlet> cloudletList;
	/** The vmlist. */ 虛擬機列表
	private static List<Vm> vmlist;

	@SuppressWarnings("unused") 
	//主函數運行
	public static void main(String[] args) {
		Log.printLine("Starting CloudSimExample1...");  //結果輸出

		try {
			// 第一步:初始化工具包
			int num_user = 1; // number of cloud users 雲用戶數量
			Calendar calendar = Calendar.getInstance(); //  用當前日期和時間初始化字段的日曆
 			boolean trace_flag = false; // trace events 事件跟蹤
 			
    ************************************************************************************************/
    *  Comment Start 
    * Initialize the CloudSim library. 
	* init()調用 initCommonVariable(), initCommonVariable()反過來調用initialize()
	           (all these 3 methods are defined in CloudSim.java).
	* initialize() 創建了兩個集合 - an 數組列表 of SimEntity 數組對象 (表示模擬實體的named entities) and 
	* a LinkedHashMap 鏈表哈希映射 (named entitiesByName 表示相同模擬實體的LinkedHashMap), 
	           以每個SimEntity的名稱作爲鍵.
	* initialize() 創建兩個隊列 - a Queue of SimEvents (future) and another Queue of SimEvents (deferred). 
	* initialize() creates a 哈希表 of 預測 (以整數爲鍵) - these predicates are used 
			   to select a particular event from the deferred queue. 
	* initialize() sets the simulation clock to 0 and running (a boolean flag) to false.
	* 一旦initialize()返回(請注意,我們現在處於方法initCommonVariable()), 
			   就會創建一個CloudSimShutDown(從SimEntity派生而來)實例
	* (with numuser as 1, its name as CloudSimShutDown, id as -1, and state as RUNNABLE). 
			   然後將這個新實體添加到模擬中
	* 當添加到模擬中時,它的id變爲0(從前面的-1). 兩個集合 - entities 和 entitiesByName 使用此SimEntity更新.
	* the shutdownId (whose default value was -1) is 0    
	* 一旦initCommonVariable()返回(請注意,我們現在是在方法init()), 就會創建一個        
			   CloudInformationService(它也派生自SimEntity)實例
	* (with its name as CloudInformatinService, id as -1, and state as RUNNABLE). 
			   然後這個新實體也被添加到模擬中. 
	* While being added to the simulation, the id of the SimEntitiy is changed to 1 
			   (which is the next id) from its earlier value of -1. 
	* 兩個集合 - entities 和 entitiesByName are updated with this SimEntity.
	* the cisId(whose default value is -1) is 1
	* Comment End - Dinesh Bhagwat 
	************************************************************************************************/
			 
			CloudSim.init(num_user, calendar, trace_flag);

			// 第二步:創建數據中心
			// Datacenters are the resource providers in CloudSim. We need at
			// list one of them to run a CloudSim simulation
			Datacenter datacenter0 = createDatacenter("Datacenter_0");

			// 第三步: Create Broker 代理
			DatacenterBroker broker = createBroker();
			int brokerId = broker.getId();

			// 第四步: Create one virtual machine
			vmlist = new ArrayList<Vm>();

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

			// create VM 以剛纔定義的參數創建VM
			Vm vm = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());

			// add the VM to the vmList 加入虛擬機列表
			vmlist.add(vm);

			// submit vm list to the broker 虛擬機列表提交給代理
			broker.submitVmList(vmlist);

			// 第五步: Create one Cloudlet 創建一個雲任務
			cloudletList = new ArrayList<Cloudlet>();

			// Cloudlet 參數
			int id = 0;
			long length = 400000;
			long fileSize = 300;
			long outputSize = 300;
			UtilizationModel utilizationModel = new UtilizationModelFull();
			// create cloudlet 以剛纔定義的參數創建雲任務
			Cloudlet cloudlet = 
                                new Cloudlet(id, length, pesNumber, fileSize, 
                                        outputSize, utilizationModel, utilizationModel, 
                                        utilizationModel);
			cloudlet.setUserId(brokerId);
			cloudlet.setVmId(vmid);

			// add the cloudlet to the list 雲任務加入列表
			cloudletList.add(cloudlet);

			// submit cloudlet list to the broker 雲任務列表提交給代理
			broker.submitCloudletList(cloudletList);

			// 第六步: Starts the simulation 開始仿真
			CloudSim.startSimulation();

			CloudSim.stopSimulation();

			//最後一步: Print results when simulation is over  仿真結束 打印結果
			List<Cloudlet> newList = broker.getCloudletReceivedList();
			printCloudletList(newList);

			Log.printLine("CloudSimExample1 finished!");
		} catch (Exception e) {             Java Exception 異常處理機制
			e.printStackTrace();
			Log.printLine("Unwanted errors happen");
		}
	}

	/**函數
	 * Creates the datacenter.
	 *
	 * @命名
	 *
	 * @return the datacenter
	 */
	private static Datacenter createDatacenter(String name) {

		// Here are the steps needed to create a PowerDatacenter:
		// 1. We need to create a list to store
		// our machine 創建列表儲存機器
		List<Host> hostList = new ArrayList<Host>();

		// 2. A Machine contains one or more PEs or CPUs/Cores. 一個機器含有的處理器
		// In this example, it will have only one core.
		List<Pe> peList = new ArrayList<Pe>();

		int mips = 1000;

		// 3. Create PEs and add these into a list. 創建處理器 並添加到Pe列表
		peList.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating Pe id 和 處理速度

		// 4. Create Host 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,
				peList,
				new VmSchedulerTimeShared(peList) 虛擬機時間共享
			)
		); // This is our machine

		// 5. 創建一個數據中心特徵對象,
		// 該對象存儲數據中心的屬性:體系結構、操作系統、機器列表、
		// 分配策略:時間或空間共享、時區及其價格(G$/Pe時間單位)
		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
		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. 最後, 創建數據中心對象
		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
	/** 創建代理,可以根據特定需求發展自己的代理協議來提交虛擬機和雲任務
	 *
	 * @return the datacenter broker
	 */
	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
	 */打印雲任務參數
	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()));
			}
		}
	}
}

運行結果:

結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章