first version
This commit is contained in:
parent
d675cfa80a
commit
9db472a1fc
1 changed files with 103 additions and 0 deletions
103
is_master.go
Normal file
103
is_master.go
Normal file
|
@ -0,0 +1,103 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"flag"
|
||||
"os"
|
||||
"syscall"
|
||||
"strings"
|
||||
"net"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Option to parse
|
||||
var (
|
||||
HELP = flag.Bool("help", false, "print the help message")
|
||||
IP = flag.String("ip", "", "")
|
||||
FILE = flag.String("file", "", "")
|
||||
COMMAND = flag.String("command", "", "command to execute")
|
||||
)
|
||||
|
||||
// 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() {
|
||||
var isMaster bool
|
||||
|
||||
if *FILE != "" {
|
||||
isMaster = fileExist(*FILE)
|
||||
} else {
|
||||
isMaster = ipExist(*IP)
|
||||
}
|
||||
|
||||
if isMaster == false {
|
||||
Ok("OK - I am slave, i going to sleep")
|
||||
}
|
||||
|
||||
command := strings.Split(*COMMAND, " ")
|
||||
syscall.Exec(command[0], command, []string{})
|
||||
}
|
Loading…
Reference in a new issue