Desligamento automático seletivo com apcupsd

Neste artigo quero mostrar como desligar de forma automática os servidores ou estações de trabalho em caso de falha no fornecimento de energia elétrica. Utilizarei um software chamado apcupsd, que funciona com os Nobreaks APC. O desligamento automático visa evitar a corrupção de dados em caso de desligamento incorreto.

[ Hits: 47.084 ]

Por: Delton em 05/07/2011


Configuração dos agentes



Para configurar os agentes basta executar a instalação do apcupsd da mesma forma que no servidor. A única diferença é o arquivo de configurações, que deve ficar assim:

UPSCABLE ether
UPSTYPE net
DEVICE ip-do-servidor:3551

Para garantir que as máquinas virtuais sejam desligadas antes que os hospedeiros, basta alterar os valores do BATTERYLEVEL e MINUTES.

Nos servidores Linux não é necessária mais nenhuma modificação. Já para os servidores Windows, é necessário alterar o arquivo apccontrol.bat. Substitua todo o conteúdo por este:

@echo off
setlocal
REM ####################################
REM Description: This script is used to handle the different events for the
REM      apcupsd service on server.test.com
REM Required files: background, popup, apcupsd, shutdown, hostname, tr, blat
REM Last modified: July 6, 2010
REM ####################################
REM ################
REM Set variables
REM ################

set command=%1
set background="F:\Program Files\apcupsd\bin\background.exe"
set popup=%background% "F:\Program Files\apcupsd\bin\popup.exe"
set apcupsd="F:\Program Files\apcupsd\bin\apcupsd.exe"
set shutdown="C:\APC\apcupsd\etc\apcupsd\PSshutdown.exe"
set hostname="C:\WINDOWS\system32\hostname.exe"
REM set tr="F:\Program Files\System Utilities\bin\tr.exe"
set blat="C:\WINDOWS\system32\blat.exe"

