Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"wechat_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/resource/conf:go_default_library",
"//app/service/main/resource/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"wechat.go",
],
importpath = "go-common/app/service/main/resource/dao/alarm",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/resource/conf:go_default_library",
"//app/service/main/resource/model:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,69 @@
package alarm
import (
"context"
"net/http"
"strings"
"time"
"go-common/app/service/main/resource/conf"
"go-common/app/service/main/resource/model"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
)
// Dao is redis dao.
type Dao struct {
c *conf.Config
netClient *http.Client
httpClient *httpx.Client
}
// New is new redis dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
httpClient: httpx.NewClient(c.HTTPClient),
netClient: &http.Client{
Timeout: 3 * time.Second,
},
}
return d
}
func (d *Dao) CheckURL(originURL string, wis []*model.ResWarnInfo) {
var (
url string
req *http.Request
resp *http.Response
err error
)
if strings.HasPrefix(originURL, "https://") {
log.Info("CheckURL url(%s) is https ,replace to http", originURL)
url = strings.Replace(originURL, "https://", "http://", -1)
} else if !strings.HasPrefix(originURL, "http://") {
log.Info("CheckURL url(%s) don't have https and http", originURL)
url = "http://" + originURL
} else {
url = originURL
}
if req, err = http.NewRequest("GET", url, nil); err != nil {
log.Error("CheckURL NewRequest(%v) error(%v)", url, err)
return
}
req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36")
resp, err = d.netClient.Do(req)
if err != nil {
log.Error("CheckURL url(%s) originURL(%s) error(%v)", url, originURL, err)
} else if resp.StatusCode != http.StatusOK {
log.Error("CheckURL url(%s) originURL(%s) code(%v) not OK ", url, originURL, resp.StatusCode)
var sends = make(map[string][]*model.ResWarnInfo)
for _, wi := range wis {
sends[wi.UserName] = append(sends[wi.UserName], wi)
}
for userName, send := range sends {
d.sendWeChartURL(context.TODO(), resp.StatusCode, userName, send)
}
}
}

View File

@@ -0,0 +1,63 @@
package alarm
import (
"flag"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
"go-common/app/service/main/resource/conf"
"go-common/app/service/main/resource/model"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.app-svr.resource-service")
flag.Set("conf_token", "y79sErNhxggjvULS0O8Czas9PaxHBF5o")
flag.Set("tree_id", "3232")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/resource-service-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.httpClient.SetTransport(gock.DefaultTransport)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}
func TestDaoCheckURL(t *testing.T) {
var (
originURL = "https://www.bilibili.com"
wis = []*model.ResWarnInfo{}
)
convey.Convey("CheckURL", t, func(ctx convey.C) {
httpMock("GET", "http://www.bilibili.com").Reply(200)
d.CheckURL(originURL, wis)
ctx.Convey("no return values", func() {
})
})
}

View File

