github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/cfghandler/pqsupdate.go (about) 1 package cfghandler 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 8 "github.com/siglens/siglens/pkg/config" 9 "github.com/siglens/siglens/pkg/querytracker" 10 log "github.com/sirupsen/logrus" 11 "github.com/valyala/fasthttp" 12 ) 13 14 type PqsConfig struct { 15 PQSEnabled bool `json:"pqsEnabled"` 16 } 17 18 func GetPqsEnabled(ctx *fasthttp.RequestCtx) { 19 // Read the value from the runmod config file, but if that doesn't exist, 20 // read the value from the config file. 21 var pqsEnabled bool 22 runModConfig, err := config.ReadRunModConfig(config.RunModFilePath) 23 if err != nil { 24 log.Infof("GetPqsEnabled:Error reading runmod config: %v", err) 25 pqsEnabled = config.IsPQSEnabled() 26 } else { 27 pqsEnabled = runModConfig.PQSEnabled 28 } 29 30 ctx.SetStatusCode(fasthttp.StatusOK) 31 ctx.SetContentType("application/json") 32 _, err = ctx.WriteString(`{"pqsEnabled":` + fmt.Sprintf("%v", pqsEnabled) + `}`) 33 if err != nil { 34 log.Errorf("GetPqsEnabled:Error writing response: %v", err) 35 ctx.SetStatusCode(fasthttp.StatusInternalServerError) 36 return 37 } 38 } 39 40 func PostPqsUpdate(ctx *fasthttp.RequestCtx) { 41 var cfg PqsConfig 42 err := json.Unmarshal(ctx.PostBody(), &cfg) 43 if err != nil { 44 log.Errorf("PostPqsUpdate:Error parsing request body: %v", err) 45 ctx.Error("Bad Request", fasthttp.StatusBadRequest) 46 return 47 } 48 if err := SavePQSConfigToRunMod(config.RunModFilePath, cfg.PQSEnabled); err != nil { 49 log.Errorf("PostPqsUpdate:Error saving pqsEnabled: %v", err) 50 51 ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError) 52 return 53 } 54 55 ctx.SetStatusCode(fasthttp.StatusOK) 56 ctx.SetContentType("application/json") 57 _, err = ctx.WriteString(`{"status":"success"}`) 58 if err != nil { 59 log.Errorf("PostPqsUpdate:Error writing response: %v", err) 60 return 61 62 } 63 } 64 func SavePQSConfigToRunMod(filepath string, pqsEnabled bool) error { 65 file, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY, 0666) 66 if err != nil { 67 log.Errorf("SavePQSConfigToRunMod:Failed to open or create the file %s: %v", filepath, err) 68 return err 69 } 70 defer file.Close() 71 configData := map[string]bool{"PQSEnabled": pqsEnabled} 72 encoder := json.NewEncoder(file) 73 74 err = encoder.Encode(configData) 75 if err != nil { 76 log.Errorf("SavePQSConfigToRunMod:Failed to encode JSON data to file %s: %v", filepath, err) 77 return err 78 } 79 80 if !pqsEnabled { 81 querytracker.ClearPqs() 82 } 83 84 return nil 85 }