router_collect.go 9.2 KB
Newer Older
7
3.0.0  
710leo 已提交
1 2 3 4 5 6 7 8
package http

import (
	"encoding/json"
	"fmt"
	"regexp"
	"strings"

9
	"github.com/didi/nightingale/src/models"
Y
yubo 已提交
10
	"github.com/didi/nightingale/src/modules/monapi/collector"
7
3.0.0  
710leo 已提交
11 12 13 14 15 16 17 18
	"github.com/didi/nightingale/src/modules/monapi/scache"

	"github.com/gin-gonic/gin"
	"github.com/toolkits/pkg/errors"
	"github.com/toolkits/pkg/logger"
)

type CollectRecv struct {
Y
yubo 已提交
19 20
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
7
3.0.0  
710leo 已提交
21 22
}

Y
yubo 已提交
23
func collectRulePost(c *gin.Context) {
7
3.0.0  
710leo 已提交
24 25 26
	var recv []CollectRecv
	errors.Dangerous(c.ShouldBind(&recv))

Y
yubo 已提交
27
	creator := loginUsername(c)
7
3.0.0  
710leo 已提交
28
	for _, obj := range recv {
Y
yubo 已提交
29 30
		cl, err := collector.GetCollector(obj.Type)
		errors.Dangerous(err)
7
3.0.0  
710leo 已提交
31

Y
yubo 已提交
32 33
		if err := cl.Create([]byte(obj.Data), creator); err != nil {
			errors.Bomb("%s add rule err %s", obj.Type, err)
7
3.0.0  
710leo 已提交
34 35 36 37 38 39
		}
	}

	renderData(c, "ok", nil)
}

Y
yubo 已提交
40
func collectRulesGetByLocalEndpoint(c *gin.Context) {
7
3.0.0  
710leo 已提交
41 42 43 44
	collect := scache.CollectCache.GetBy(urlParamStr(c, "endpoint"))
	renderData(c, collect, nil)
}

Y
yubo 已提交
45
func collectRuleGet(c *gin.Context) {
7
3.0.0  
710leo 已提交
46
	t := mustQueryStr(c, "type")
Y
yubo 已提交
47 48 49
	id := mustQueryInt64(c, "id")

	cl, err := collector.GetCollector(t)
7
3.0.0  
710leo 已提交
50 51
	errors.Dangerous(err)

Y
yubo 已提交
52 53
	ret, err := cl.Get(id)
	renderData(c, ret, err)
7
3.0.0  
710leo 已提交
54 55
}

Y
yubo 已提交
56
func collectRulesGet(c *gin.Context) {
7
3.0.0  
710leo 已提交
57 58 59 60 61 62 63 64 65 66 67
	nid := queryInt64(c, "nid", -1)
	tp := queryStr(c, "type", "")
	var resp []interface{}
	var types []string

	if tp == "" {
		types = []string{"port", "proc", "log", "plugin"}
	} else {
		types = []string{tp}
	}

Y
yubo 已提交
68 69 70 71 72 73
	nids := []int64{nid}
	for _, t := range types {
		cl, err := collector.GetCollector(t)
		if err != nil {
			logger.Warning(t, err)
			continue
7
3.0.0  
710leo 已提交
74
		}
Y
yubo 已提交
75 76 77 78 79

		ret, err := cl.Gets(nids)
		if err != nil {
			logger.Warning(t, err)
			continue
7
3.0.0  
710leo 已提交
80
		}
Y
yubo 已提交
81
		resp = append(resp, ret...)
7
3.0.0  
710leo 已提交
82 83 84 85 86
	}

	renderData(c, resp, nil)
}

87 88 89 90 91 92 93 94 95 96 97 98 99
func collectRulesGetV2(c *gin.Context) {
	nid := queryInt64(c, "nid", 0)
	limit := queryInt(c, "limit", 20)
	typ := queryStr(c, "type", "")

	total, list, err := models.GetCollectRules(typ, nid, limit, offset(c, limit, 0))

	renderData(c, map[string]interface{}{
		"total": total,
		"list":  list,
	}, err)
}

Y
yubo 已提交
100
func collectRulePut(c *gin.Context) {
7
3.0.0  
710leo 已提交
101 102 103
	var recv CollectRecv
	errors.Dangerous(c.ShouldBind(&recv))

Y
yubo 已提交
104 105
	cl, err := collector.GetCollector(recv.Type)
	errors.Dangerous(err)
7
3.0.0  
710leo 已提交
106

Y
yubo 已提交
107 108 109
	creator := loginUsername(c)
	if err := cl.Update([]byte(recv.Data), creator); err != nil {
		errors.Bomb("%s update rule err %s", recv.Type, err)
7
3.0.0  
710leo 已提交
110 111 112 113 114 115 116 117 118
	}
	renderData(c, "ok", nil)
}

