| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package main
-
- import (
- //"reflect"
- "bytes"
- "fmt"
- "text/template"
- )
- //----------------------------------------------
- // params: class, bucket, varname=default _DATA
- // %s => bucket tmplate value
- // %s => ifcond
- // %s => bucket value
- //----------------------------------------------
- //https://stackoverflow.com/questions/22367337/last-item-in-a-template-range
- type RuleStru struct{
- Class string
- Bucket string
- VarName string
-
- NickName string
- PrintID string
- PrintAtTime string
- SnmpResult []string // snmpResult0, ...
- TmplIndex []string // {{index .value 0}} , ...
- }
- //-------------------------------------------------------------------------------------------------
- // bucket2rule -class "class1, class2" -tmpl "myrule.tmpl" -type "etcd"/"file" -out "/opt/syslog"
- //-------------------------------------------------------------------------------------------------
- func main() {
- myrule := `{{$VAR := .VarName}}
- --class = {{.Class}}
- --parser = json
- --fields = {{.VarName}}
- --mqltmpl= insert into {{.Class}} (id, {{.Bucket}}) values ('{{.PrintID}}', [{{range $i, $e := .TmplIndex}} {{if $i}},{{end}} {{.}} {{end}}]) at '{{.PrintAtTime}}'
- --ignore = false
- log.info("{{.Bucket}}_{{.NickName}} start...")
- if {{range $i, $e := .SnmpResult}} {{if $i}} AND {{end}} {{$VAR}}["{{.}}"] ~= nil {{end}} then
- _id = "{{.NickName}}:" ..{{.VarName}}["IPaddress"]
- _values = { {{range $i, $e := .SnmpResult}} {{if $i}}, {{end}} {{$VAR}}["{{.}}"] {{end}} }
- _attime = {{.VarName}}["tasktime"]
- else
- _IGNORE = true
- end
- `
- rs := RuleStru{Class: "/matrix/devops/node", Bucket: "cpu_perf", VarName: "_DATA", NickName: "node", PrintID: `{{.id}}`, PrintAtTime:`{{.attime}}`, SnmpResult: []string{"snmpResult0", "snmpResult1"} , TmplIndex: []string{`{{index .value 0}}`, `{{index .value 1}}`}}
-
- t := template.Must(template.New("abc").Parse(myrule))
-
- buf := &bytes.Buffer{}
- if err := t.Execute(buf, rs) ; err != nil {
- fmt.Println(err)
- }else{
- fmt.Println( buf.String() )
- }
- }
|