%hostname% > %hostname_results%#
for /f "tokens=1" %%x in (%hostname_results%#) do (set host=%%x)
del /f /q # > nul 2>&1
REM echo %host% | %tr% '[:upper:]' '[:lower:]' > %lowercase_results%#
for /f "tokens=1" %%x in (%lowercase_results%#) do (set host=%%x)
del /f /q # > nul 2>&1
set host=server
set month=%date:~-10,2%
set day=%date:~-7,2%
set year=%date:~-2,2%
set current_day=%month%/%day%/%year%
set hour=%time:~-11,2%
REM put a leading zero for hours before 10 AM
if "%time:~0,1%"==" " set hour=0%hour:~1,1%
set minute=%time:~-8,2%
set second=%time:~-5,2%
set current_time=%hour%:%minute%:%second%
set timestamp=%current_day% %current_time%
set to=networkalerts@test.com
set profile=test.com
REM Use call here because event script might be a batch file itself
call ".\%command%" 2> nul
REM This is retarded. "if errorlevel 99" means greater-than-or-
REM equal-to 99, so we have to synthesize an == using two ifs.
REM Ahh, the glory of Windows batch programming. At least they
REM gave us a NOT op.
if not errorlevel 99 goto :events
if not errorlevel 100 goto :done
:events
REM
REM powerout, onbattery, offbattery, mainsback events occur
REM   in that order.
REM
if "%command%" == "commfailure"   goto :commfailure
if "%command%" == "commok"        goto :commok
if "%command%" == "powerout"      goto :powerout
if "%command%" == "onbattery"     goto :onbattery
if "%command%" == "offbattery"    goto :offbattery
if "%command%" == "mainsback"     goto :mainsback
if "%command%" == "failing"       goto :failing
if "%command%" == "timeout"       goto :timeout
if "%command%" == "loadlimit"     goto :loadlimit
if "%command%" == "runlimit"      goto :runlimit
if "%command%" == "doshutdown"    goto :doshutdown
if "%command%" == "annoyme"       goto :annoyme
if "%command%" == "emergency"     goto :emergency
if "%command%" == "changeme"      goto :changeme
if "%command%" == "remotedown"    goto :remotedown
if "%command%" == "startselftest" goto :startselftest
if "%command%" == "endselftest"   goto :endselftest
if "%command%" == "battdetach"    goto :battdetach
if "%command%" == "battattach"    goto :battattach
echo Unknown command '%command%'
echo.
echo Usage: %0 command
echo.
echo Warning: this script is intended to be launched by
echo apcupsd and should never be launched by users.
goto :done
:commfailure
   set description=Warning communications lost with UPS %2.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:commok
   set description=Communications restored with UPS %2.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:powerout
   goto :done
:onbattery
   set description=Power failure on UPS %2. Running on batteries.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:offbattery
   set description=Power has returned on UPS %2.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:mainsback
   goto :done
:failing
   set description=Battery power exhausted on UPS %2. Doing shutdown.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:timeout
   set description=Battery time limit exceeded on UPS %2. Doing shutdown.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:loadlimit
   set description=Remaining battery charge below limit on UPS %2. Doing shutdown.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:runlimit
   set description=Remaining battery runtime below limit on UPS %2. Doing shutdown.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:doshutdown
REM set description=Apccontrol doing: %apcupsd% /kill on UPS %2.
REM %popup% "%description% [%timestamp%]"
REM %apcupsd% /kill
REM %shutdown% /s /f /t 15 /c "Shutting down due to apcupsd event."
REM %plink% root@192.168.0.1 -pw senha  "sh .scripts/shutdown-esxi.sh"
    %shutdown% -k -e u:0:0
    goto :done
:annoyme
   set description=Power problems with UPS %2. Please logoff.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:emergency
   set description=Emergency shutdown. Possible battery failure on UPS %2.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:changeme
   set description=Emergency! Batteries have failed on UPS %2. Change them NOW.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:remotedown
   set description=Remote shutdown. Beginning shutdown sequence.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:startselftest
   set description=Self-test starting
   %popup% "%description% [%timestamp%]"
   goto :done
:endselftest
   set description=Self-test completed
   %popup% "%description% [%timestamp%]"
   goto :done
:battdetach
   set description=Battery disconnected.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:battattach
   set description=Battery reattached.
   %popup% "%description% [%timestamp%]"
   set subject="Network Alert: Apcupsd event (%1) on %host% [%timestamp%]"
   set body="%timestamp% %description%"
   %blat% -to %to% -subject %subject% -body %body% -p %profile% -q > nul 2>&1
   goto :done
:done

No início do arquivo os comandos set definem o caminho dos programas auxiliares utilizados.

Detalhe importante: o serviço apcupsd deve ser executado como administrador, caso contrário não haverá permissão para iniciar o shutdown.
Página anterior     Próxima página

Páginas do artigo
   1. Introdução e Estrutura dos Servidores
   3. Arquivos de configuração
   4. Configuração dos agentes
   5. Desligar o ESXi e Considerações Finais
Outros artigos deste autor

Quando o Linux me deixou na mão

Leitura recomendada

Iptraf Sniffer - noções básicas

YASG (Yet Another Security Guide)

Dark Web e Malwares na internet, quanto custa?

Ferramentas de administração remota

Backup de sua instalação em .iso bootável

  
Comentários
[1] Comentário enviado por carlosalberto4ti em 11/07/2011 - 21:30h

Grante , muito interessante .

Tenho alguns servidores que tomo conta , vou tentar aplicar esse tutorial aos mesmo .

Parabéns pela capacidade !

[2] Comentário enviado por JohnRobson em 19/07/2011 - 21:36h

Muito obrigado pelo tutorial.

2 semanas atrás meu servidor na faculdade ficou sem energia por 1h e como o nobreak não estava configurado corretamente desligou o servidor sem qualquer aviso de shutdown; o /etc/fstab ficou corrompido e centenas de alunos foram prejudicados por algumas horas até eu poder resolver o problema...

Executei todos os passos e funcionaram perfeitamente, parabéns pelo tutorial.

[3] Comentário enviado por mauroprojetos em 02/09/2013 - 16:29h

Amigo esse modelo de nobreak tem suporte para modulo de bateria?
Estou procurando algum model ode apc para rack com essa caracteristica.

Abraços e parabéns pelo tutorial.

[4] Comentário enviado por mauroprojetos em 20/05/2015 - 17:07h


Amigo aonde baixo o programa o executavel abaixo?
REM set tr="F:\Program Files\System Utilities\bin\tr.exe"

[5] Comentário enviado por wpopov em 31/03/2016 - 17:56h

Pessoal,

desenvolvi um driver para o software apcupsd para os modelos da APC Brasil com protocolo herdado da Microsol. Esse driver não está disponível no projeto apcupsd original. O projeto que pode ser utilizado com esses modelos é:

http://apcupsd-brazil.sourceforge.net/

Tem 2 meses que ele está rodando no meu servidor sem problema.

att,
Wagner
wpopov

Posts: 2
Joined: 2014/10/07 15:21:12

[6] Comentário enviado por bifi em 02/02/2017 - 16:29h

Boa tarde Amigo,
Excelente artigo, me ajudou muito, queria saber se consigo fazer o linux e não o windows desligar o esxi, ou seja fazer o linux executar o script shutdown-host.sh.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts