is_master-go/is_master.go

113 lines
2.1 KiB
Go
Raw Normal View History

2019-06-27 18:37:47 +00:00
package main
import (
"fmt"
"flag"
"os"
"syscall"
"strings"
"net"
"regexp"
)
// Option to parse
var (
HELP = flag.Bool("help", false, "print the help message")
2019-06-29 06:01:45 +00:00
IP = flag.String("ip", "", "ip expected")
FILE = flag.String("file", "", "path file expected")
2019-06-27 18:37:47 +00:00
COMMAND = flag.String("command", "", "command to execute")
2019-06-27 19:08:08 +00:00
NOT = flag.Bool("not", false, "execute the command if the ip or the file isn't present")
2019-06-27 18:37:47 +00:00
)
// Critical print a message and exit with code 2
func Critical(msg string) {
fmt.Println(fmt.Sprintf("CRITICAL - %s", msg))
os.Exit(2)
}
// Warning print a message and exit with code 1
func Warning(msg string) {
fmt.Println(fmt.Sprintf("WARNING - %s", msg))
os.Exit(1)
}
// Ok print a message and exit with code 0
func Ok(msg string) {
fmt.Println(fmt.Sprintf("OK - %s", msg))
os.Exit(0)
}
func init() {
flag.Parse()
if *HELP {
flag.PrintDefaults()
os.Exit(3)
}
if *IP == "" && *FILE == "" {
Critical("Please set file or ip option")
}
if *COMMAND == "" {
Critical("Please set command option")
}
}
// fileExist return true if the file exist
func fileExist(path string) bool {
_, err := os.Stat(*FILE)
if err == nil {
return true
}
return false
}
// ipExist return true if an interface has the ip
func ipExist(ip string) bool {
r := regexp.MustCompile(`^(.*)/\d{1,2}$`)
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
match := r.FindSubmatch([]byte(fmt.Sprintf("%s", addr)))
if len(match) == 0 {
continue
}
if string(match[1]) == ip {
return true
}
}
}
return false
}
func main() {
2019-06-27 19:08:08 +00:00
var execute bool
2019-06-27 18:37:47 +00:00
if *FILE != "" {
2019-06-27 19:08:08 +00:00
execute = fileExist(*FILE)
2019-06-27 18:37:47 +00:00
} else {
2019-06-27 19:08:08 +00:00
execute = ipExist(*IP)
2019-06-27 18:37:47 +00:00
}
2019-06-27 19:08:08 +00:00
if *NOT {
if execute {
execute = false
} else {
execute = true
}
}
if execute {
2019-06-27 18:49:34 +00:00
Ok("I have nothing to do, i going to sleep")
2019-06-27 18:37:47 +00:00
}
command := strings.Split(*COMMAND, " ")
syscall.Exec(command[0], command, []string{})
}