test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. //"reflect"
  4. "bytes"
  5. "fmt"
  6. "text/template"
  7. )
  8. //----------------------------------------------
  9. // params: class, bucket, varname=default _DATA
  10. // %s => bucket tmplate value
  11. // %s => ifcond
  12. // %s => bucket value
  13. //----------------------------------------------
  14. //https://stackoverflow.com/questions/22367337/last-item-in-a-template-range
  15. type RuleStru struct{
  16. Class string
  17. Bucket string
  18. VarName string
  19. NickName string
  20. PrintID string
  21. PrintAtTime string
  22. SnmpResult []string // snmpResult0, ...
  23. TmplIndex []string // {{index .value 0}} , ...
  24. }
  25. //-------------------------------------------------------------------------------------------------
  26. // bucket2rule -class "class1, class2" -tmpl "myrule.tmpl" -type "etcd"/"file" -out "/opt/syslog"
  27. //-------------------------------------------------------------------------------------------------
  28. func main() {
  29. myrule := `{{$VAR := .VarName}}
  30. --class = {{.Class}}
  31. --parser = json
  32. --fields = {{.VarName}}
  33. --mqltmpl= insert into {{.Class}} (id, {{.Bucket}}) values ('{{.PrintID}}', [{{range $i, $e := .TmplIndex}} {{if $i}},{{end}} {{.}} {{end}}]) at '{{.PrintAtTime}}'
  34. --ignore = false
  35. log.info("{{.Bucket}}_{{.NickName}} start...")
  36. if {{range $i, $e := .SnmpResult}} {{if $i}} AND {{end}} {{$VAR}}["{{.}}"] ~= nil {{end}} then
  37. _id = "{{.NickName}}:" ..{{.VarName}}["IPaddress"]
  38. _values = { {{range $i, $e := .SnmpResult}} {{if $i}}, {{end}} {{$VAR}}["{{.}}"] {{end}} }
  39. _attime = {{.VarName}}["tasktime"]
  40. else
  41. _IGNORE = true
  42. end
  43. `
  44. 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}}`}}
  45. t := template.Must(template.New("abc").Parse(myrule))
  46. buf := &bytes.Buffer{}
  47. if err := t.Execute(buf, rs) ; err != nil {
  48. fmt.Println(err)
  49. }else{
  50. fmt.Println( buf.String() )
  51. }
  52. }