func configPushRoutes() { http.HandleFunc("/v1/push", func(w http.ResponseWriter, req *http.Request) { if req.ContentLength == 0 { http.Error(w, "body is blank", http.StatusBadRequest) return } decoder := json.NewDecoder(req.Body) var metrics []*model.MetricValue err := decoder.Decode(&metrics) if err != nil { http.Error(w, "connot decode body", http.StatusBadRequest) return } g.SendToTransfer(metrics) w.Write([]byte("success")) }) }
func collect(sec int64, fns []func() []*model.MetricValue) { t := time.NewTicker(time.Second * time.Duration(sec)).C for { <-t hostname, err := g.Hostname() if err != nil { continue } mvs := []*model.MetricValue{} ignoreMetrics := g.Config().IgnoreMetrics for _, fn := range fns { items := fn() if items == nil { continue } if len(items) == 0 { continue } for _, mv := range items { if b, ok := ignoreMetrics[mv.Metric]; ok && b { continue } else { mvs = append(mvs, mv) } } } now := time.Now().Unix() for j := 0; j < len(mvs); j++ { mvs[j].Step = sec mvs[j].Endpoint = hostname mvs[j].Timestamp = now } g.SendToTransfer(mvs) } }
func PluginRun(plugin *Plugin) { timeout := plugin.Cycle*1000 - 500 fpath := filepath.Join(g.Config().Plugin.Dir, plugin.FilePath) if !file.IsExist(fpath) { log.Println("no such plugin:", fpath) return } debug := g.Config().Debug if debug { log.Println(fpath, "running...") } cmd := exec.Command(fpath) var stdout bytes.Buffer cmd.Stdout = &stdout var stderr bytes.Buffer cmd.Stderr = &stderr cmd.Start() err, isTimeout := sys.CmdRunWithTimeout(cmd, time.Duration(timeout)*time.Millisecond) errStr := stderr.String() if errStr != "" { logFile := filepath.Join(g.Config().Plugin.LogDir, plugin.FilePath+".stderr.log") if _, err = file.WriteString(logFile, errStr); err != nil { log.Printf("[ERROR] write log to %s fail, error: %s\n", logFile, err) } } if isTimeout { // has be killed if err == nil && debug { log.Println("[INFO] timeout and kill process", fpath, "successfully") } if err != nil { log.Println("[ERROR] kill process", fpath, "occur error:", err) } return } if err != nil { log.Println("[ERROR] exec plugin", fpath, "fail. error:", err) return } // exec successfully data := stdout.Bytes() if len(data) == 0 { if debug { log.Println("[DEBUG] stdout of", fpath, "is blank") } return } var metrics []*model.MetricValue err = json.Unmarshal(data, &metrics) if err != nil { log.Printf("[ERROR] json.Unmarshal stdout of %s fail. error:%s stdout: \n%s\n", fpath, err, stdout.String()) return } // fill in fields sec := plugin.Cycle now := time.Now().Unix() hostname, err := g.Hostname() if err != nil { hostname = "" } for j := 0; j < len(metrics); j++ { metrics[j].Step = int64(sec) metrics[j].Endpoint = hostname metrics[j].Timestamp = now } g.SendToTransfer(metrics) }