Skip to content

Commit

Permalink
Merge pull request #171 from Zhang21/master
Browse files Browse the repository at this point in the history
Add: Makefile
  • Loading branch information
feiyu563 authored Dec 15, 2021
2 parents b178cbf + 1434c19 commit e018ee3
Show file tree
Hide file tree
Showing 17 changed files with 252 additions and 72 deletions.
3 changes: 1 addition & 2 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
.idea
.git
doc
example
logo
tests
.gitignore
build.sh
build.bat
README.MD
README.MD
19 changes: 14 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,32 @@ FROM golang:1.16-alpine3.12 as builder

WORKDIR $GOPATH/src/github.com/feiyu563/PrometheusAlert

RUN apk update && apk upgrade && apk add --no-cache gcc g++ sqlite-libs
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
apk update && apk upgrade && \
apk add --no-cache gcc g++ sqlite-libs make git

ENV GO111MODULE on

ENV GOPROXY https://goproxy.io

COPY . $GOPATH/src/github.com/feiyu563/PrometheusAlert

RUN go mod vendor && go build
RUN make build

# -----------------------------------------------------------------------------

FROM alpine:3.12

LABEL maintainer="jikun.zhang"

RUN apk update && apk upgrade && apk add --no-cache sqlite-libs
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
apk add tzdata && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo "Asia/Shanghai" > /etc/timezone && \
apk del tzdata && \
apk update && apk upgrade && apk add --no-cache sqlite-libs curl

HEALTHCHECK --start-period=10s --interval=20s --timeout=3s --retries=3 \
CMD curl -fs http://localhost:8080/health || exit 1

WORKDIR /app

Expand All @@ -38,4 +47,4 @@ COPY views views

#ENTRYPOINT [ "/app/PrometheusAlert" ]

CMD if [ ! -f /app/db/PrometheusAlertDB.db ];then cp /opt/PrometheusAlertDB.db /app/db/PrometheusAlertDB.db;echo 'init ok!';else echo 'pass!';fi && /app/PrometheusAlert
CMD if [ ! -f /app/db/PrometheusAlertDB.db ];then cp /opt/PrometheusAlertDB.db /app/db/PrometheusAlertDB.db;echo 'init ok!';else echo 'pass!';fi && /app/PrometheusAlert
56 changes: 56 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
pkgs = $(shell go list ./... | grep -v vendor/)

DOCKER_IMAGE_NAME ?= feiyu563/prometheus-alert

BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
BUILDDATE ?= $(shell date -I'seconds')
BUILDUSER ?= $(shell whoami)@$(shell hostname)
REVISION ?= $(shell git rev-parse HEAD)
TAG_VERSION ?= $(shell git describe --tags --abbrev=0)

VERSION_LDFLAGS := \
-X main.Version=$(TAG_VERSION) \
-X main.Revision=$(REVISION) \
-X main.BuildUser=$(BUILDUSER) \
-X main.BuildDate=$(BUILDDATE)

all: format vet test build

.PHONY: format
format:
@echo ">> formatting code"
go fmt $(pkgs)

.PHONY: vet
vet:
@echo ">> vetting code"
go vet $(pkgs)

.PHONY: test
test:
@echo ">> running short tests"
go test -short $(pkgs)

.PHONY: build
build:
@echo ">> building code"
go mod vendor
GO11MODULE=on GO111MODULE=on GOPROXY=https://goproxy.io \
go build -ldflags "$(VERSION_LDFLAGS)" -o PrometheusAlert

.PHONY: docker
docker:
@echo ">> building docker image"
docker build -t "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" .
docker tag "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" "$(DOCKER_IMAGE_NAME):latest"

.PHONY: docker-push
docker-push:
@echo ">> pushing docker image"
docker push "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)"
docker push "$(DOCKER_IMAGE_NAME):latest"

.PHONY: docker-test
docker-test:
@echo ">> testing docker image and PrometheusAlert's health"
cmd/test_image.sh "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" 8080
40 changes: 40 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,46 @@ PrometheusAlert是开源的运维告警中心消息转发系统,支持主流
<br>
<br>


## 构建

应用信息和构建相关的命令都写入了Makefile,请确保安装`make`, `git`, `go`命令。如有特定需要,请自行修改Makefile。

```bash
# 默认
make

# 只运行构建
make build

# 运行 go fmt
make format

# 运行 go vet
make vet

# 构建镜像
make docker

# 推送镜像
make docker-push

# 运行镜像测试
make docker-test


# 运行
copy conf/app-example.conf conf/app.conf
./PrometheusAlert
# 测试应用健康
curl http://localhost:8080/health
```