type CollectsDelRev struct {
	Type string  `json:"type"`
	Ids  []int64 `json:"ids"`
}

Y
yubo 已提交
119
func collectsRuleDel(c *gin.Context) {
7
3.0.0  
710leo 已提交
120 121 122
	var recv []CollectsDelRev
	errors.Dangerous(c.ShouldBind(&recv))

Y
yubo 已提交
123 124
	username := loginUsername(c)
	for _, obj := range recv {
7
3.0.0  
710leo 已提交
125
		for i := 0; i < len(obj.Ids); i++ {
Y
yubo 已提交
126
			cl, err := collector.GetCollector(obj.Type)
7
3.0.0  
710leo 已提交
127 128
			errors.Dangerous(err)

Y
yubo 已提交
129
			if err := cl.Delete(obj.Ids[i], username); err != nil {
7
3.0.0  
710leo 已提交
130 131 132 133 134 135 136 137
				errors.Dangerous(err)
			}
		}
	}

	renderData(c, "ok", nil)
}

Y
yubo 已提交
138 139 140 141 142 143 144 145 146
func collectRuleTypesGet(c *gin.Context) {
	category := mustQueryStr(c, "category")
	switch category {
	case "remote":
		renderData(c, collector.GetRemoteCollectors(), nil)
	case "local":
		renderData(c, collector.GetLocalCollectors(), nil)
	default:
		renderData(c, nil, nil)
7
3.0.0  
710leo 已提交
147 148 149
	}
}

Y
yubo 已提交
150 151 152 153
func collectRuleTemplateGet(c *gin.Context) {
	t := urlParamStr(c, "type")
	collector, err := collector.GetCollector(t)
	errors.Dangerous(err)
7
3.0.0  
710leo 已提交
154

Y
yubo 已提交
155 156
	tpl, err := collector.Template()
	renderData(c, tpl, err)
7
3.0.0  
710leo 已提交
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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
}

type RegExpCheckDto struct {
	Success bool                `json:"success"`
	Data    []map[string]string `json:"tags"`
}

var RegExpExcludePatition string = "```EXCLUDE```"

func regExpCheck(c *gin.Context) {
	param := make(map[string]string, 0)
	errors.Dangerous(c.ShouldBind(&param))

	ret := &RegExpCheckDto{
		Success: true,
		Data:    make([]map[string]string, 0),
	}

	// 处理时间格式
	if t, ok := param["time"]; !ok || t == "" {
		tmp := map[string]string{"time": "time参数不存在或为空"}
		ret.Data = append(ret.Data, tmp)
	} else {
		timePat, _ := GetPatAndTimeFormat(param["time"])
		if timePat == "" {
			tmp := map[string]string{"time": genErrMsg("时间格式")}
			ret.Data = append(ret.Data, tmp)
		} else {
			suc, tRes, _ := checkRegPat(timePat, param["log"], true)
			if !suc {
				ret.Success = false
				tRes = genErrMsg("时间格式")
			}
			tmp := map[string]string{"time": tRes}
			ret.Data = append(ret.Data, tmp)
		}
	}

	// 计算方式
	calc_method, _ := param["calc_method"]

	// 处理主正则(with exclude)
	if re, ok := param["re"]; !ok || re == "" {
		tmp := map[string]string{"re": "re参数不存在或为空"}
		ret.Data = append(ret.Data, tmp)
	} else {
		// 处理exclude的情况
		exclude := ""
		if strings.Contains(re, RegExpExcludePatition) {
			l := strings.Split(re, RegExpExcludePatition)
			if len(l) >= 2 {
				param["re"] = l[0]
				exclude = l[1]
			}
		}

		// 匹配主正则
		suc, reRes, isSub := checkRegPat(param["re"], param["log"], false)
		if !suc {
			ret.Success = false
			reRes = genErrMsg("主正则")
		}
		if calc_method != "" && calc_method != "cnt" && !isSub {
			ret.Success = false
			reRes = genSubErrMsg("主正则")
		}
		tmp := map[string]string{"主正则": reRes}
		ret.Data = append(ret.Data, tmp)

		// 匹配exclude, 这个不影响失败
		if exclude != "" {
			suc, exRes, _ := checkRegPat(exclude, param["log"], false)
			if !suc {
				//ret.Success = false
				exRes = "未匹配到排除串,请检查是否符合预期"
			}
			tmp := map[string]string{"排除串": exRes}
			ret.Data = append(ret.Data, tmp)
		}
	}

	// 处理tags
	var nonTagKey = map[string]bool{
		"re":          true,
		"log":         true,
		"time":        true,
		"calc_method": true,
	}

	for tagk, pat := range param {
		// 如果不是tag,就继续循环
		if _, ok := nonTagKey[tagk]; ok {
			continue
		}
		suc, tagRes, isSub := checkRegPat(pat, param["log"], false)
		if !suc {
			// 正则错误
			ret.Success = false
			tagRes = genErrMsg(tagk)
		} else if !isSub {
			// 未匹配出子串
			ret.Success = false
			tagRes = genSubErrMsg(tagk)
		} else if includeIllegalChar(tagRes) || includeIllegalChar(tagk) {
			// 保留字报错
			ret.Success = false
			tagRes = genIllegalCharErrMsg()
		}

		tmp := map[string]string{tagk: tagRes}
		ret.Data = append(ret.Data, tmp)
	}

	renderData(c, ret, nil)
}

//根据配置的时间格式,获取对应的正则匹配pattern和time包用的时间格式
func GetPatAndTimeFormat(tf string) (string, string) {
	var pat, timeFormat string
	switch tf {
	case "dd/mmm/yyyy:HH:MM:SS":
		pat = `([012][0-9]|3[01])/[JFMASOND][a-z]{2}/(2[0-9]{3}):([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "02/Jan/2006:15:04:05"
	case "dd/mmm/yyyy HH:MM:SS":
		pat = `([012][0-9]|3[01])/[JFMASOND][a-z]{2}/(2[0-9]{3})\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "02/Jan/2006 15:04:05"
	case "yyyy-mm-ddTHH:MM:SS":
		pat = `(2[0-9]{3})-(0[1-9]|1[012])-([012][0-9]|3[01])T([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "2006-01-02T15:04:05"
	case "dd-mmm-yyyy HH:MM:SS":
		pat = `([012][0-9]|3[01])-[JFMASOND][a-z]{2}-(2[0-9]{3})\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "02-Jan-2006 15:04:05"
	case "yyyy-mm-dd HH:MM:SS":
		pat = `(2[0-9]{3})-(0[1-9]|1[012])-([012][0-9]|3[01])\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "2006-01-02 15:04:05"
	case "yyyy/mm/dd HH:MM:SS":
		pat = `(2[0-9]{3})/(0[1-9]|1[012])/([012][0-9]|3[01])\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "2006/01/02 15:04:05"
	case "yyyymmdd HH:MM:SS":
		pat = `(2[0-9]{3})(0[1-9]|1[012])([012][0-9]|3[01])\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "20060102 15:04:05"
	case "mmm dd HH:MM:SS":
		pat = `[JFMASOND][a-z]{2}\s+([1-9]|[1-2][0-9]|3[01])\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "Jan 2 15:04:05"
	case "mmdd HH:MM:SS":
		pat = `(0[1-9]|1[012])([012][0-9]|3[01])\s([01][0-9]|2[0-4])(:[012345][0-9]){2}`
		timeFormat = "0102 15:04:05"
	default:
		logger.Errorf("match time pac failed : [timeFormat:%s]", tf)
		return "", ""
	}
	return pat, timeFormat
}

// 出错信息直接放在body里
func checkRegPat(pat string, log string, origin bool) (succ bool, result string, isSub bool) {
	if pat == "" {
		return false, "", false
	}

	reg, err := regexp.Compile(pat)
	if err != nil {
		return false, "", false
	}

	res := reg.FindStringSubmatch(log)
	switch len(res) {
	// 没查到
	case 0:
		return false, "", false
	// 没查到括号内的串,返回整个匹配串
	case 1:
		return true, res[0], false
	// 查到了,默认取第一个串
	default:
		var msg string
		if origin {
			msg = res[0]
			isSub = false
		} else {
			msg = res[1]
			isSub = true
		}
		return true, msg, isSub
	}
}

func includeIllegalChar(s string) bool {
	illegalChars := ":,=\r\n\t"
	return strings.ContainsAny(s, illegalChars)
}

// 生成返回错误信息
func genErrMsg(sign string) string {
	return fmt.Sprintf("正则匹配失败,请认真检查您[%s]的配置", sign)
}

// 生成子串匹配错误信息
func genSubErrMsg(sign string) string {
	return fmt.Sprintf("正则匹配成功。但根据配置,并没有获取到()内的子串,请认真检查您[%s]的配置", sign)
}

// 生成子串匹配错误信息
func genIllegalCharErrMsg() string {
	return fmt.Sprintf(`正则匹配成功。但是tag的key或者value包含非法字符:[:,/=\r\n\t], 请重新调整`)
}
Y
yubo 已提交
363 364 365 366 367 368

func collectRulesGetByRemoteEndpoint(c *gin.Context) {
	rules := scache.CollectRuleCache.GetBy(urlParamStr(c, "endpoint"))
	renderData(c, rules, nil)

}