Skip to content

Commit

Permalink
Format code of Icinga 2 integration
Browse files Browse the repository at this point in the history
Use standard golang formatting in the Icinga 2 integration.

Signed-off-by: Tobias von der Krone <[email protected]>
  • Loading branch information
Tobias von der Krone committed Sep 11, 2019
1 parent 1b68302 commit a5eec08
Showing 1 changed file with 91 additions and 92 deletions.
183 changes: 91 additions & 92 deletions icinga2/icinga2/icinga2opsgenie.go
Original file line number Diff line number Diff line change
@@ -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
}
Expand All @@ -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") {
Expand All @@ -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])
}
}
}
Expand All @@ -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"]

Expand All @@ -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)
Expand All @@ -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"]
Expand All @@ -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 {
Expand All @@ -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)
Expand All @@ -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"
}

Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -306,33 +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")
priority := flag.String("priority","","Priority")
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 != "" {
Expand Down Expand Up @@ -400,7 +399,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]
Expand Down

0 comments on commit a5eec08

Please sign in to comment.