12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package alarm
- import (
- "context"
- "fmt"
- "smart-thirdparty/errors"
- "smart-thirdparty/parser"
- pb_v1 "smart-thirdparty/pb/v1"
- "smart-thirdparty/thirdparty"
- "github.com/jaryhe/gopkgs/logger"
- jsoniter "github.com/json-iterator/go"
- "go.uber.org/zap"
- "google.golang.org/grpc/status"
- )
- // 替换encoding/json包
- var json = jsoniter.ConfigCompatibleWithStandardLibrary
- // 发送短信告警
- func sendSmsAlarm(req *pb_v1.SendAlarmRequest) error {
- var data []interface{}
- data = append(data, parser.Conf.ThirdParty.RongLian.City)
- data = append(data, req.DeviceName)
- data = append(data, req.AlarmTime)
- data = append(data, req.AlarmReason)
- if err := thirdparty.SendTemplateSMS(req.PhoneNumber, data, parser.Conf.ThirdParty.RongLian.AlarmTemplateId); err != nil {
- logger.Error("func",
- zap.String("call", "ThirdParty.SendTemplateSMS"),
- zap.String("params", req.PhoneNumber),
- zap.String("error", err.Error()))
- return errors.SmsAlarmError
- }
- return nil
- }
- // 发送邮件告警
- func sendEmailAlarm(req *pb_v1.SendAlarmRequest) error {
- content := fmt.Sprintf("设备(%s) 于 %s 因 %s 告警", req.DeviceName, req.AlarmTime, req.AlarmReason)
- err := thirdparty.SendMail(parser.Conf.ThirdParty.MailUser,
- parser.Conf.ThirdParty.MailPass,
- parser.Conf.ThirdParty.MailHost,
- req.Email, "设备告警", nil, content)
- if err != nil {
- logger.Error("func",
- zap.String("call", "thirdparty.SendMail"),
- zap.String("params", req.Email),
- zap.String("error", err.Error()))
- return errors.SmsAlarmError
- }
- return nil
- }
- func SendAlarm(ctx context.Context, req *pb_v1.SendAlarmRequest) (reply *pb_v1.SendAlarmReply, err error) {
- reply = &pb_v1.SendAlarmReply{}
- // 捕获各个task中的异常并返回给调用者
- defer func() {
- if r := recover(); r != nil {
- err = fmt.Errorf("%+v", r)
- e := &status.Status{}
- if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
- logger.Error("err",
- zap.String("system_err", err.Error()),
- zap.Stack("stacktrace"))
- }
- }
- }()
- if req.PhoneNumber == "" && req.Email == "" {
- return nil, status.Error(10003, "参数错误,告警联系人为空")
- }
- if req.AlarmReason == "" {
- return nil, status.Error(10003, "参数错误,告警原因为空")
- }
- if req.AlarmTime == "" {
- return nil, status.Error(10003, "参数错误,告警时间为空")
- }
- if req.DeviceName == "" {
- return nil, status.Error(10003, "参数错误,设备名为空")
- }
- if req.PhoneNumber != "" {
- sendSmsAlarm(req)
- }
- if req.Email != "" {
- sendEmailAlarm(req)
- }
- return
- }
|