crispud

Untitled

Feb 27th, 2026
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.93 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "net"
  5.     "os/exec"
  6.     "time"
  7. )
  8.  
  9. const (
  10.     target        = "192.168.1.50:8080" // IP:porta da controllare
  11.     serviceName   = "mioservizio"       // servizio systemd
  12.     checkInterval = 5 * time.Second
  13.     maxFailures   = 3
  14.     timeout       = 2 * time.Second
  15. )
  16.  
  17. func checkTCP(addr string, timeout time.Duration) bool {
  18.     conn, err := net.DialTimeout("tcp", addr, timeout)
  19.     if err != nil {
  20.         return false
  21.     }
  22.     conn.Close()
  23.     return true
  24. }
  25.  
  26. func systemctl(action string) {
  27.     cmd := exec.Command("systemctl", action, serviceName)
  28.     cmd.Run()
  29. }
  30.  
  31. func main() {
  32.     failCount := 0
  33.     serviceDown := false
  34.  
  35.     for {
  36.         ok := checkTCP(target, timeout)
  37.  
  38.         if ok {
  39.             failCount = 0
  40.             if serviceDown {
  41.                 systemctl("start")
  42.                 serviceDown = false
  43.             }
  44.         } else {
  45.             failCount++
  46.             if failCount >= maxFailures && !serviceDown {
  47.                 systemctl("stop")
  48.                 serviceDown = true
  49.             }
  50.         }
  51.  
  52.         time.Sleep(checkInterval)
  53.     }
  54. }
Tags: watchdog
Advertisement
Add Comment
Please, Sign In to add comment