Pull to refresh

VMware Server :: управляемся с парком машин

Reading time 7 min
Views 2.5K
Всем привет ;)

Продолжаем… (кто пропустил шаг назад)
Интересно, а как вы управляетесь с виртуальными машинами?!
Каждый раз, когда Вы делаете 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 — основной скрипт
'
' VmCOM VBScript Sample Script (sample2)
' Copyright 1998 VMware, Inc. All rights reserved. -- VMware Confidential

' Permission is hereby granted, free of charge, to any person obtaining a
' copy of the software in this file (the "Software"), to deal in the
' Software without restriction, including without limitation the rights to
' use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:

' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software.

' The names "VMware" and "VMware, Inc." must not be used to endorse or
' promote products derived from the Software without the prior written
' permission of VMware, Inc.

' Products derived from the Software may not be called "VMware", nor may
' "VMware" appear in their name, without the prior written permission of
' VMware, Inc.

' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' VMWARE,INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
' IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
' CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'
' ------
'
' This program is for educational purposes only.
' It is not to be used in production environments.
'
' Description:
'
' This script displays the virtual machines on the local server.
' It prints the configuration file path and current execution
' state of each VM. If a VM is in the stuck state, the current
' question and its choices are also printed.
' Additionally, if a VM is stuck on an undoable disk related
' question, the script automatically answers 'Keep' on a power-off
' and 'Append' on a power-on.
'
' NOTE: the question-answering logic used is language and product
'    dependent, and is only provided for illustration purposes only!
'
' Instructions for Windows 2000 and later operating systems:
'
' - save the contents of this file to a file named 'sample2.vbs'
'  unless it's already named that way
'
' - there should be an accompanying file named 'sample2.wsf'
'  It is placed in the same directory as this file during
'  product installation. This file is responsible for setting
'  up the Windows Script Host environment and loading the
'  VmCOM type library, thereby enabling this script to
'  reference symbolic constants such as vmExecutionState_On
'
' - in a command line window, type:
'  cscript //nologo sample2.wsf
'

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'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!

     Set r = new RegExp   
     r.pattern = "undoable disk"
     r.ignorecase = True
     Set matches = r.Execute(q.text)

     if matches.count > 0 then
      for i = 1 to choices.count
       if choices(i) = "Append" or choices(i) = "Keep" then
         WScript.Echo(s)
         s = "  --> Automatically selecting '" & q.choices(i) & "' as answer"
         vm.AnswerQuestion q,i
        exit for
        end if
      next
     end if
   end if
  end if
  WScript.Echo(s)
  Recheck(vm) 'добавляем вызов функции
next

function State2Str(vm)
  select case vm.ExecutionState
   case vmExecutionState_On
     State2Str = "ON"
   case vmExecutionState_Off
     State2Str = "OFF"
   case vmExecutionState_Suspended
     State2Str = "SUSPENDED"
   case vmExecutionState_Stuck
     State2Str = "STUCK"
   case else
     State2Str = "UNKNOWN"
  end select
end function
' Вот и сама функция, выставления ее на паузу и повторной проверки статуса машины
function Recheck(vm)
  if vm.ExecutionState = vmExecutionState_On then 'Проверка работы машины
         vm.Suspend (vmPowerOpMode_Hard) ' Установка паузы, в документации описаны дполнительные режимы паузы (можно использовать другие)
         WScript.Echo "Recheck this VM_machine state=" & State2Str(vm) 'вывод в лог повторной проверки
         WScript.Sleep(10000) 'Тайм аут, даем время все закрыть
   end if
end function
* This source code was highlighted with Source Code Highlighter.




Далее запускаемый скрипт check_vm.wsf, от которого передается управление к основному check_vm.vbs:

<job id="Check_vm">
  <reference object="VmCOM.VmCtl" />
  <script language="VBScript" src="check_vm.vbs" />
</job>

* This source code was highlighted with Source Code Highlighter.




Ну и наконец bat файл, который вы можете поставить выполнение, например на 22 часа рабочего времени. При таком использовании, никто не забудет, правильно выключить ваш любимый и горячо любимый парк.

cscript check_vm.wsf >> log.txt
shutdown -s -f -t 100


В bat происходит вызов скрипта, с перенаправлением в лог.
Ну shutdown, это как тюнинг на выключение. Можно попробовать поиграть в параметрами.

Пример лога:

path=E:\vmware\Ubuntu\Ubuntu.vmx state=ON os=ubuntu
Recheck this VM_machine state=SUSPENDED
path=E:\vmware\Ubuntu_Kde_4\Ubuntu.vmx state=OFF os=ubuntu
path=E:\development\FreeBSD\FreeBSD.vmx state=ON os=freebsd
Recheck this VM_machine state=SUSPENDED

Вот и вроде все. :)
Уфффф… Управились.
Спите спокойно, а самое главное берегите нервы.
До следующей статьи…
Tags:
Hubs:
+26
Comments 33
Comments Comments 33

Articles