notify_tpl.go 5.1 KB
Newer Older
N
ning 已提交
1 2 3 4 5 6 7 8 9 10
package models

import (
	"encoding/json"
	"fmt"
	"html/template"
	"path"
	"strings"

	"github.com/ccfos/nightingale/v6/pkg/ctx"
11
	"github.com/ccfos/nightingale/v6/pkg/poster"
N
ning 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	"github.com/ccfos/nightingale/v6/pkg/tplx"

	"github.com/pkg/errors"
	"github.com/toolkits/pkg/file"
	"github.com/toolkits/pkg/logger"
)

type NotifyTpl struct {
	Id      int64  `json:"id"`
	Name    string `json:"name"`
	Channel string `json:"channel"`
	Content string `json:"content"`
}

func (n *NotifyTpl) TableName() string {
	return "notify_tpl"
}

func (n *NotifyTpl) Create(c *ctx.Context) error {
	return Insert(c, n)
}

func (n *NotifyTpl) UpdateContent(c *ctx.Context) error {
	return DB(c).Model(n).Update("content", n.Content).Error
}

func (n *NotifyTpl) Update(c *ctx.Context) error {
	return DB(c).Model(n).Select("name").Updates(n).Error
}

func (n *NotifyTpl) CreateIfNotExists(c *ctx.Context, channel string) error {
	count, err := NotifyTplCountByChannel(c, channel)
	if err != nil {
		return errors.WithMessage(err, "failed to count notify tpls")
	}

	if count != 0 {
		return nil
	}

	err = n.Create(c)
	return err
}

func NotifyTplCountByChannel(c *ctx.Context, channel string) (int64, error) {
	var count int64
	err := DB(c).Model(&NotifyTpl{}).Where("channel=?", channel).Count(&count).Error
	return count, err
}

func NotifyTplGets(c *ctx.Context) ([]*NotifyTpl, error) {
63 64 65 66 67
	if !c.IsCenter {
		lst, err := poster.GetByUrls[[]*NotifyTpl](c, "/v1/n9e/notify-tpls")
		return lst, err
	}

N
ning 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80
	var lst []*NotifyTpl
	err := DB(c).Find(&lst).Error
	return lst, err
}

func ListTpls(c *ctx.Context) (map[string]*template.Template, error) {
	notifyTpls, err := NotifyTplGets(c)
	if err != nil {
		return nil, errors.WithMessage(err, "failed to get notify tpls")
	}

	tpls := make(map[string]*template.Template)
	for _, notifyTpl := range notifyTpls {
N
ning 已提交
81 82 83 84 85 86
		var defs = []string{
			"{{$labels := .TagsMap}}",
			"{{$value := .TriggerValue}}",
		}
		text := strings.Join(append(defs, notifyTpl.Content), "")
		tpl, err := template.New(notifyTpl.Channel).Funcs(tplx.TemplateFuncMap).Parse(text)
N
ning 已提交
87 88 89 90 91 92 93 94 95 96
		if err != nil {
			return nil, fmt.Errorf("failed to parse tpl:%v %v ", notifyTpl, err)
		}

		tpls[notifyTpl.Channel] = tpl
	}
	return tpls, nil
}

func InitNotifyConfig(c *ctx.Context, tplDir string) {
97 98 99 100
	if !c.IsCenter {
		return
	}

N
ning 已提交
101 102 103 104 105 106 107 108 109
	// init notify channel
	cval, err := ConfigsGet(c, NOTIFYCHANNEL)
	if err != nil {
		logger.Errorf("failed to get notify contact config: %v", err)
		return
	}

	if cval == "" {
		var notifyChannels []NotifyChannel
N
ning 已提交
110
		for _, channel := range DefaultChannels {
N
ning 已提交
111 112 113 114 115 116 117 118 119
			notifyChannels = append(notifyChannels, NotifyChannel{Ident: channel, Name: channel, BuiltIn: true})
		}

		data, _ := json.Marshal(notifyChannels)
		err = ConfigsSet(c, NOTIFYCHANNEL, string(data))
		if err != nil {
			logger.Errorf("failed to set notify contact config: %v", err)
			return
		}
N
ning 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	} else {
		var channels []NotifyChannel
		err = json.Unmarshal([]byte(cval), &channels)
		if err != nil {
			logger.Errorf("failed to unmarshal notify channel config: %v", err)
			return
		}
		channelMap := make(map[string]bool)
		for _, channel := range channels {
			channelMap[channel.Ident] = true
		}

		var newChannels []NotifyChannel
		for _, channel := range DefaultChannels {
			if _, ok := channelMap[channel]; !ok {
				newChannels = append(newChannels, NotifyChannel{Ident: channel, Name: channel, BuiltIn: true})
			}
		}
		if len(newChannels) > 0 {
			channels = append(channels, newChannels...)
			data, _ := json.Marshal(channels)
			err = ConfigsSet(c, NOTIFYCHANNEL, string(data))
			if err != nil {
				logger.Errorf("failed to set notify contact config: %v", err)
				return
			}
		}
N
ning 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	}

	// init notify contact
	cval, err = ConfigsGet(c, NOTIFYCONTACT)
	if err != nil {
		logger.Errorf("failed to get notify contact config: %v", err)
		return
	}

	if cval == "" {
		var notifyContacts []NotifyContact
		contacts := []string{DingtalkKey, WecomKey, FeishuKey, MmKey, TelegramKey}
		for _, contact := range contacts {
			notifyContacts = append(notifyContacts, NotifyContact{Ident: contact, Name: contact, BuiltIn: true})
		}

		data, _ := json.Marshal(notifyContacts)
		err = ConfigsSet(c, NOTIFYCONTACT, string(data))
		if err != nil {
			logger.Errorf("failed to set notify contact config: %v", err)
			return
		}
	}

	// init notify tpl
	filenames, err := file.FilesUnder(tplDir)
	if err != nil {
		logger.Errorf("failed to get tpl files under %s", tplDir)
		return
	}

	if len(filenames) == 0 {
		logger.Errorf("no tpl files under %s", tplDir)
		return
	}

	tplMap := make(map[string]string)
	for i := 0; i < len(filenames); i++ {
		if strings.HasSuffix(filenames[i], ".tpl") {
			name := strings.TrimSuffix(filenames[i], ".tpl")
			tplpath := path.Join(tplDir, filenames[i])
			content, err := file.ToString(tplpath)
			if err != nil {
				logger.Errorf("failed to read tpl file: %s", filenames[i])
				continue
			}
			tplMap[name] = content
		}
	}

	for channel, content := range tplMap {
		notifyTpl := NotifyTpl{
			Name:    channel,
			Channel: channel,
			Content: content,
		}

		err := notifyTpl.CreateIfNotExists(c, channel)
		if err != nil {
			logger.Warningf("failed to create notify tpls %v", err)
		}
	}
}