Vmware guest shutdown что это
Записки виртуального админа
Новости, обзоры и заметки о виртуальных машинах и платформах виртуализации.
вторник, 4 мая 2010 г.
HA Deepdive: Isolation
До версии ESX 3.5 U2 / vCenter 2.5U2 ответ на изоляцию по умолчанию при создании нового кластера был «power off». В ESX 3.5 U3 / vCenter 2.5 U3 ответ был изменен на “leave powered on”, а в ESX 4.0 / vCenter 4.0 стал «shut down». Обязательно помните об этом при настройке новой среды, возможно, будет необходимо изменить ответ по умолчанию на какой-то конкретный для нужд заказчика.
Power off – при обнаружении изоляции все ВМ выключаются. В данном случае это жесткое выключение (выдернули вилку из 220В).
Shut down – при обнаружении изоляции все ВМ выключаются через VMware Tools (shutdown guest). По истечению 5-минутного таймаута оставшиеся включенными ВМ выключаются жестко.
Leave powered on – при обнаружении изоляции состояние ВМ не меняется.
Количество попыток перезапуска можно сконфигурировать начиная с vCenter 2.5 U4 при помощи advanced параметра «das.maxvmrestartcount». Значение по умолчанию 5. При версии vCenter до 2.5 U4 HA будет пытаться перезапустить ВМ бесконечно, что может привести к серьезным проблемам.
Для iSCSI я рекомендую установить ответ на изоляцию «Power off» во избежание split brain. Я также рекомендую иметь вторую Service Console на том же vSwitch, что и iSCSI для обнаружения проблем с ISCSI и соотв. ложных изоляций.
Я думал, что это знание из разряда базового, как 2*2=4, но недавний пост Mike Laverick указал, что я неправ. Думаю, что если Mike Laverick этого не знает, то это точно не общеизвестно.
По умолчанию таймаут для обнаружения изоляции/отказа 15 секунд. Иными словами, изолированный или отказавший хост будет объявлен умершим остальными хостами в HA кластере на 15 секунде и рестарт ВМ будет инициирован одним из primary хостов.
Предположим, что ответ на изоляцию «power off». Действие «power off» будет инициировано изолированным хостом за две секунды до истечения das.failuredetectiontime. Действие «power off» будет инициировано на 13й секунде, а рестарт на 15й.
VMware Server :: управляемся с парком машин
Продолжаем… (кто пропустил шаг назад)
Интересно, а как вы управляетесь с виртуальными машинами?!
Каждый раз, когда Вы делаете snapshot, ставите на паузу или выключаете машину(ы) Вы тратите на это время?!
Тогда мы идем к Вам! 🙂
Попытаюсь рассказать, как лично я автоматизировал работу с виртуальными машинами.
Многим это покажется полной тупостью, но это решение и ОНО найдено руками пользователя, а не разработчика.
Начнем с самого болезненого, с выключения. Почему с него, да потому что обычно на него никогда не хватает время, вечно куда-то опаздываешь. Ну или, например, оставляешь коллеге, а он по забывчивости не выключает ее.
Не знаю как у остальных, но на моей практике доказано: если выставить машину в режим самовыключения (режим On host shutdown — Shut down guest operating system), то вероятность некорректного выключения очень высока. Vmware просто не успевает корректно все остановить.
Если у кого-то есть желание, можно испытать: берем сервер, запускаем несколько машин c ОС FreeBSD, запускаем на них нагрузочные тесты, выключаем ОС под которой крутится VM. Получаем при новом старте запуск fsck на FreeBSD.
Итого: в таких ситуациях рекомендую VMware ставить на паузу. При снятии с паузы вам остается только синхронизировать время.
А знаете ли вы. при плотной загрузке виртуальными машинами физ.сервера, происходит замедление времени на каждой из них.
Переходим к самому интересному.
Реализация скрипта для автоматического перехода в режим паузы, всех работающих машин.
А знаете ли вы. под VMware можно разрабатывать скрипты управления машинами.
Более подробно можно почитать на http://www.vmware.com/support/pubs/server_pubs.html
Перед Вами представлен модифицированный пример-скрипт из поставки дистрибутива VMware (на чем он написан тут все сказано):
Примитивный алгоритм работы:
1. Проверка всех зарегистрированных машин (определенных в invetory).
1.1. Машина работает.
1.1.1 Ставим на паузу
1.1.2 Проверяем встала или нет.
check_vm.vbs — основной скрипт
Set cp = CreateObject( «VmCOM.VmConnectParams» )
Set server = CreateObject( «VmCOM.VmServerCtl» )
server.Connect cp
Set vmCollection = server.RegisteredVmNames
for each vmName in vmCollection
Set vm = CreateObject( «VmCOM.VmCtl» )
s = «path=» & vmName
On error resume next ‘ Clear error object
vm.Connect cp,vmName
if err.Number = vmErr_VMBUSY then
s = s & » UNAVAILABLE (controlled by local console)»
elseif err.Number <> 0 then
s = s & » ERROR CONNECTING desc='» & err.Description & «‘»
else
On error goto 0 ‘Make errors fatal past this point
s = s & » state=» & State2Str(vm) & » os=» & vm.Config( «guestos» )
if vm.ExecutionState = vmExecutionState_Stuck then
Set q = vm.PendingQuestion
Set choices = q.choices
s = s & » question= ‘» & q.text & «‘ choices=»
for each choice in choices
s = s & «[» & choice & «] »
next
‘ If this looks like an undoable disk save question,
‘ automatically answer ‘Append’ or ‘Keep’
‘
‘ NOTE: this code makes alot of assumptions about the product
‘ and the language used, and may break under some environments.
‘ It is shown for illustration purposes only!
Vmware guest shutdown что это
When running VMware and you want to shut down or restart the guest OS, it is very tempting to sometimes just use the buttons in the “Power Toolbar”. One thing you should realize is that shutting down or restarting your OS using these buttons is the equivalent of cutting off power to your PC and instantly shutting off. Since this typically isn’t good practice and can lead to settings not being saved or more importantly, the loss of data you should always go through the OS’s shutdown procedure.
Then why do they put the buttons on the toolbar if they are useless you ask? These buttons are configurable to do what you want. You can set the buttons to go through the proper OS shutdown or restart procedures. To change this setting, open VMware and click on the VM menu and choose settings. Once the settings menu is up, choose the “Options” tab and click on the “Power” setting in the list on the left. Here you can change the stop button from “Power Off” to “Shut Down Guest” and the restart button from “Reset” to “Restart Guest”.
These buttons work by telling the guest OS to run a shutdown or restart script and that requires VMware Tools to be installed on your guest OS. Additionally, you can customize these scripts by launching VMware Tools in your guest OS and going to the “Scripts” tab. here you can specify specific scripts you want run for the different events.
Following this process should give you a quick and easy way to shutdown or restart your virtual machine with one click instead of going through the menus.
Share this:
Like this:
Related
2 Responses to “VMware: Proper Shutdown & Restart of Guest OS”
I have this acute problem with shut down is VMWare… The host OS is Ubuntu Feilsy. The guest OS is Mandriva (Spring 2007). Now, when I shut down the guest OS (just by
shutting Mandriva down), VMWare hangs and then I lose mouse/keyboard control… If I “Power down” the virtual machine, VMWare crashes and Ubuntu stays up, but when I shut down Ubuntu, the “Virtual Machine” can’t be closed down, so the shut down process is halted… Anyways, in both cases, I have to do a “hard reboot” (hold the power button of the PC for 5 seconds, forcing the PC to reboot..) ANd that’s very-very bad! Please help me if you know anything about this. Assalamu Alaykum!
Ok so a user chose to power off before shutting down and we can no longer open the vm. Is there a chance of recovery?
Настройка автозапуска для виртуальных машин на VMware ESXi
По умолчанию все виртуальные машины, запущенные на сервере VMWare ESXi или VMware Hypervisor не запускаются автоматически после перезагрузки сервера. Это означает, что после перезагрузки хоста ESXi (плановой или неплановой, по питанию), администратору придется вручную запускать все виртуальные машины. Разберемся, как настроить автоматический запуск ВМ на сервере VMWare ESXi, чтобы ВМ загружались автоматом без участия администратора.
Как вы видите все ВМ, расположенные на данном сервере ESXi, перечислены в списке Manual Startup. Это означает, что после перезагрузки сервера, их нужно включать вручную.
Чтобы они загружались автоматически, нужно вручную добавить в список Automatic Startup. Для этого нажмите кнопку Edit.
В диалоговом окне Edit VM Startup and Shutdown, поставьте чекбокс Autmatically start and stop the virtual machines with the system. Теперь можно настраивать параметры автозапуска ВМ.
Доступны следующие опции включения/выключения виртуальных машин:
Можно поместить ВМ в одну из следующих секций:
Выберите виртуальную машину и с помощью кнопок Вверх/Вниз переместите ее в секцию Automatic Startup. Аналогичную операцию выполните для всех ВМ.
Сохраните изменения, нажав ОК.
Кроме того, параметры автозапуска ВМ могут быть настроены с помощью PowerCLI. Выведем список ВМ на хосте с их настройками автозапуска:
Get-VM –VMname * | Select-Object VMname, AutomaticStartAction
Чтобы включить автозапуск для всех ВМ, чьё имя начинается с msk, выполните команду:
Get-VM –VMname msk* | Set-VM –AutomaticStartAction Start
Vmware guest shutdown что это
I am using powershell + powerCLI to build a shutdown vmwares script. My goal is: using shutdown-vmguest command to shutdown the virtual machines, if VM’s vmware tools have some problems (not running / not installed) switch to stop-vm command to power off virtual machines automatically.
I don’t know how to monitor the command exit codes to branch to stop-vm command automation in the script yet. Please teach me about that case.
I’d just do it in two foreach loops.
In the first loop use shutdown-VMGuest against all VMs that are poweredOn and have the VMware Tools running.
In the second loop use Stop-VM against all VMs that are running. That will kill your VMs without the Tools and also those with tools that hung up during shutdown.
your idea is quite helpful for me. But I am wondering about the time to finish the task of the script beacuse now we have hundreds of virtual machines need to shutdown in the short-time (about 15 minutes) in fact. So, how to run shutdown command to multiple virtual machine at the same time (parallel summited)? and according to your method (2 loops) when the Shutdown-VMguest loop finish, we have to wait for all virtual machines shutted down already (status to power off) then do the second loop use Stop-VM command for the other running VMs, right? if that it take me along time to done.
Thus, I want to Power off action (Stop-VM) with shutdown guest error VMs only for time saving.
Ok, hundreds of VMs, you didn’t mention that :smileygrin:
Bad news: Shutdown-VMGuest doesn’t have that switch.
As a Workaround I would think about launching one instance of the script for each of your ESXi server ( depending on the number of VMs running on each ).
and let each instance of the script only shutdown the VMs that are running on this one ESXi server:
Well, I will try to do as your comments.
Thanks for your sound
When you run the script once for every Host, yes you will get the 70 shutdowns simultaneously Keep in mind there’s a 500 sessions limit in vCenter, in case you have manye other things running. Also I have no idea how 70 running scripts will impact the performance. Might be usefull to reduce the number of running scripts a little by processing 2 or 3 ESXi hosts per script instance
Well, I will try to do as yo ur comments.
I hope you don’t try it in your productive environment :smileygrin: