Skip to content

Commit

Permalink
Merge pull request opsgenie#50 from Samoxive/update-opsviewv6
Browse files Browse the repository at this point in the history
Update Opsview integration script
  • Loading branch information
MeralBusraTekinsen authored Aug 29, 2019
2 parents fb10a31 + edceab1 commit e9117a5
Show file tree
Hide file tree
Showing 10 changed files with 397 additions and 1 deletion.
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@ apply from: 'bmcFootPrintsV11Incoming/bmcFootPrintsV11Incoming.gradle'
apply from: 'bmcFootPrintsV11Marid/bmcFootPrintsV11Marid.gradle'
apply from: 'cherwell/cherwell.gradle'
apply from: 'activeDirectory/activeDirectory.gradle'
apply from: 'opsviewv6/opsviewv6.gradle'


task packageIntegrations(dependsOn: [
Expand Down Expand Up @@ -562,7 +563,8 @@ task packageIntegrations(dependsOn: [
'packageBMCFootPrintsV11',
'packageBmcFootPrintsV11Incoming',
'packageBmcFootPrintsV11Marid',
'packageCherwell'
'packageCherwell',
'packageOpsviewV6'
])

task packageAll(dependsOn: ['packageIntegrations', 'packageLamp'])
2 changes: 2 additions & 0 deletions downloads.template.properties
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ bmcfootprintsv11Incomingzip.url=https://s3-us-west-2.amazonaws.com/opsgeniedownl
bmcfootprintsv11Maridzip.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/repo/opsgenie-bmcFootPrints-v11-[[bmcFootPrintsV11Marid]].zip
cherwellzip.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/repo/opsgenie-cherwell-[[cherwell]].zip
activedirectoryzip.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/repo/opsgenie-activedirectory-[[activeDirectory]].zip
opsviewv6rpm.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/repo/opsgenie-opsviewv6-[[opsviewv6]]-1.all.noarch.rpm
opsviewv6deb.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/repo/opsgenie-opsviewv6_[[opsviewv6]]_all.deb

graylog.url=https://github.com/opsgenie/opsgenie-graylog-plugin/releases
androidapp.url=https://s3-us-west-2.amazonaws.com/opsgeniedownloads/mobile/OpsGenieAndroid-2.1.16.apk
Expand Down
Binary file added opsviewv6/nagios2opsgenie
Binary file not shown.
216 changes: 216 additions & 0 deletions opsviewv6/nagios2opsgenie.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package main

import (
"bytes"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"

"github.com/alexcesaro/log"
"github.com/alexcesaro/log/golog"
)

var TOTAL_TIME = 60
var configParameters = map[string]string{
"logLevel": "warning",
"logPath": "/var/log/opsgenie/nagios2opsgenie.log",
/*
if you are using opsgenie from another domain e.g. eu, sandbox etc.
you should update the line below
*/
"opsgenieApiUrl": "https://api.opsgenie.com",
}
var parameters = make(map[string]string)
var levels = map[string]log.Level{"info": log.Info, "debug": log.Debug, "warning": log.Warning, "error": log.Error}
var logger log.Logger

func main() {
version := flag.String("v", "", "")
parseFlags()
if *version != "" {
fmt.Println("OpsView: 1.1")
return
}

logger = configureLogger()
printConfigToLog()

http_post()
}

func printConfigToLog() {
if logger != nil {
if logger.LogDebug() {
logger.Debug("Config:")
for k, v := range configParameters {
logger.Debug(k + "=" + v)
}
}
}
}

func configureLogger() log.Logger {
level := configParameters["logLevel"]
var logFilePath = configParameters["logPath"]

var tmpLogger 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)

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)
} else {
tmpLogger = golog.New(fileTmp, levels[strings.ToLower(level)])
}
} else {
tmpLogger = golog.New(file, levels[strings.ToLower(level)])
}

return tmpLogger
}

func getHttpClient(timeout int) *http.Client {
seconds := (TOTAL_TIME / 12) * 2 * timeout
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: http.ProxyFromEnvironment,
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*time.Duration(seconds))
if err != nil {
if logger != nil {
logger.Error("Error occurred while connecting: ", err)
}

return nil, err
}
conn.SetDeadline(time.Now().Add(time.Second * time.Duration(seconds)))
return conn, nil
},
},
}
return client
}

func http_post() {
apiUrl := configParameters["opsgenieApiUrl"] + "/v1/json/opsview"
target := "OpsGenie"

if logger != nil {
logger.Debug("Data to be posted:")
logger.Debug(parameters)
logger.Debug("url: " + apiUrl)
}
var buf, _ = json.Marshal(parameters)
logger.Debug(buf)
for i := 1; i <= 3; i++ {
body := bytes.NewBuffer(buf)
request, _ := http.NewRequest("POST", apiUrl, body)
client := getHttpClient(i)

if logger != nil {
logger.Debug("Trying to send data to " + target + " with timeout: " + strconv.Itoa((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 logger != nil {
logger.Debug(" Response code: " + strconv.Itoa(resp.StatusCode))
logger.Debug("Response: " + string(body[:]))
logger.Info("Data from Opsview posted to " + target + " successfully")
}
} else {
if logger != nil {
logger.Error("Couldn't post data from Opsview to " + target + " successfully; Response code: " + strconv.Itoa(resp.StatusCode) + " Response Body: " + string(body[:]))
}
}
} else {
if logger != nil {
logger.Error("Couldn't read the response from "+target, err)
}
}
break
} else if i < 3 {
if logger != nil {
logger.Error("Error occurred while sending data, will retry.", error)
}
} else {
if logger != nil {
logger.Error("Failed to post data from Opsview to "+target, error)
}
}
if resp != nil {
defer resp.Body.Close()
}
}
}

func parseFlags() map[string]string {
apiKey := flag.String("apiKey", "", "apiKey")
tags := flag.String("tags", "", "Tags")
responders := flag.String("responders", "", "Responders")
logLevel := flag.String("logLevel", "", "logLevel")
logPath := flag.String("logPath", "", "logPath")
opsgenieApiUrl := flag.String("opsgenieApiUrl", "", "opsgenieApiUrl")

flag.Parse()

if *apiKey != "" {
parameters["apiKey"] = *apiKey
}
if *responders != "" {
parameters["responders"] = *responders
}
if *tags != "" {
parameters["tags"] = *tags
}
if *logPath != "" {
configParameters["logPath"] = *logPath
}
if *logLevel != "" {
configParameters["logLevel"] = *logLevel
}
if *opsgenieApiUrl != "" {
if strings.Contains(*opsgenieApiUrl, "https://") {
configParameters["opsgenieApiUrl"] = *opsgenieApiUrl
} else {
configParameters["opsgenieApiUrl"] = "https://" + (*opsgenieApiUrl)
}
}

for _, e := range os.Environ() {
pair := strings.Split(e, "=")
key := pair[0]
if strings.Contains(key, "NAGIOS") {
parameters[key] = pair[1]
}
}

args := flag.Args()
for i := 0; i < len(args); i += 2 {
if len(args)%2 != 0 && i == len(args)-1 {
parameters[args[i]] = ""
} else {
parameters[args[i]] = args[i+1]
}
}

return parameters
}
11 changes: 11 additions & 0 deletions opsviewv6/native/control_deb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Package: [package-name]
Version: [version]
Architecture: all
Description: [description]
Depends:
Vendor: OpsGenie
License: 'Apache 2.0'
Section: default
Priority: extra
Homepage: http://www.opsgenie.com
Maintainer: OpsGenie
14 changes: 14 additions & 0 deletions opsviewv6/native/ogAfter.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
if [ ! -d "/var/log/opsgenie" ]; then
mkdir /var/log/opsgenie
fi
chmod -R 775 /var/log/opsgenie
chmod -R g+s /var/log/opsgenie

chmod 755 /opt/opsview/monitoringscripts/notifications/nagios2opsgenie

if id -u opsview >/dev/null 2>&1; then
usermod -a -G opsgenie opsview
chown -R opsview:opsgenie /var/log/opsgenie
else
echo "WARNING : opsview user does not exist. Please don't forget to add your opsview user to opsgenie group!"
fi
6 changes: 6 additions & 0 deletions opsviewv6/native/ogBefore.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash
if [ -z $(getent passwd opsgenie) ]
then
groupadd opsgenie -r
useradd -g opsgenie opsgenie -r -d /var/opsgenie/
fi
Loading

0 comments on commit e9117a5

Please sign in to comment.