func TestCreateUpdateTask(t *testing.T) { task := kapacitor.Task{ Id: stat, Type: "batch", Database: database, RetentionPolicy: retentionPolicy, Script: kapacitor.GenBatchTick(stat, database, retentionPolicy, measurement, where, period, every, alerts, post), Status: "enabled", } err := kapacitor.SetTask(task) if err != nil { t.Errorf("Failed to add task - %v", err) } // to make work with repo update from 4767348... TO 3003b83... // requires using kapacitord 1.0.0-beta or nightlies. task.Status = "disabled" err = kapacitor.SetTask(task) if err != nil { t.Errorf("Failed to update task - %v", err) } task.Status = "" err = kapacitor.SetTask(task) if err != nil { t.Errorf("Failed to test task status blank - %v", err) } task.Status = "bad" err = kapacitor.SetTask(task) if err == nil { t.Error("Failed to fail bad task status") } task.Type = "stream" err = kapacitor.SetTask(task) if err == nil { t.Errorf("Failed to fail add stream task - %v", err) } task.Type = "bad" err = kapacitor.SetTask(task) if err == nil { t.Errorf("Failed to fail add bad task type - %v", err) } }
// add or update a kapacitor task func setAlert(res http.ResponseWriter, req *http.Request) { var alert kapacitor.Alert err := parseBody(req, &alert) if err != nil { writeBody(apiError{ErrorString: err.Error()}, res, http.StatusBadRequest, req) return } // verify we have enough info if alert.Metric == "" || alert.Post == "" { writeBody(apiError{ErrorString: "Missing value in payload"}, res, http.StatusBadRequest, req) return } // set sane defaults if alert.Level == "" { alert.Level = "crit" } if alert.Duration == "" { alert.Duration = "5m" } lambda := map[string]string{alert.Level: fmt.Sprintf("\"mean_%s\" > %d", alert.Metric, alert.Threshold)} task := kapacitor.Task{ // todo: make id more unique, for use with same stat, multiple tags Id: alert.Metric, Type: "batch", Database: "statistics", RetentionPolicy: "one_day", Script: kapacitor.GenBatchTick(alert.Metric, "statistics", "one_day", alert.Metric, alert.Tags, alert.Duration, "30s", lambda, alert.Post), Status: "enabled", } err = kapacitor.SetTask(task) if err != nil { writeBody(apiError{ErrorString: err.Error()}, res, http.StatusBadRequest, req) return } writeBody(alert, res, http.StatusOK, req) }