From ca4b78760f08c72242db02590ce3c4a62d2d320e Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 14:03:20 +0200 Subject: [PATCH 1/6] nagios integration: Code formatting cleanup (go fmt/goimports) --- nagios/nagios/nagios2opsgenie.go | 213 +++++++++++++++---------------- 1 file changed, 105 insertions(+), 108 deletions(-) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index 1df9114..ec847d0 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -1,58 +1,60 @@ package main import ( + "bufio" "bytes" + "crypto/tls" "encoding/json" "flag" - "net/http" + "fmt" + "io" + "io/ioutil" "net" - "time" + "net/http" + "net/url" "os" - "bufio" - "strings" - "io" "strconv" - "github.com/alexcesaro/log/golog" + "strings" + "time" + "github.com/alexcesaro/log" - "fmt" - "io/ioutil" - "crypto/tls" - "net/url" + "github.com/alexcesaro/log/golog" ) var NAGIOS_SERVER = "default" var API_KEY = "" var TOTAL_TIME = 60 -var configParameters = map[string]string{"apiKey": API_KEY, - "nagios_server": NAGIOS_SERVER, - "nagios2opsgenie.logger":"warning", - "opsgenie.api.url":"https://api.opsgenie.com" , - "nagios2opsgenie.http.proxy.enabled" : "false", - "nagios2opsgenie.http.proxy.port" : "1111", - "nagios2opsgenie.http.proxy.host": "localhost", - "nagios2opsgenie.http.proxy.protocol":"http", +var configParameters = map[string]string{ + "apiKey": API_KEY, + "nagios_server": NAGIOS_SERVER, + "nagios2opsgenie.logger": "warning", + "opsgenie.api.url": "https://api.opsgenie.com", + "nagios2opsgenie.http.proxy.enabled": "false", + "nagios2opsgenie.http.proxy.port": "1111", + "nagios2opsgenie.http.proxy.host": "localhost", + "nagios2opsgenie.http.proxy.protocol": "http", "nagios2opsgenie.http.proxy.username": "", "nagios2opsgenie.http.proxy.password": ""} var parameters = make(map[string]string) var configPath = "/etc/opsgenie/conf/opsgenie-integration.conf" -var levels = map [string]log.Level{"info":log.Info,"debug":log.Debug,"warning":log.Warning,"error":log.Error} +var levels = map[string]log.Level{"info": log.Info, "debug": log.Debug, "warning": log.Warning, "error": log.Error} var logger log.Logger func main() { configFile, err := os.Open(configPath) - if err == nil{ + if err == nil { readConfigFile(configFile) - }else{ + } else { panic(err) } - version := flag.String("v","","") + version := flag.String("v", "", "") parseFlags() logger = configureLogger() printConfigToLog() - if *version != ""{ + if *version != "" { fmt.Println("Version: 1.1") return } @@ -68,9 +70,9 @@ func main() { http_post() } -func printConfigToLog(){ +func printConfigToLog() { if logger != nil { - if (logger.LogDebug()) { + if logger.LogDebug() { logger.Debug("Config:") for k, v := range configParameters { if strings.Contains(k, "password") { @@ -83,19 +85,19 @@ func printConfigToLog(){ } } -func readConfigFile(file io.Reader){ +func readConfigFile(file io.Reader) { scanner := bufio.NewScanner(file) - for scanner.Scan(){ + for scanner.Scan() { line := scanner.Text() line = strings.TrimSpace(line) - if !strings.HasPrefix(line,"#") && line != "" { - l := strings.SplitN(line,"=",2) + if !strings.HasPrefix(line, "#") && line != "" { + l := strings.SplitN(line, "=", 2) l[0] = strings.TrimSpace(l[0]) l[1] = strings.TrimSpace(l[1]) - configParameters[l[0]]=l[1] - if l[0] == "nagios2opsgenie.timeout"{ - TOTAL_TIME,_ = strconv.Atoi(l[1]) + configParameters[l[0]] = l[1] + if l[0] == "nagios2opsgenie.timeout" { + TOTAL_TIME, _ = strconv.Atoi(l[1]) } } } @@ -104,7 +106,7 @@ func readConfigFile(file io.Reader){ } } -func configureLogger ()log.Logger{ +func configureLogger() log.Logger { level := configParameters["nagios2opsgenie.logger"] var logFilePath = parameters["logPath"] @@ -117,9 +119,9 @@ func configureLogger ()log.Logger{ file, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { - fmt.Println("Could not create log file \"" + logFilePath + "\", will log to \"/tmp/nagios2opsgenie.log\" file. Error: ", err) + fmt.Println("Could not create log file \""+logFilePath+"\", will log to \"/tmp/nagios2opsgenie.log\" file. Error: ", err) - fileTmp, errTmp := os.OpenFile("/tmp/nagios2opsgenie.log", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666) + fileTmp, errTmp := os.OpenFile("/tmp/nagios2opsgenie.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if errTmp != nil { fmt.Println("Logging disabled. Reason: ", errTmp) @@ -133,7 +135,7 @@ func configureLogger ()log.Logger{ return tmpLogger } -func getHttpClient (timeout int) *http.Client { +func getHttpClient(timeout int) *http.Client { seconds := (TOTAL_TIME / 12) * 2 * timeout var proxyEnabled = configParameters["nagios2opsgenie.http.proxy.enabled"] var proxyHost = configParameters["nagios2opsgenie.http.proxy.host"] @@ -143,14 +145,13 @@ func getHttpClient (timeout int) *http.Client { var proxyPassword = configParameters["nagios2opsgenie.http.proxy.password"] proxy := http.ProxyFromEnvironment - if proxyEnabled == "true" { u := new(url.URL) u.Scheme = scheme - u.Host = proxyHost + ":" + proxyPort + u.Host = proxyHost + ":" + proxyPort if len(proxyUsername) > 0 { - u.User = url.UserPassword(proxyUsername,proxyPassword) + u.User = url.UserPassword(proxyUsername, proxyPassword) } if logger != nil { @@ -160,10 +161,10 @@ func getHttpClient (timeout int) *http.Client { } client := &http.Client{ Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify : true}, - Proxy: proxy, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: proxy, Dial: func(netw, addr string) (net.Conn, error) { - conn, err := net.DialTimeout(netw, addr, time.Second * time.Duration(seconds)) + conn, err := net.DialTimeout(netw, addr, time.Second*time.Duration(seconds)) if err != nil { if logger != nil { logger.Error("Error occurred while connecting: ", err) @@ -178,23 +179,23 @@ func getHttpClient (timeout int) *http.Client { return client } -func http_post() { +func http_post() { var logPrefix = "" - if parameters["entity_type"] == "host"{ - logPrefix = "[HostName: "+ parameters["host_name"] + ", HostState: "+ parameters["host_state"] +"]" - }else{ - logPrefix = "[HostName: "+ parameters["host_name"] + ", ServiceDesc: "+ parameters["service_desc"] + ", ServiceState: " + parameters["service_state"] +"]" + if parameters["entity_type"] == "host" { + logPrefix = "[HostName: " + parameters["host_name"] + ", HostState: " + parameters["host_state"] + "]" + } else { + logPrefix = "[HostName: " + parameters["host_name"] + ", ServiceDesc: " + parameters["service_desc"] + ", ServiceState: " + parameters["service_state"] + "]" } apiUrl := configParameters["opsgenie.api.url"] + "/v1/json/nagios" viaMaridUrl := configParameters["viaMaridUrl"] target := "" - if viaMaridUrl != ""{ + if viaMaridUrl != "" { apiUrl = viaMaridUrl target = "Marid" - }else{ + } else { target = "OpsGenie" } @@ -211,52 +212,53 @@ func http_post() { client := getHttpClient(i) if logger != nil { - logger.Debug(logPrefix + "Trying to send data to OpsGenie with timeout: ", (TOTAL_TIME / 12) * 2 * i) + logger.Debug(logPrefix+"Trying to send data to OpsGenie with timeout: ", (TOTAL_TIME/12)*2*i) } resp, error := client.Do(request) if error == nil { defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) - if err == nil{ - if resp.StatusCode == 200{ + if err == nil { + if resp.StatusCode == 200 { if logger != nil { logger.Debug(logPrefix + " Response code: " + strconv.Itoa(resp.StatusCode)) logger.Debug(logPrefix + "Response: " + string(body[:])) - logger.Info(logPrefix + "Data from Nagios posted to " + target + " successfully") } - }else{ + logger.Info(logPrefix + "Data from Nagios posted to " + target + " successfully") + } + } else { if logger != nil { logger.Error(logPrefix + "Couldn't post data from Nagios to " + target + " successfully; Response code: " + strconv.Itoa(resp.StatusCode) + " Response Body: " + string(body[:])) } } - }else{ + } else { if logger != nil { - logger.Error(logPrefix + "Couldn't read the response from " + target, err) + logger.Error(logPrefix+"Couldn't read the response from "+target, err) } } break - }else if i < 3 { + } else if i < 3 { if logger != nil { - logger.Error(logPrefix + "Error occurred while sending data, will retry.", error) + logger.Error(logPrefix+"Error occurred while sending data, will retry.", error) } - }else { + } else { if logger != nil { - logger.Error(logPrefix + "Failed to post data from Nagios. ", error) + logger.Error(logPrefix+"Failed to post data from Nagios. ", error) } } - if resp != nil{ + if resp != nil { defer resp.Body.Close() } } } -func parseFlags()map[string]string{ - apiKey := flag.String("apiKey","","api key") - nagiosServer := flag.String("ns","","nagios server") +func parseFlags() map[string]string { + apiKey := flag.String("apiKey", "", "api key") + nagiosServer := flag.String("ns", "", "nagios server") - entityType := flag.String("entityType","","") + entityType := flag.String("entityType", "", "") - notificationType := flag.String("t", "","NOTIFICATIONTYPE") + notificationType := flag.String("t", "", "NOTIFICATIONTYPE") longDateTime := flag.String("ldt", "", "LONGDATETIME") hostName := flag.String("hn", "", "HOSTNAME") @@ -265,21 +267,21 @@ func parseFlags()map[string]string{ hostAddress := flag.String("haddr", "", "HOSTADDRESS") hostState := flag.String("hs", "", "HOSTSTATE") hostStateId := flag.String("hsi", "", "HOSTSTATEID") - lastHostState := flag.String("lhs","","LASTHOSTSTATE") - lastHostStateId := flag.String("lhsi","","LASTHOSTSTATEID") - hostStateType := flag.String("hst","","HOSTSTATETYPE") + lastHostState := flag.String("lhs", "", "LASTHOSTSTATE") + lastHostStateId := flag.String("lhsi", "", "LASTHOSTSTATEID") + hostStateType := flag.String("hst", "", "HOSTSTATETYPE") hostAttempt := flag.String("ha", "", "HOSTATTEMPT") maxHostAttempts := flag.String("mha", "", "MAXHOSTATTEMPTS") - hostEventId := flag.String("hei","","HOSTEVENTID") - lastHostEventId := flag.String("lhei","","LASTHOSTEVENTID") - hostProblemId := flag.String("hpi","","HOSTPROBLEMID") - lastHostProblemId := flag.String("lhpi","","LASTHOSTPROBLEMID") + hostEventId := flag.String("hei", "", "HOSTEVENTID") + lastHostEventId := flag.String("lhei", "", "LASTHOSTEVENTID") + hostProblemId := flag.String("hpi", "", "HOSTPROBLEMID") + lastHostProblemId := flag.String("lhpi", "", "LASTHOSTPROBLEMID") hostLatency := flag.String("hl", "", "HOSTLATENCY") - hostExecutionTime := flag.String ("het","","HOSTEXECUTIONTIME") + hostExecutionTime := flag.String("het", "", "HOSTEXECUTIONTIME") hostDuration := flag.String("hd", "", "HOSTDURATION") hostDurationSec := flag.String("hds", "", "HOSTDURATIONSEC") - hostDownTime := flag.String("hdt","","HOSTDOWNTIME") - hostPercentChange := flag.String("hpc","","HOSTPERCENTCHANGE") + hostDownTime := flag.String("hdt", "", "HOSTDOWNTIME") + hostPercentChange := flag.String("hpc", "", "HOSTPERCENTCHANGE") hostGroupName := flag.String("hgn", "", "HOSTGROUPNAME") hostGroupNames := flag.String("hgns", "", "HOSTGROUPNAMES") lastHostCheck := flag.String("lhc", "", "LASTHOSTCHECK") @@ -293,7 +295,7 @@ func parseFlags()map[string]string{ hostPerfData := flag.String("hpd", "", "HOSTPERFDATA") serviceDesc := flag.String("s", "", "SERVICEDESC") - serviceDisplayName := flag.String("sdn","","SERVICEDISPLAYNAME") + serviceDisplayName := flag.String("sdn", "", "SERVICEDISPLAYNAME") serviceState := flag.String("ss", "", "SERVICESTATE") serviceStateId := flag.String("ssi", "", "SERVICESTATEID") lastServiceState := flag.String("lss", "", "LASTSERVICESTATE") @@ -301,57 +303,57 @@ func parseFlags()map[string]string{ serviceStateType := flag.String("sst", "", "SERVICESTATETYPE") serviceAttempt := flag.String("sa", "", "SERVICEATTEMPT") maxServiceAttempts := flag.String("msa", "", "MAXSERVICEATTEMPTS") - serviceIsVolatile := flag.String("siv","","SERVICEISVOLATILE") - serviceEventId := flag.String("sei","","SERVICEEVENTID") - lastServiceEventId := flag.String("lsei","","LASTSERVICEEVENTID") - serviceProblemId := flag.String("spi","","SERVICEPROBLEMID") - lastServiceProblemId := flag.String("lspi","","LASTSERVICEPROBLEMID") + serviceIsVolatile := flag.String("siv", "", "SERVICEISVOLATILE") + serviceEventId := flag.String("sei", "", "SERVICEEVENTID") + lastServiceEventId := flag.String("lsei", "", "LASTSERVICEEVENTID") + serviceProblemId := flag.String("spi", "", "SERVICEPROBLEMID") + lastServiceProblemId := flag.String("lspi", "", "LASTSERVICEPROBLEMID") serviceLatency := flag.String("sl", "", "SERVICELATENCY") - serviceExecutionTime := flag.String("set","","SERVICEEXECUTIONTIME") + serviceExecutionTime := flag.String("set", "", "SERVICEEXECUTIONTIME") serviceDuration := flag.String("sd", "", "SERVICEDURATION") serviceDurationSec := flag.String("sds", "", "SERVICEDURATIONSEC") - serviceDownTime := flag.String("sdt","","SERVICEDOWNTIME") - servicePercentChange := flag.String("spc","","SERVICEPERCENTCHANGE") + serviceDownTime := flag.String("sdt", "", "SERVICEDOWNTIME") + servicePercentChange := flag.String("spc", "", "SERVICEPERCENTCHANGE") serviceGroupName := flag.String("sgn", "", "SERVICEGROUPNAME") serviceGroupNames := flag.String("sgns", "", "SERVICEGROUPNAMES") lastServiceCheck := flag.String("lsch", "", "LASTSERVICECHECK") lastServiceStateChange := flag.String("lssc", "", "LASTSERVICESTATECHANGE") - lastServiceOk := flag.String("lsok","","LASTSERVICEOK") - lastServiceWarning := flag.String("lsw","","LASTSERVICEWARNING") - lastServiceUnknown := flag.String("lsu","","LASTSERVICEUNKNOWN") - lastServiceCritical := flag.String("lsc","","LASTSERVICECRITICAL") + lastServiceOk := flag.String("lsok", "", "LASTSERVICEOK") + lastServiceWarning := flag.String("lsw", "", "LASTSERVICEWARNING") + lastServiceUnknown := flag.String("lsu", "", "LASTSERVICEUNKNOWN") + lastServiceCritical := flag.String("lsc", "", "LASTSERVICECRITICAL") serviceOutput := flag.String("so", "", "SERVICEOUTPUT") longServiceOutput := flag.String("lso", "", "LONGSERVICEOUTPUT") serviceNotesUrl := flag.String("snu", "", "SERVICENOTESURL") servicePerfData := flag.String("spd", "", "SERVICEPERFDATA") logPath := flag.String("logPath", "", "LOGPATH") - responders := flag.String("responders","","Responders") - tags := flag.String("tags","","Tags") + responders := flag.String("responders", "", "Responders") + tags := flag.String("tags", "", "Tags") flag.Parse() - if *apiKey != ""{ + if *apiKey != "" { parameters["apiKey"] = *apiKey - }else{ - parameters["apiKey"] = configParameters ["apiKey"] + } else { + parameters["apiKey"] = configParameters["apiKey"] } - if *nagiosServer != ""{ + if *nagiosServer != "" { parameters["nagios_server"] = *nagiosServer - }else{ + } else { parameters["nagios_server"] = configParameters["nagios_server"] } - if *responders != ""{ + if *responders != "" { parameters["responders"] = *responders - }else{ - parameters["responders"] = configParameters ["responders"] + } else { + parameters["responders"] = configParameters["responders"] } - if *tags != ""{ + if *tags != "" { parameters["tags"] = *tags - }else{ - parameters["tags"] = configParameters ["tags"] + } else { + parameters["tags"] = configParameters["tags"] } if *logPath != "" { @@ -433,7 +435,7 @@ func parseFlags()map[string]string{ args := flag.Args() for i := 0; i < len(args); i += 2 { - if(len(args)%2 != 0 && i==len(args)-1){ + if len(args)%2 != 0 && i == len(args)-1 { parameters[args[i]] = "" } else { parameters[args[i]] = args[i+1] @@ -442,8 +444,3 @@ func parseFlags()map[string]string{ return parameters } - - - - - From 55d5fa5290c74eb52206f1999bac44026b5e1728 Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 15:18:55 +0200 Subject: [PATCH 2/6] nagios integration: Restructure flag parsing, config reading and logging setup This to allow flag parsing to log errors while validating arguments and to have a new "-c " option to specify non-default config file to use. --- nagios/nagios/nagios2opsgenie.go | 60 ++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index ec847d0..c497c1d 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -21,6 +21,7 @@ import ( "github.com/alexcesaro/log/golog" ) +var VERSION = "1.1" var NAGIOS_SERVER = "default" var API_KEY = "" var TOTAL_TIME = 60 @@ -41,23 +42,7 @@ var levels = map[string]log.Level{"info": log.Info, "debug": log.Debug, "warning var logger log.Logger func main() { - configFile, err := os.Open(configPath) - if err == nil { - readConfigFile(configFile) - } else { - panic(err) - } - - version := flag.String("v", "", "") - parseFlags() - - logger = configureLogger() - printConfigToLog() - - if *version != "" { - fmt.Println("Version: 1.1") - return - } + parseFlags_readConfig_setupLogging() if parameters["notification_type"] == "" { if logger != nil { @@ -252,7 +237,10 @@ func http_post() { } } -func parseFlags() map[string]string { +func parseFlags_readConfig_setupLogging() { + version := flag.String("v", "", "") + configfile := flag.String("c", "", "Configuration file") + apiKey := flag.String("apiKey", "", "api key") nagiosServer := flag.String("ns", "", "nagios server") @@ -333,6 +321,34 @@ func parseFlags() map[string]string { flag.Parse() + if *version != "" { + fmt.Println("Version:", VERSION) + os.Exit(1) + } + + // Need config file parsed before setting up logging + if *configfile != "" { // Override default configfile based on commandline + configPath = *configfile + } + configFile, err := os.Open(configPath) + if err == nil { + readConfigFile(configFile) + } else { + panic(err) + } + + // Logging related commandline options + if *logPath != "" { + parameters["logPath"] = *logPath + } else { + parameters["logPath"] = configParameters["logPath"] + } + + // Logging needed to be setup before parsing further command line options below that could have errors to report + logger = configureLogger() + printConfigToLog() + + // Handle the remaining options from commandline and/or configuration file if *apiKey != "" { parameters["apiKey"] = *apiKey } else { @@ -356,12 +372,6 @@ func parseFlags() map[string]string { parameters["tags"] = configParameters["tags"] } - if *logPath != "" { - parameters["logPath"] = *logPath - } else { - parameters["logPath"] = configParameters["logPath"] - } - parameters["entity_type"] = *entityType parameters["notification_type"] = *notificationType @@ -441,6 +451,4 @@ func parseFlags() map[string]string { parameters[args[i]] = args[i+1] } } - - return parameters } From bbc3f9bab1bba9b02856c54d11e8d4656ab3b0d4 Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 15:23:39 +0200 Subject: [PATCH 3/6] nagios integration: Support setting "priority" Based on similar pull request for Iciniga 2 integration by tobiasvdk: https://github.com/opsgenie/opsgenie-integration/pull/53 (not sure if it wouldn't be better to fail than only log if validation of specified priority fails) --- nagios/nagios/nagios2opsgenie.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index c497c1d..010504f 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -318,6 +318,7 @@ func parseFlags_readConfig_setupLogging() { responders := flag.String("responders", "", "Responders") tags := flag.String("tags", "", "Tags") + priority := flag.String("priority", "", "Priority (P1...P5)") flag.Parse() @@ -372,6 +373,15 @@ func parseFlags_readConfig_setupLogging() { parameters["tags"] = configParameters["tags"] } + if *priority == "" { + parameters["priority"] = "" + } else if IsValidPriority(*priority) { + parameters["priority"] = *priority + } else { + logger.Warning("Priority is not valid, needs to be one of P1, P2, P3, P4, P5.") + parameters["priority"] = "" + } + parameters["entity_type"] = *entityType parameters["notification_type"] = *notificationType @@ -452,3 +462,16 @@ func parseFlags_readConfig_setupLogging() { } } } + +func IsValidPriority(priority string) bool { + switch priority { + case + "P1", + "P2", + "P3", + "P4", + "P5": + return true + } + return false +} From f3bebce1ad3e736e7f8f6575fa8db213ba29139c Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 15:32:00 +0200 Subject: [PATCH 4/6] nagios integration: Cleaner logging and formatting --- nagios/nagios/nagios2opsgenie.go | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index 010504f..50e304a 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -46,7 +46,7 @@ func main() { if parameters["notification_type"] == "" { if logger != nil { - logger.Warning("Stopping, Nagios NOTIFICATIONTYPE param has no value, please make sure your Nagios and OpsGenie files pass necessary parameters") + logger.Error("Stopping, Nagios NOTIFICATIONTYPE param has no value, please make sure your Nagios and OpsGenie files pass necessary parameters") } return @@ -186,8 +186,7 @@ func http_post() { if logger != nil { logger.Debug("URL: ", apiUrl) - logger.Debug("Data to be posted:") - logger.Debug(parameters) + logger.Debug("Data to be posted:", parameters) } var buf, _ = json.Marshal(parameters) @@ -197,7 +196,7 @@ func http_post() { client := getHttpClient(i) if logger != nil { - logger.Debug(logPrefix+"Trying to send data to OpsGenie with timeout: ", (TOTAL_TIME/12)*2*i) + logger.Debug(logPrefix+" Trying to send data to OpsGenie with timeout: ", (TOTAL_TIME/12)*2*i) } resp, error := client.Do(request) @@ -207,28 +206,27 @@ func http_post() { if err == nil { if resp.StatusCode == 200 { if logger != nil { - logger.Debug(logPrefix + " Response code: " + strconv.Itoa(resp.StatusCode)) - logger.Debug(logPrefix + "Response: " + string(body[:])) - logger.Info(logPrefix + "Data from Nagios posted to " + target + " successfully") + logger.Debug(logPrefix + " Response code: " + strconv.Itoa(resp.StatusCode) + ", Response Body: " + string(body[:])) + logger.Info(logPrefix + " Data from Nagios posted to " + target + " successfully") } } else { if logger != nil { - logger.Error(logPrefix + "Couldn't post data from Nagios to " + target + " successfully; Response code: " + strconv.Itoa(resp.StatusCode) + " Response Body: " + string(body[:])) + logger.Error(logPrefix + " Couldn't post data from Nagios to " + target + "; Response code: " + strconv.Itoa(resp.StatusCode) + ", Response Body: " + string(body[:])) } } } else { if logger != nil { - logger.Error(logPrefix+"Couldn't read the response from "+target, err) + logger.Error(logPrefix+" Couldn't read the response from "+target, err) } } break } else if i < 3 { if logger != nil { - logger.Error(logPrefix+"Error occurred while sending data, will retry.", error) + logger.Error(logPrefix+" Error occurred while sending data, will retry.", error) } } else { if logger != nil { - logger.Error(logPrefix+"Failed to post data from Nagios. ", error) + logger.Error(logPrefix+" Failed to post data from Nagios.", error) } } if resp != nil { From 0055a395f76b67c263ee332ca4e77aaf75e591f5 Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 15:38:21 +0200 Subject: [PATCH 5/6] nagios integration: Log invocation and arguments to better understand errors Without that context, the final "Data from Nagios posted to OpsGenie successful/failed" is quite meaningless. --- nagios/nagios/nagios2opsgenie.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index 50e304a..6a60922 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -318,6 +318,7 @@ func parseFlags_readConfig_setupLogging() { tags := flag.String("tags", "", "Tags") priority := flag.String("priority", "", "Priority (P1...P5)") + saved_args := os.Args // save the arguments for logging once it is initialized flag.Parse() if *version != "" { @@ -345,6 +346,7 @@ func parseFlags_readConfig_setupLogging() { // Logging needed to be setup before parsing further command line options below that could have errors to report logger = configureLogger() + logger.Info("Invocation:", saved_args[0], `"`+strings.Join(saved_args[1:], `" "`)+`"`) printConfigToLog() // Handle the remaining options from commandline and/or configuration file From 3c8ea118df26d4c20b9cba8a73b558086729dd32 Mon Sep 17 00:00:00 2001 From: Roland Alder Date: Wed, 30 Mar 2022 15:52:43 +0200 Subject: [PATCH 6/6] nagios integration: Use real hostname and not "default" as default Allow override in config file and an commandline. --- nagios/nagios/nagios2opsgenie.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/nagios/nagios/nagios2opsgenie.go b/nagios/nagios/nagios2opsgenie.go index 6a60922..ef19934 100644 --- a/nagios/nagios/nagios2opsgenie.go +++ b/nagios/nagios/nagios2opsgenie.go @@ -22,12 +22,11 @@ import ( ) var VERSION = "1.1" -var NAGIOS_SERVER = "default" var API_KEY = "" var TOTAL_TIME = 60 var configParameters = map[string]string{ "apiKey": API_KEY, - "nagios_server": NAGIOS_SERVER, + "nagios_server": "", "nagios2opsgenie.logger": "warning", "opsgenie.api.url": "https://api.opsgenie.com", "nagios2opsgenie.http.proxy.enabled": "false", @@ -355,10 +354,16 @@ func parseFlags_readConfig_setupLogging() { } else { parameters["apiKey"] = configParameters["apiKey"] } + // Nagios servername precedence: command line > config file > os.Hostname if *nagiosServer != "" { parameters["nagios_server"] = *nagiosServer - } else { + } else if configParameters["nagios_server"] != "" { parameters["nagios_server"] = configParameters["nagios_server"] + } else { + thisServerHostname, err := os.Hostname() + if err == nil { + parameters["nagios_server"] = thisServerHostname + } } if *responders != "" {