<br/>
<br/>


## 启动

```
Expand Down
37 changes: 37 additions & 0 deletions cmd/test_image.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/bin/bash
set -eo pipefail

docker_image=$1
port=$2

container_id=''

wait_start() {
for _ in {1..10}; do
if /usr/bin/curl -s -m 5 -f "http://localhost:${port}/health"; then
docker_cleanup
exit 0
else
sleep 1
fi
done

exit 1
}

docker_start() {
container_id=$(docker run --rm -d -p "${port}":"${port}" "${docker_image}")
}

docker_cleanup() {
echo ">> cleaning up container"
docker kill "${container_id}"
}

if [[ "$#" -ne 2 ]] ; then
echo "Usage: $0 feiyu563/prometheus-alert 8080" >&2
exit 1
fi

docker_start
wait_start
20 changes: 13 additions & 7 deletions controllers/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package controllers
import (
"PrometheusAlert/models"
"bytes"
"encoding/json"
"strconv"
"time"
"text/template"
"time"

"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"encoding/json"
)

//取到tpl路径
Expand All @@ -25,6 +26,11 @@ func (c *MainController) Get() {
c.Data["IsLogin"] = checkAccount(c.Ctx)
}

// Health returns Hello 200
func (c *MainController) Health() {
c.Ctx.WriteString("Hello!\n")
}

//test page
func (c *MainController) Test() {
if !checkAccount(c.Ctx) {
Expand Down Expand Up @@ -145,13 +151,13 @@ func (c *MainController) MarkdownTest() {
buf := new(bytes.Buffer)
tpl, err := template.New("").Funcs(funcMap).Parse(TplContent)
if err != nil {
resp=err.Error()
resp = err.Error()
} else {
err=tpl.Execute(buf, p_json)
if err!=nil {
resp=err.Error()
err = tpl.Execute(buf, p_json)
if err != nil {
resp = err.Error()
} else {
resp=buf.String()
resp = buf.String()
}
}
c.Data["json"] = resp
Expand Down
4 changes: 2 additions & 2 deletions controllers/graylog3.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ type Graylog3 struct {
Backlogs []Backlog `json:"backlog"`
}
type AlertEvent struct {
Source string `json:"source`
Source string `json:"source"`
}
type Backlog struct {
Timestamp string `json:"timestamp"` //开始时间
Index string `json:"index"` //索引
Message string `json:"message"`
Fields G3Field `json:"fields`
Fields G3Field `json:"fields"`
}
type G3Field struct {
Gl2RemoteIp string `json:"gl2_remote_ip"`
Expand Down
2 changes: 1 addition & 1 deletion controllers/huawei.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func PostHWmessage(Messages string, PhoneNumbers, logsign string) string {
digestBase64 := base64.StdEncoding.EncodeToString([]byte(digest))
xheader := `"UsernameToken Username="` + hwappkey + `",PasswordDigest="` + digestBase64 + `",Nonce="` + nonce + `",Created="` + now + `"`
//生成form数据
FormData:=strings.NewReader(url.Values{"from": {sender}, "to": {PhoneNumbers}, "templateId": {hwtplid}, "templateParas": {"[\"" + Messages + "\"]"}, "signature": {hwsign}, "statusCallback": {""}, "extend": {logsign}}.Encode())
FormData := strings.NewReader(url.Values{"from": {sender}, "to": {PhoneNumbers}, "templateId": {hwtplid}, "templateParas": {"[\"" + Messages + "\"]"}, "signature": {hwsign}, "statusCallback": {""}, "extend": {logsign}}.Encode())
var tr *http.Transport
if proxyUrl := beego.AppConfig.String("proxy"); proxyUrl != "" {
proxy := func(_ *http.Request) (*url.URL, error) {
Expand Down
2 changes: 1 addition & 1 deletion controllers/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type Annotations struct {
Email string `json:"email"` //2020年7月4日 10:15:20 增加多个email告警支持
Groupid string `json:"groupid"` //2021年2月2日 17:28:23 增加多个如流告警支持
AtSomeOne string `json:"at"` //2021年6月23日 14:02:21 增加@某人支持
Rr string `json:"rr"` //2021年9月14日 14:48:08 增加随机轮询参数支持
Rr string `json:"rr"` //2021年9月14日 14:48:08 增加随机轮询参数支持
}
type Alerts struct {
Status string
Expand Down
18 changes: 9 additions & 9 deletions controllers/prometheusalert.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"PrometheusAlert/models"
"bytes"
"encoding/json"
"strings"
"text/template"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"strings"
"text/template"
)

type PrometheusAlertController struct {
Expand Down Expand Up @@ -119,7 +119,7 @@ func (c *PrometheusAlertController) PrometheusAlert() {
P_groupid = beego.AppConfig.String("BDRL_ID")
}
P_atsomeone := c.Input().Get("at")
P_rr:=c.Input().Get("rr")
P_rr := c.Input().Get("rr")
//get tpl
message := ""
funcMap := template.FuncMap{
Expand All @@ -140,7 +140,7 @@ func (c *PrometheusAlertController) PrometheusAlert() {
message = err.Error()
} else {
tpl.Execute(buf, p_json)
message = SendMessagePrometheusAlert(buf.String(), P_type, P_ddurl, P_wxurl, P_fsurl, P_webhookurl, P_phone, P_email, P_touser, P_toparty, P_totag, P_groupid, P_atsomeone,P_rr,logsign)
message = SendMessagePrometheusAlert(buf.String(), P_type, P_ddurl, P_wxurl, P_fsurl, P_webhookurl, P_phone, P_email, P_touser, P_toparty, P_totag, P_groupid, P_atsomeone, P_rr, logsign)
}
} else {
message = "接口参数缺失!"
Expand All @@ -150,15 +150,15 @@ func (c *PrometheusAlertController) PrometheusAlert() {
c.ServeJSON()
}

func SendMessagePrometheusAlert(message, ptype, pddurl, pwxurl, pfsurl, pwebhookurl, pphone, email, ptouser, ptoparty, ptotag, pgroupid, patsomeone,prr, logsign string) string {
func SendMessagePrometheusAlert(message, ptype, pddurl, pwxurl, pfsurl, pwebhookurl, pphone, email, ptouser, ptoparty, ptotag, pgroupid, patsomeone, prr, logsign string) string {
Title := beego.AppConfig.String("title")
ret := ""
model.AlertsFromCounter.WithLabelValues("PrometheusAlert", message, "", "", "").Add(1)
switch ptype {
//微信渠道
case "wx":
Wxurl := strings.Split(pwxurl, ",")
if prr=="true" {
if prr == "true" {
ret += PostToWeiXin(message, DoBalance(Wxurl), patsomeone, logsign)
} else {
for _, url := range Wxurl {
Expand All @@ -169,7 +169,7 @@ func SendMessagePrometheusAlert(message, ptype, pddurl, pwxurl, pfsurl, pwebhook
//钉钉渠道
case "dd":
Ddurl := strings.Split(pddurl, ",")
if prr=="true" {
if prr == "true" {
ret += PostToDingDing(Title+"告警消息", message, DoBalance(Ddurl), patsomeone, logsign)
} else {
for _, url := range Ddurl {
Expand All @@ -180,7 +180,7 @@ func SendMessagePrometheusAlert(message, ptype, pddurl, pwxurl, pfsurl, pwebhook
//飞书渠道
case "fs":
Fsurl := strings.Split(pfsurl, ",")
if prr=="true" {
if prr == "true" {
ret += PostToFS(Title+"告警消息", message, DoBalance(Fsurl), patsomeone, logsign)
} else {
for _, url := range Fsurl {
Expand All @@ -191,7 +191,7 @@ func SendMessagePrometheusAlert(message, ptype, pddurl, pwxurl, pfsurl, pwebhook
//Webhook渠道
case "webhook":
Fwebhookurl := strings.Split(pwebhookurl, ",")
if prr=="true" {
if prr == "true" {
ret += PostToWebhook(message, DoBalance(Fwebhookurl), logsign)
} else {
for _, url := range Fwebhookurl {
Expand Down
10 changes: 5 additions & 5 deletions controllers/public.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package controllers

import (
"bufio"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"math/rand"
"os"
"strconv"
"strings"
"time"
"math/rand"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)

//转换时间戳到时间字符串
Expand Down Expand Up @@ -109,11 +109,11 @@ func GetUserPhone(neednum int) string {
// 随机返回
func DoBalance(instances []string) string {
if len(instances) == 0 {
logs.Error( "no instances for rand")
logs.Error("no instances for rand")
return ""
}
lens := len(instances)
index := rand.Intn(lens)
inst := instances[index]
return inst
}
}
Loading

0 comments on commit e018ee3

Please sign in to comment.