//Init ializes the configuration func Init(configfile string) { var configContent []byte var tempContent []byte var err error tempContent, err = ioutil.ReadFile(configfile) if err == nil { configContent = tempContent } else { tempContent, err = ioutil.ReadFile("config.yaml") if err == nil { configContent = tempContent } else { panic("Not found in folder! Panic!") } } m := Configuration{} err = yaml.Unmarshal(configContent, &m) errUnmarshal := yaml.Unmarshal(configContent, &C) if errUnmarshal != nil { log.Error("Cannot load configuration! Make sure the configuration file matches your version of monitoring.") panic(errUnmarshal.Error()) } name, err := os.Hostname() if err != nil { panic(err) } else { C.Hostname = name } if len(C.Actions.Telegram.Target) > 2 { log.Notice("Telegram enabled.") C.Actions.Telegram.Enabled = true } else { log.Error("Telegram is disabled.") } IsLoaded = true log.Notice("Services: ", C.Paths.Services) log.Notice("Checks: ", C.Paths.Checks) }
func init() { log.Notice("Initializing..") flag.BoolVar(&debug, "debug", false, "Enable debugging") flag.BoolVar(&testConfig, "test", false, "Test configuration instead of running") flag.BoolVar(&apiEnabled, "api", true, "Enable Web API") flag.BoolVar(&autoStart, "autostart", true, "Autostart service checking") flag.BoolVar(&noActionHandling, "no-action-handling", false, "Do not do anything when services are down") flag.StringVar(&config, "config", "/etc/monitoring/config.yaml", "Path to config file") flag.Parse() }
func readServiceFiles(searchDir string) []model.Service { findingList := []string{} var allServices []model.Service err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error { findingList = append(findingList, path) if strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml") { log.Notice("Loaded ", path) allServices = append(allServices, servicesBuilder(path)...) } return nil }) if err != nil { panic(err) } return allServices }
//Handle dispatches the correct action handling func Handle(service model.Service) { if configuration.C.NoActionHandling == false { if service.Acknowledged != true { switch service.Action.Name { case "telegram": handleTelegram(service) case "none": log.Notice("Skipping action for ", service.Identifier) default: handleTelegram(service) } } } else { fmt.Println("Silenced.") } }
//Setup initializes routers, login and services. func Setup() { if configuration.Debug { gin.SetMode(gin.DebugMode) } else { gin.SetMode(gin.ReleaseMode) } r := gin.New() r.Use(cors.Middleware(cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE", RequestHeaders: "Origin, Authorization, Content-Type", ExposedHeaders: "", MaxAge: 50 * time.Second, Credentials: true, ValidateHeaders: false, })) r.SetHTMLTemplate(pages.Template) r.GET("/", pages.Homepage) serviceGroup := r.Group("/api/", AuthRequired()) { serviceGroup.GET("/services/:identifier/update", services.Update) serviceGroup.GET("/services/:identifier/reschedule", services.Reschedule) serviceGroup.GET("/services/:identifier", services.Show) serviceGroup.GET("/services", services.List) } systemAPI := r.Group("/api/system/", AuthRequired()) { systemAPI.GET("/start", system.Start) systemAPI.GET("/stop", system.Stop) systemAPI.GET("/reload", system.Reload) } log.Notice("Starting webserver..") log.Info("API listening on http://" + configuration.C.API.Address) r.Run(configuration.C.API.Address) }
//Start daemon's checking func Start() { log.Notice("Starting..") IsActive = true }
//Execute a command by specifying executable and arguments, returns statuscode and output summary func Execute(timeout int, cmdName string, cmdArgs ...string) (status int, output string) { // TODO: Check if cmdName file exists cmd := exec.Command(cmdName, cmdArgs...) cmdOutput := &bytes.Buffer{} errOutput := &bytes.Buffer{} fail := false killed := false cmd.Stdout = cmdOutput cmd.Stderr = errOutput var waitStatus syscall.WaitStatus cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Start() timer := time.AfterFunc(time.Duration(timeout+1)*time.Second, func() { if cmd.Process != nil { pgid, err := syscall.Getpgid(cmd.Process.Pid) if err == nil { syscall.Kill(-pgid, 9) // note the minus sign log.Notice("Killed PID", pgid, "because of timeout of ", timeout, "seconds while running", cmdName) killed = true } } else { log.Error("Tried to kill but it didn't exist (anymore).", cmdName, cmdArgs) } }) if err := cmd.Wait(); err != nil { if err != nil { fail = true } if exitError, ok := err.(*exec.ExitError); ok { waitStatus = exitError.Sys().(syscall.WaitStatus) } } else { // Success waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus) } if killed { return killedStatus() } timer.Stop() outputString := string(cmdOutput.Bytes()) shortOutputStrings := strings.Split(outputString, "\n") statusCode := waitStatus.ExitStatus() if waitStatus.ExitStatus() == -1 { return killedStatus() } if waitStatus.ExitStatus() == 0 && fail { statusCode = 420 } return statusCode, shortOutputStrings[0] }