diff --git a/icinga2/icinga2/icinga2opsgenie.go b/icinga2/icinga2/icinga2opsgenie.go index f29c743..cfd85de 100644 --- a/icinga2/icinga2/icinga2opsgenie.go +++ b/icinga2/icinga2/icinga2opsgenie.go @@ -1,59 +1,59 @@ package main import ( + "bufio" "bytes" + "crypto/tls" "encoding/json" "flag" - "net/http" - "net" - "time" - "os" - "bufio" - "strings" - "io" - "strconv" - "github.com/alexcesaro/log/golog" - "github.com/alexcesaro/log" "fmt" + "github.com/alexcesaro/log" + "github.com/alexcesaro/log/golog" + "io" "io/ioutil" - "crypto/tls" + "net" + "net/http" "net/url" + "os" + "strconv" + "strings" + "time" ) var ICINGA_SERVER = "default" var API_KEY = "" var TOTAL_TIME = 60 var configParameters = map[string]string{"apiKey": API_KEY, - "icinga_server": ICINGA_SERVER, - "icinga2opsgenie.logger":"warning", - "opsgenie.api.url":"https://api.opsgenie.com", - "icinga2opsgenie.http.proxy.enabled" : "false", - "icinga2opsgenie.http.proxy.port" : "1111", - "icinga2opsgenie.http.proxy.host": "localhost", - "icinga2opsgenie.http.proxy.protocol":"http", + "icinga_server": ICINGA_SERVER, + "icinga2opsgenie.logger": "warning", + "opsgenie.api.url": "https://api.opsgenie.com", + "icinga2opsgenie.http.proxy.enabled": "false", + "icinga2opsgenie.http.proxy.port": "1111", + "icinga2opsgenie.http.proxy.host": "localhost", + "icinga2opsgenie.http.proxy.protocol": "http", "icinga2opsgenie.http.proxy.username": "", "icinga2opsgenie.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() { + logger = configureLogger() 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 +68,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 +83,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] == "icinga2opsgenie.timeout"{ - TOTAL_TIME,_ = strconv.Atoi(l[1]) + configParameters[l[0]] = l[1] + if l[0] == "icinga2opsgenie.timeout" { + TOTAL_TIME, _ = strconv.Atoi(l[1]) } } } @@ -104,7 +104,7 @@ func readConfigFile(file io.Reader){ } } -func configureLogger ()log.Logger{ +func configureLogger() log.Logger { level := configParameters["icinga2opsgenie.logger"] var logFilePath = parameters["logPath"] @@ -117,9 +117,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/icinga2opsgenie.log\" file. Error: ", err) + fmt.Println("Could not create log file \""+logFilePath+"\", will log to \"/tmp/icinga2opsgenie.log\" file. Error: ", err) - fileTmp, errTmp := os.OpenFile("/tmp/icinga2opsgenie.log", os.O_CREATE | os.O_WRONLY | os.O_APPEND, 0666) + fileTmp, errTmp := os.OpenFile("/tmp/icinga2opsgenie.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if errTmp != nil { fmt.Println("Logging disabled. Reason: ", errTmp) @@ -133,8 +133,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["icinga2opsgenie.http.proxy.enabled"] var proxyHost = configParameters["icinga2opsgenie.http.proxy.host"] @@ -145,14 +144,13 @@ func getHttpClient (timeout int) *http.Client { 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 { @@ -163,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) @@ -181,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/icinga2" viaMaridUrl := configParameters["viaMaridUrl"] target := "" - if viaMaridUrl != ""{ + if viaMaridUrl != "" { apiUrl = viaMaridUrl target = "Marid" - }else{ + } else { target = "OpsGenie" } @@ -214,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 Icinga posted to " + target + " successfully") } - }else{ + logger.Info(logPrefix + "Data from Icinga posted to " + target + " successfully") + } + } else { if logger != nil { logger.Error(logPrefix + "Couldn't post data from Icinga 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 Icinga to " + target, error) + logger.Error(logPrefix+"Failed to post data from Icinga to "+target, error) } } - if resp != nil{ + if resp != nil { defer resp.Body.Close() } } } -func parseFlags()map[string]string{ - apiKey := flag.String("apiKey","","api key") - icingaServer := flag.String("is","","icinga server") +func parseFlags() map[string]string { + apiKey := flag.String("apiKey", "", "api key") + icingaServer := flag.String("is", "", "icinga 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") @@ -268,16 +267,16 @@ 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") hostLatency := flag.String("hl", "", "HOSTLATENCY") - hostExecutionTime := flag.String ("het","","HOSTEXECUTIONTIME") + hostExecutionTime := flag.String("het", "", "HOSTEXECUTIONTIME") hostDurationSec := flag.String("hds", "", "HOSTDURATIONSEC") - hostDownTime := flag.String("hdt","","HOSTDOWNTIMEDEPTH") - hostPercentChange := flag.String("hpc","","HOSTPERCENTCHANGE") + hostDownTime := flag.String("hdt", "", "HOSTDOWNTIMEDEPTH") + hostPercentChange := flag.String("hpc", "", "HOSTPERCENTCHANGE") hostGroupName := flag.String("hgn", "", "HOSTGROUPNAME") hostGroupNames := flag.String("hgns", "", "HOSTGROUPNAMES") lastHostCheck := flag.String("lhc", "", "LASTHOSTCHECK") @@ -286,7 +285,7 @@ func parseFlags()map[string]string{ hostPerfData := flag.String("hpd", "", "HOSTPERFDATA") serviceDesc := flag.String("s", "", "SERVICENAME") - 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") @@ -295,9 +294,9 @@ func parseFlags()map[string]string{ serviceAttempt := flag.String("sa", "", "SERVICEATTEMPT") maxServiceAttempts := flag.String("msa", "", "MAXSERVICEATTEMPTS") serviceLatency := flag.String("sl", "", "SERVICELATENCY") - serviceExecutionTime := flag.String("set","","SERVICEEXECUTIONTIME") + serviceExecutionTime := flag.String("set", "", "SERVICEEXECUTIONTIME") serviceDurationSec := flag.String("sds", "", "SERVICEDURATIONSEC") - serviceDownTime := flag.String("sdt","","SERVICEDOWNTIMEDEPTH") + serviceDownTime := flag.String("sdt", "", "SERVICEDOWNTIMEDEPTH") serviceGroupNames := flag.String("sgns", "", "SERVICEGROUPNAMES") lastServiceCheck := flag.String("lsch", "", "LASTSERVICECHECK") lastServiceStateChange := flag.String("lssc", "", "LASTSERVICESTATECHANGE") @@ -306,32 +305,33 @@ func parseFlags()map[string]string{ serviceCheckCommand := flag.String("sc", "", "SERVICECHECKCOMMAND") 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") + priority := flag.String("priority", "", "Priority") flag.Parse() - if *apiKey != ""{ + if *apiKey != "" { parameters["apiKey"] = *apiKey - }else{ - parameters["apiKey"] = configParameters ["apiKey"] + } else { + parameters["apiKey"] = configParameters["apiKey"] } - if *icingaServer != ""{ + if *icingaServer != "" { parameters["icinga_server"] = *icingaServer - }else{ + } else { parameters["icinga_server"] = configParameters["icinga_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 != "" { @@ -388,9 +388,18 @@ func parseFlags()map[string]string{ parameters["service_perf_data"] = *servicePerfData parameters["service_check_command"] = *serviceCheckCommand + 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"] = "" + } + 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] @@ -400,7 +409,15 @@ func parseFlags()map[string]string{ return parameters } - - - - +func IsValidPriority(priority string) bool { + switch priority { + case + "P1", + "P2", + "P3", + "P4", + "P5": + return true + } + return false +} diff --git a/icinga2/icinga2/opsgenie.conf b/icinga2/icinga2/opsgenie.conf index 3533409..c40675d 100644 --- a/icinga2/icinga2/opsgenie.conf +++ b/icinga2/icinga2/opsgenie.conf @@ -3,6 +3,7 @@ object NotificationCommand "opsgenie-service-notification" { vars.hgns = {{ host.groups.join(",") }} vars.sgns = {{ service.groups.join(",") }} + vars.priority = "P3" command = [ "/usr/bin/icinga2opsgenie" ] arguments = { "-entityType" = "service" @@ -48,6 +49,7 @@ object NotificationCommand "opsgenie-service-notification" { "-lssc" = "$service.last_state_change$" "-so" = "$service.output$" "-spd" = "$service.perfdata$" + "-priority" = "$priority$" } } @@ -55,6 +57,7 @@ object NotificationCommand "opsgenie-host-notification" { import "plugin-notification-command" vars.hgns = {{ host.groups.join(",") }} + vars.priority = "P3" command = [ "/usr/bin/icinga2opsgenie" ] arguments = { "-entityType" = "host" @@ -81,6 +84,7 @@ object NotificationCommand "opsgenie-host-notification" { "-lhsc" = "$host.last_state_change$" "-ho" = "$host.output$" "-hpd" = "$host.perfdata$" + "-priority" = "$priority$" } }