@@ -0,0 +1,182 @@
package alarm
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/service/main/resource/model"
"go-common/library/log"
)
var (
_states = map[int8]string{
int8(0): "开放浏览",
int8(-1): "待审",
int8(-2): "打回稿件回收站",
int8(-3): "网警锁定删除",
int8(-4): "锁定稿件",
// -5: "锁定稿件开放浏览",
int8(-6): "修复待审",
int8(-7): "暂缓审核",
// -8: "补档待审",
int8(-9): "等待转码",
int8(-10): "延迟发布",
int8(-11): "视频源待修",
// -12: "上传失败",
int8(-13): "允许评论待审",
// -14: "临时回收站",
int8(-15): "分发中",
int8(-16): "转码失败",
int8(-30): "创建已提交",
int8(-40): "UP主定时发布",
int8(-100): "UP主删除",
}
_codes = map[int]string{
404: "页面未找到",
502: "服务端异常",
504: "SLB超时",
}
)
func stateDescribe(state int8) string {
des, ok := _states[state]
if ok {
return des
}
return strconv.Itoa(int(state))
}
const (
_warnTitle = `
【线上投放告警】您有一个投放发生了异常,请尽快确认是否影响投放。
%v
以上内容确认后,如有异常请联系相关人员手动处理。`
_offLineTitle = `
【线上投放下线告警】您有一个投放内容变不可见状态,已自动下线。请尽快补充投放。
%v
以上投放所涉及的排期申请已经置为 <申请未投放>。`
_archiveContent = `
投放ID%d
稿件ID%d
投放标题:%s
投放位置:%s (位置ID%d)
投放时间段:%s - %s
当前稿件状态:%s
`
_urlContent = `
投放ID%d
URL%v
投放标题:%s
投放位置:%s (位置ID%d)
投放时间段:%s - %s
错误信息:%v(错误码: %v)
`
)
type wxParams struct {
Username string `json:"username"`
Content string `json:"content"`
Token string `json:"token"`
Timestamp int64 `json:"timestamp"`
Sign string `json:"signature"`
}
type resp struct {
Status int64 `json:"status"`
Msg string `json:"msg"`
}
// SendWeChart send message to QYWX
func (d *Dao) SendWeChart(c context.Context, ns int8, userName string, res []*model.ResWarnInfo, titleType string) (err error) {
var (
users = append(d.c.WeChantUsers, userName)
newStateStr = stateDescribe(ns)
contents []string
)
for _, re := range res {
stime := re.STime.Time().Format("2006-01-02 15:04:05")
etime := re.ETime.Time().Format("2006-01-02 15:04:05")
contents = append(contents, fmt.Sprintf(_archiveContent, re.AssignmentID, re.AID, re.AssignmentName, re.ResourceName, re.ResourceID, stime, etime, newStateStr))
}
params := url.Values{}
params.Set("username", strings.Join(users, ","))
if titleType == "warn" {
params.Set("content", fmt.Sprintf(_warnTitle, strings.Join(contents, "")))
} else {
params.Set("content", fmt.Sprintf(_offLineTitle, strings.Join(contents, "")))
}
params.Set("token", d.c.WeChatToken)
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
mh := md5.Sum([]byte(params.Encode() + d.c.WeChatSecret))
params.Set("signature", hex.EncodeToString(mh[:]))
p := &wxParams{
Username: params.Get("username"),
Content: params.Get("content"),
Token: params.Get("token"),
Sign: params.Get("signature"),
}
p.Timestamp, _ = strconv.ParseInt(params.Get("timestamp"), 10, 64)
bs, _ := json.Marshal(p)
payload := strings.NewReader(string(bs))
req, _ := http.NewRequest("POST", "http://bap.bilibili.co/api/v1/message/add", payload)
req.Header.Add("content-type", "application/json; charset=utf-8")
v := &resp{}
if err = d.httpClient.Do(context.TODO(), req, v); err != nil {
log.Error("s.httpClient.Do error(%v)", err)
}
return
}
// sendWeChartURL send message to QYWX
func (d *Dao) sendWeChartURL(c context.Context, code int, userName string, res []*model.ResWarnInfo) (err error) {
var (
users = append(d.c.WeChantUsers, userName)
codeInfo string
contents []string
)
if codeInfo = _codes[code]; codeInfo == "" {
codeInfo = "未知错误,请手动确认"
}
for _, re := range res {
stime := re.STime.Time().Format("2006-01-02 15:04:05")
etime := re.ETime.Time().Format("2006-01-02 15:04:05")
contents = append(contents, fmt.Sprintf(_urlContent, re.AssignmentID, re.URL, re.AssignmentName, re.ResourceName, re.ResourceID, stime, etime, codeInfo, code))
}
params := url.Values{}
params.Set("username", strings.Join(users, ","))
params.Set("content", fmt.Sprintf(_warnTitle, strings.Join(contents, "")))
params.Set("token", d.c.WeChatToken)
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
mh := md5.Sum([]byte(params.Encode() + d.c.WeChatSecret))
params.Set("signature", hex.EncodeToString(mh[:]))
p := &wxParams{
Username: params.Get("username"),
Content: params.Get("content"),
Token: params.Get("token"),
Sign: params.Get("signature"),
}
p.Timestamp, _ = strconv.ParseInt(params.Get("timestamp"), 10, 64)
bs, _ := json.Marshal(p)
payload := strings.NewReader(string(bs))
req, _ := http.NewRequest("POST", "http://bap.bilibili.co/api/v1/message/add", payload)
req.Header.Add("content-type", "application/json; charset=utf-8")
v := &resp{}
if err = d.httpClient.Do(context.TODO(), req, v); err != nil {
log.Error("s.httpClient.Do error(%v)", err)
}
return
}

View File

@@ -0,0 +1,72 @@
package alarm
import (
"context"
"testing"
"go-common/app/service/main/resource/model"
"github.com/smartystreets/goconvey/convey"
)
func TestAlarmstateDescribe(t *testing.T) {
convey.Convey("stateDescribe", t, func(ctx convey.C) {
ctx.Convey("When state = 0 is in the const map", func(ctx convey.C) {
res := stateDescribe(0)
ctx.Convey("Then res should equal 开放浏览", func(ctx convey.C) {
ctx.So(res, convey.ShouldEqual, "开放浏览")
})
})
ctx.Convey("When state = -99 is not in the const map", func(ctx convey.C) {
res := stateDescribe(-99)
ctx.Convey("Then res should equal -99", func(ctx convey.C) {
ctx.So(res, convey.ShouldEqual, "-99")
})
})
})
}
func TestAlarmSendWeChart(t *testing.T) {
convey.Convey("SendWeChart", t, func() {
convey.Convey("When everything is correct", func(ctx convey.C) {
httpMock("POST", "http://bap.bilibili.co/api/v1/message/add").Reply(200).JSON("{}")
err := d.SendWeChart(context.Background(), 1, "", []*model.ResWarnInfo{{}}, "unit test msg")
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
convey.Convey("When set http request gets 404", func(ctx convey.C) {
httpMock("POST", "http://bap.bilibili.co/api/v1/message/add").Reply(404)
err := d.SendWeChart(context.Background(), 1, "", []*model.ResWarnInfo{{}}, "unit test msg")
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
convey.Convey("When set titleType == \"warn\"", func(ctx convey.C) {
httpMock("POST", "http://bap.bilibili.co/api/v1/message/add").Reply(200).JSON("{}")
err := d.SendWeChart(context.Background(), 1, "", []*model.ResWarnInfo{{}}, "warn")
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestAlarmsendWeChartURL(t *testing.T) {
convey.Convey("sendWeChartURL", t, func() {
convey.Convey("When everything is correct", func(ctx convey.C) {
httpMock("POST", "http://bap.bilibili.co/api/v1/message/add").Reply(200).JSON("{}")
err := d.sendWeChartURL(context.Background(), 1, "", []*model.ResWarnInfo{{}})
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
convey.Convey("When set http request gets 404", func(ctx convey.C) {
httpMock("POST", "http://bap.bilibili.co/api/v1/message/add").Reply(404)
err := d.sendWeChartURL(context.Background(), 1, "", []*model.ResWarnInfo{{}})
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}