Pregunta

He visto la pregunta formulada " ¿puede ejecutar Monit en Windows? " ;, y a menos que quiera usar una VM, la respuesta parece ser no.

Entonces ... ¿hay alguna aplicación pequeña de tipo monit en realidad para los sistemas operativos Windows? Lo que estoy buscando no es solo monitorear (de los cuales hay cientos de aplicaciones), sino también la capacidad de ejecutar un script o reiniciar un servicio. Por ejemplo, monitoree una página web y reinicie Tomcat si esa página deja de responder (no puede simplemente mirar el servicio, porque el servicio aún se está ejecutando pero no responde correctamente).

Esto es para una aplicación pequeña, no para una aplicación grande, por lo que no se desean las soluciones pesadas / costosas.

¿Fue útil?

Solución

No encontré nada que se ajustara a mis necesidades, así que aprendí un poco de scripts de Powershell y desarrollé una solución que también debería ser útil para otros. Suponiendo una plataforma de Windows (¡de lo contrario, use monit!), Powershell es realmente potente y fácil.

script sample-monitor.ps1:

$webClient = new-object System.Net.WebClient

###################################################
# BEGIN USER-EDITABLE VARIABLES

# the URL to ping
$HeartbeatUrl = "http://someplace.com/somepage/"

# the response string to look for that indicates things are working ok
$SuccessResponseString = "Some Text"

# the name of the windows service to restart (the service name, not the display name)
$ServiceName = "Tomcat6"

# the log file used for monitoring output
$LogFile = "c:\temp\heartbeat.log"

# used to indicate that the service has failed since the last time we checked.
$FailureLogFile = "c:\temp\failure.log"

# END USER-EDITABLE VARIABLES
###################################################

# create the log file if it doesn't already exist.
if (!(Test-Path $LogFile)) {
    New-Item $LogFile -type file
}

$startTime = get-date
$output = $webClient.DownloadString($HeartbeatUrl)
$endTime = get-date

if ($output -like "*" + $SuccessResponseString + "*") {
    # uncomment the below line if you want positive confirmation
    #"Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile

    # remove the FailureLog if it exists to indicate we're in good shape.
    if (Test-Path $FailureLogFile) {
        Remove-Item $FailureLogFile
    }

} 
else {
    "Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile

    # restart the service if this is the first time it's failed since the last successful check.
    if (!(Test-Path $FailureLogFile)) {
        New-Item $FailureLogFile -type file
        "Initial failure:" + $startTime.DateTime >> $FailureLogFile
        Restart-Service $ServiceName
    }
}

La única lógica en este script es que solo intentará reiniciar el servicio una vez después de una falla inicial. Esto es para evitar una situación en la que un servicio tarda un tiempo en reiniciarse, y mientras se reinicia, el monitor sigue viendo la falla y se reinicia nuevamente (bucle infinito defectuoso). De lo contrario, puede hacer casi cualquier cosa, como agregar notificaciones por correo electrónico o hacer más que simplemente reiniciar un servicio.

Este script se ejecutará una vez, lo que significa que deberá controlar su repetición externamente. Podrías ponerlo en un bucle infinito directamente en el guión, pero eso parece un poco inestable. Usé el Programador de tareas de Windows, ejecutándolo así: Programa: Powershell.exe argumentos: -command " C: \ projects \ foo \ scripts \ monitor.ps1 " -sin perfil Comience en: C: \ projects \ foo \ scripts

También podría usar un programador más robusto como VisualCron, conectarlo a un servicio de Windows o mediante un programador de servidor de aplicaciones como Quart.NET. En mi caso, el programador de tareas funciona bien.

Otros consejos

Ajusté un poco el script de Dan Tanner cuando no pudo conectarse, mostró un error y no reinicié el servicio

$webClient = new-object System.Net.WebClient

###################################################
# BEGIN USER-EDITABLE VARIABLES

# the URL to ping
$HeartbeatUrl = "http://localhost:8080/"

# the response string to look for that indicates things are working ok
$SuccessResponseString = "Apache"

# the name of the windows service to restart (the service name, not the display name)
$ServiceName = "Tomcat6"

# the log file used for monitoring output
$LogFile = "c:\temp\log.log"

# used to indicate that the service has failed since the last time we checked.
$FailureLogFile = "c:\temp\log2.log"

# END USER-EDITABLE VARIABLES
###################################################

# create the log file if it doesn't already exist.
if (!(Test-Path $LogFile)) {
    New-Item $LogFile -type file
}

$startTime = get-date
try {
    $output = $webClient.DownloadString($HeartbeatUrl)
    $endTime = get-date

    if ($output -like "*" + $SuccessResponseString + "*") {
        # uncomment the below line if you want positive confirmation
        #"Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile

        # remove the FailureLog if it exists to indicate we're in good shape.
        if (Test-Path $FailureLogFile) {
            Remove-Item $FailureLogFile
        }

    } 
    else {
        "Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile

        # restart the service if this is the first time it's failed since the last successful check.
        if (!(Test-Path $FailureLogFile)) {
            New-Item $FailureLogFile -type file
            "Initial failure:" + $startTime.DateTime >> $FailureLogFile
            Restart-Service $ServiceName
        }
    }
    }catch [Net.WebException] {
        New-Item $FailureLogFile -type file
        "Initial failure:" + $startTime.DateTime + $_.Exception.ToString() >> $FailureLogFile
        Restart-Service $ServiceName
}

Estoy usando ipsentry de RGE Inc ( http://www.ipsentry.com/ ).

Lo he estado usando durante varios años, me salvó muchas veces.

Sin afiliación con ellos, esto no es un anuncio, solo información de un cliente satisfecho.

Esto se puede lograr al menos parcialmente usando el Administrador de control de servicios que se incluye con Windows. Supervisa las aplicaciones de servicio y puede iniciarlas automáticamente en el arranque, reiniciarlas cuando se bloquea, etc. Escribir su aplicación como un servicio es una opción, pero si no puede escribir la aplicación como un servicio, puede intentar ajustar el proceso usando srvany.exe en el Kit de recursos de Windows.

Más información sobre cómo escribir un servicio: https://support.microsoft.com/en -us / kb / 137890

En cuanto a las funciones de monitoreo reales, no estoy completamente seguro de lo que está disponible, o la extensión de las capacidades de SCM.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top