Exemple #1
0
	def start(self,vmname):
		"""Starts a virtual machine
		vmname: Name of the virtual machine"""
		if vmname in self.vmhash:
			return "Error: VM is already running"
		for vmfile in os.listdir(self.vmpath):
			vm = Vm(self.vmpath+'/'+vmfile,self.disks)
			if vm.name==vmname:
				if vm.status=="stopped":
					self.vmhash[vm.name] = vm
					vm.start()
					return "started VM"
				else:
					return "Error: VM is not stopped"
		return "Error: VM not found"
Exemple #2
0
	def resume(self,vmname):
		"""Resumes a suspended virtual machine from a snapshot.
		vmname: Name of the virtual machine"""
		if vmname in self.vmhash:
			if self.vmhash[vmname].hasFinished()==None:
				return "Error: VM is still running"
		for vmfile in os.listdir(self.vmpath):
			vm = Vm(self.vmpath+'/'+vmfile,self.disks)
			if vm.name==vmname:
				if vm.status=="suspended":
					self.vmhash[vm.name] = vm
					vm.resume()
					return "Resumed VM"
				else:
					return "Error: VM not suspended"
		return "Error: VM not found"
Exemple #3
0
    def GetVmBySummaryPath(self, vmxFilename):
        self.serviceInstance

        dsPath = self.GetDsPathFromLocalPath(vmxFilename)
        if (dsPath == None):
            return None

        managedObject = pyVim.folder.FindBySummaryPath(dsPath)
        if managedObject is None:
            return None

        vm = Vm(host=self, managedObject=managedObject)

        if not managedObject:
            vm.dsPath = dsPath

        return vm
Exemple #4
0
    def GetVmByCfgPath(self, vmxFilename):
        """
      @todo Look at moving path conversion stuff into pyVim or other lib
      """

        self.serviceInstance

        dsPath = self.GetDsPathFromLocalPath(vmxFilename)
        managedObject = pyVim.folder.FindCfg(dsPath)
        if managedObject is None:
            raise pyVmomi.vim.fault.NotFound(
               msg='No virtual machine found with config path: %s' \
                   % vmxFilename)

        vm = Vm(host=self, managedObject=managedObject)

        if not managedObject: vm.dsPath = dsPath

        return vm
Exemple #5
0
    def GetVms(self):
        self.serviceInstance

        if not self._vmList:
            self._vmList = [
                Vm(host=self, managedObject=managedObject)
                for managedObject in pyVim.folder.GetAll()
            ]

        return self._vmList
    def AcceptNewECS(self):
        #读取现有所有机器
        OldList = self.VQ.q
        OldResource = self.NCPool.NCResource
        NewList = []
        while True:
            NewEcs = self.NewVm.get1vm(gl.get_value('NowDate'))
            if NewEcs != None:  #列表里还有机器
                #EcsListTmp.append(NewEcs)
                NewVm = Vm(NewEcs["vmid"], NewEcs["vmtype"],
                           NewEcs["createtime"], NewEcs["releasetime"])
                # 添加今日新机至机器列表
                NewList.append(NewVm)
            else:  #所有机器读完,释放所有资源
                break

        EcsListTmp = OldList + NewList

        # 机器排序
        # 线性规划
        while True:
            DisAns = self.NCPool.Distribute_ECS(EcsListTmp)
            if DisAns == None:
                # 无解,要删机器了
                self.NCPool.NCResource = OldResource  # 恢复资源使用量,避免出现负数
                self.NCPool.DeleteEcs(NewList)
                EcsListTmp = OldList + NewList
            else:
                break
        loseVm = []
        # 依次给每个机器安排资源
        for NewECS in EcsListTmp:
            NewVM = self.NCPool.create1Vm(NewECS, DisAns)  #给这一块ECS分配内存

            if NewVM != None:
                if NewVM.status == "running":  #可以分配成功,计算收益
                    #self.gl.get_value('OP')writevm((gl.get_value('NowDate'),NewVM.name,NewVM.status,NewVM.NC.NCid,NewVM.Type,NewVM.CPU,NewVM.Memory,NewVM.createtime,NewVM.releasetime))
                    gl.get_value('OP').writevm(
                        (gl.get_value('NowDate'), NewVM.name, NewVM.status,
                         NewVM.NC.NCid, NewVM.Type, NewVM.CPU, NewVM.Memory,
                         NewVM.createtime, "\\N"
                         if NewVM.releasetime == datetime.datetime.strptime(
                             "2099-12-31 00:00:00",
                             '%Y-%m-%d %H:%M:%S').date() else
                         NewVM.releasetime))
                    gl.set_value('TodayEarnMoney',
                                 gl.get_value('TodayEarnMoney') + NewVM.Income)
                else:  #分配不成功,直接输出,正式答案里不输出
                    #self.VQ.delete(NewVM)#从现存队列中删除,删除以后队列自动向前移动,会漏数据
                    loseVm.append(NewVM)
                    #self.gl.get_value('OP')writevm((gl.get_value('NowDate'),NewVM.name,NewVM.status,NewVM.NC.NCid,NewVM.Type,NewVM.CPU,NewVM.Memory,NewVM.createtime,NewVM.releasetime))
                    #gl.get_value('OP').writevm((gl.get_value('NowDate'),NewVM.name,NewVM.status,None,NewVM.Type,NewVM.CPU,NewVM.Memory,NewVM.createtime,"\\N" if NewVM.releasetime == datetime.datetime.strptime("2099-12-31 00:00:00",'%Y-%m-%d %H:%M:%S').date() else NewVM.releasetime,None,None,None))
        self.VQ.q = EcsListTmp
        self.VQ.delete(loseVm)
        self.VQ.sortMyself()
Exemple #7
0
    def GetVmBySummaryName(self, name):
        self.serviceInstance

        if (not self._nameToVm.has_key(name)):
            managedObject = pyVim.folder.FindBySummaryName(name)
            if managedObject is None:
                return None

            vm = Vm(host=self, managedObject=managedObject)
            self._nameToVm[name] = vm
            return vm

        return self._nameToVm[name]
Exemple #8
0
    def GetVmByName(self, name):
        self.serviceInstance

        if not self._nameToVm.has_key(name):
            managedObject = pyVim.folder.Find(name)
            if managedObject is None:
                raise pyVmomi.vim.fault.NotFound(
                    msg='No virtual machine found with name: ' + name)

            vm = Vm(host=self, managedObject=managedObject)
            self._nameToVm[name] = vm

        return self._nameToVm[name]
Exemple #9
0
def main():
	print("vm server initializing")
	config = libxml2.parseFile("config.xml")
	for node in config.xpathEval('/vmconfig/path'):
		 vmpath = node.content
	print(vmpath)
	for node in config.xpathEval('/vmconfig/diskspath'):
		 diskspath = node.content
	print(diskspath)
	for node in config.xpathEval('/vmconfig/auth/login'):
		login = node.content
	for node in config.xpathEval('/vmconfig/auth/passwd'):
		passwd = node.content
	for node in config.xpathEval('/vmconfig/bind/ip'):
		bindip = node.content
	for node in config.xpathEval('/vmconfig/bind/port'):
		bindport = int(node.content)
	disks = Disks(diskspath)
	for vmfile in os.listdir(vmpath):
		vm = Vm(vmpath+'/'+vmfile,disks)
		if vm.autostart:
			print("autostarting "+vm.name)
			vm.awake()
			if vm.status=="running":
				vmhash[vm.name] = vm
	signal.signal(signal.SIGINT, shutdown)
	signal.signal(signal.SIGTERM, shutdown)
	#signal.pause()
	vmrpc = VmRpc(vmpath,disks,vmhash)
	server = DocXMLRPCServer.DocXMLRPCServer(tuple([bindip, bindport]))
	server.register_instance(vmrpc)
	print "Listening on: http://"+bindip+":"+str(bindport)+"/"
	server.timeout = 1
	while True:
		handleFinished()
		#server.serve_forever()
		server.handle_request()
	return
Exemple #10
0
def create_vm(os, name, memory, cpu_n):
    try:
        vms = get_vms()
        exists = False
        for vm in vms:
            if vm["name"] == name:
                exists = True
        if exists:
            return -1

        base_image = 'linux_base'
        if os == 'Windows 2008 (64-bit)':
            base_image = 'windows_base'
        vm = Vm()
        vbox = VBox()
        vbox.create(base_image, name, memory * 1024, cpu_n)
        return 1
    except Exception as e:
        print('error - create_vm')
        print(e)
        return 0
Exemple #11
0
def get_vms():
    try:
        vbox = VBox()
        vms = vbox.list_vms()
        data = []

        for vm in vms:
            vm_obj = Vm()
            vm_obj.set_cpus(vm["Number of CPUs"])
            vm_obj.set_name(vm["Name"])
            vm_obj.set_memory(float(vm["Memory size"]))
            vm_obj.set_os(vm["Guest OS"])
            vm_obj.set_state(vm["State"])
            data.append(vm_obj.__dict__)

        return data
    except Exception as e:
        print('error - get_vms')
        print(e)
        return 0