<commit_before>package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/buoyantio/slow_cooker/load"
	restful "github.com/emicklei/go-restful"
	"github.com/golang/glog"
)

const (
	RUNNING_STATE  = "running"
	FINISHED_STATE = "finished"
	FAILED_STATE   = "failed"
)

type BenchmarkState struct {
	Id      string                  `json:"id"`
	Error   string                  `json:"error"`
	State   string                  `json:"state"`
	Results []*load.BenchmarkRecord `json:"results"`
}

type CalibrationState struct {
	Id          string                    `json:"id"`
	Results     []*load.CalibrationRecord `json:"results"`
	FinalResult *load.CalibrationRecord   `json:"finalResult"`
	Error       string                    `json:"error"`
	State       string                    `json:"state"`
}

type Server struct {
	Benchmarks   map[string]*BenchmarkState
	Calibrations map[string]*CalibrationState
	Port         int
	mutex        sync.Mutex
}

func NewServer(serverPort int) *Server {
	server := &Server{
		Port:         serverPort,
		Benchmarks:   make(map[string]*BenchmarkState),
		Calibrations: make(map[string]*CalibrationState),
	}
	newRestfulService(server)
	return server
}

func (server *Server) Run() {
	log.Printf("Server is start and running on port :%v", server.Port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", server.Port), nil))
}

// NewRestfulService : WebServer
func newRestfulService(server *Server) {
	service := new(restful.WebService)
	service.Path("/slowcooker").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON)
	service.Route(service.POST("/benchmark/{RunId}").To(server.RunBenchmark))
	service.Route(service.GET("/benchmark/{RunId}").To(server.GetBenchmarkRunningState))
	service.Route(service.POST("/calibrate/{RunId}").To(server.RunCalibration))
	service.Route(service.GET("/calibrate/{RunId}").To(server.GetCalibrateRunningState))
	restful.Add(service)
}

func max(a int, b int) int {
	if a > b {
		return a
	}

	return b
}

// RunTest : Run test
func (server *Server) RunBenchmark(request *restful.Request, response *restful.Response) {
	loadRequest := load.BenchmarkRequest{}
	err := request.ReadEntity(&loadRequest)
	if err != nil {
		response.WriteError(http.StatusBadRequest, errors.New("Unable to read benchmark request: "+err.Error()))
		return
	}

	id := request.PathParameter("RunId")
	if id == "" {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Benchmark ID not provided"))
		return
	}

	server.mutex.Lock()
	defer server.mutex.Unlock()

	if _, ok := server.Benchmarks[id]; !ok {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Task exist"))
		return
	}

	state := &BenchmarkState{Id: id, State: RUNNING_STATE}
	server.Benchmarks[id] = state

	loadDuration, err := time.ParseDuration(loadRequest.LoadTime)
	if err != nil {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Unable to parse load time: "+err.Error()))
		return
	}

	go func() {
		for i := 0; i < max(1, loadRequest.RunsPerIntensity); i++ {
			go func() {
				loadRequest.AppLoad.Run()
			}()

			<-time.After(loadDuration)
			loadRequest.AppLoad.Stop()<commit_msg>Fix benchmark task checking<commit_after>package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/buoyantio/slow_cooker/load"
	restful "github.com/emicklei/go-restful"
	"github.com/golang/glog"
)

const (
	RUNNING_STATE  = "running"
	FINISHED_STATE = "finished"
	FAILED_STATE   = "failed"
)

type BenchmarkState struct {
	Id      string                  `json:"id"`
	Error   string                  `json:"error"`
	State   string                  `json:"state"`
	Results []*load.BenchmarkRecord `json:"results"`
}

type CalibrationState struct {
	Id          string                    `json:"id"`
	Results     []*load.CalibrationRecord `json:"results"`
	FinalResult *load.CalibrationRecord   `json:"finalResult"`
	Error       string                    `json:"error"`
	State       string                    `json:"state"`
}

type Server struct {
	Benchmarks   map[string]*BenchmarkState
	Calibrations map[string]*CalibrationState
	Port         int
	mutex        sync.Mutex
}

func NewServer(serverPort int) *Server {
	server := &Server{
		Port:         serverPort,
		Benchmarks:   make(map[string]*BenchmarkState),
		Calibrations: make(map[string]*CalibrationState),
	}
	newRestfulService(server)
	return server
}

func (server *Server) Run() {
	log.Printf("Server is start and running on port :%v", server.Port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", server.Port), nil))
}

// NewRestfulService : WebServer
func newRestfulService(server *Server) {
	service := new(restful.WebService)
	service.Path("/slowcooker").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON)
	service.Route(service.POST("/benchmark/{RunId}").To(server.RunBenchmark))
	service.Route(service.GET("/benchmark/{RunId}").To(server.GetBenchmarkRunningState))
	service.Route(service.POST("/calibrate/{RunId}").To(server.RunCalibration))
	service.Route(service.GET("/calibrate/{RunId}").To(server.GetCalibrateRunningState))
	restful.Add(service)
}

func max(a int, b int) int {
	if a > b {
		return a
	}

	return b
}

// RunTest : Run test
func (server *Server) RunBenchmark(request *restful.Request, response *restful.Response) {
	loadRequest := load.BenchmarkRequest{}
	err := request.ReadEntity(&loadRequest)
	if err != nil {
		response.WriteError(http.StatusBadRequest, errors.New("Unable to read benchmark request: "+err.Error()))
		return
	}

	id := request.PathParameter("RunId")
	if id == "" {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Benchmark ID not provided"))
		return
	}

	server.mutex.Lock()
	defer server.mutex.Unlock()

	if _, ok := server.Benchmarks[id]; ok {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Task %s already exist", id))
		return
	}

	state := &BenchmarkState{Id: id, State: RUNNING_STATE}
	server.Benchmarks[id] = state

	loadDuration, err := time.ParseDuration(loadRequest.LoadTime)
	if err != nil {
		response.WriteError(http.StatusBadRequest, fmt.Errorf("Unable to parse load time: %s", err.Error()))
		return
	}

	go func() {
		for i := 0; i < max(1, loadRequest.RunsPerIntensity); i++ {
			go func() {
				loadRequest.AppLoad.Run()
			}()

			<-time.After(loadDuration)
			loadRequest.AppLoad.Stop()
{'fraction_non_alphanumeric': 0.14052856464630478, 'fraction_numerical': 0.0006330115524608325, 'mean_word_length': 3.876543209876543, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7071922', 'n_tokens_mistral': 2205, 'n_tokens_neox': 2115, 'n_words': 410}