Semaphore/api/tasks/tasks.go

107 lines
2.5 KiB
Go
Raw Permalink Normal View History

2024-10-13 17:50:56 +02:00
package tasks
import (
"github.com/ansible-semaphore/semaphore/pkg/task_logger"
2024-10-13 17:50:56 +02:00
"net/http"
"github.com/ansible-semaphore/semaphore/api/helpers"
"github.com/ansible-semaphore/semaphore/db"
task2 "github.com/ansible-semaphore/semaphore/services/tasks"
"github.com/gorilla/context"
)
func TaskMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2024-10-13 18:46:01 +02:00
taskID, err := helpers.GetIntParam("task_id", w, r)
2024-10-13 17:50:56 +02:00
if err != nil {
helpers.WriteErrorStatus(w, err.Error(), http.StatusBadRequest)
}
context.Set(r, "task_id", taskID)
next.ServeHTTP(w, r)
})
}
type taskLocation string
const (
taskQueue taskLocation = "queue"
taskRunning taskLocation = "running"
)
2024-10-13 17:50:56 +02:00
type taskRes struct {
TaskID int `json:"task_id"`
ProjectID int `json:"project_id"`
Username string `json:"username,omitempty"`
RunnerID int `json:"runner_id,omitempty"`
Status task_logger.TaskStatus `json:"status"`
Location taskLocation `json:"location"`
RunnerName string `json:"runner_name,omitempty"`
ProjectName string `json:"project_name,omitempty"`
2024-10-13 17:50:56 +02:00
}
func GetTasks(w http.ResponseWriter, r *http.Request) {
pool := context.Get(r, "task_pool").(*task2.TaskPool)
res := []taskRes{}
2024-10-13 17:50:56 +02:00
for _, task := range pool.Queue {
res = append(res, taskRes{
TaskID: task.Task.ID,
ProjectID: task.Task.ProjectID,
RunnerID: task.RunnerID,
Username: task.Username,
Status: task.Task.Status,
Location: taskQueue,
2024-10-13 17:50:56 +02:00
})
}
for _, task := range pool.RunningTasks {
res = append(res, taskRes{
TaskID: task.Task.ID,
ProjectID: task.Task.ProjectID,
RunnerID: task.RunnerID,
Username: task.Username,
Status: task.Task.Status,
Location: taskRunning,
2024-10-13 17:50:56 +02:00
})
}
helpers.WriteJSON(w, http.StatusOK, res)
}
func DeleteTask(w http.ResponseWriter, r *http.Request) {
2024-10-13 18:46:01 +02:00
taskID := context.Get(r, "task_id").(int)
2024-10-13 17:50:56 +02:00
pool := context.Get(r, "task_pool").(*task2.TaskPool)
2024-10-13 18:46:01 +02:00
var task *db.Task
2024-10-13 17:50:56 +02:00
for _, t := range pool.Queue {
if t.Task.ID == taskID {
2024-10-13 18:46:01 +02:00
task = &t.Task
2024-10-13 17:50:56 +02:00
break
}
}
if task == nil {
for _, t := range pool.RunningTasks {
if t.Task.ID == taskID {
task = &t.Task
break
}
}
}
2024-10-13 18:46:01 +02:00
if task != nil {
err := pool.StopTask(*task, false)
if err != nil {
helpers.WriteErrorStatus(w, err.Error(), http.StatusInternalServerError)
return
}
2024-10-13 18:46:01 +02:00
}
helpers.WriteJSON(w, http.StatusNoContent, nil)
2024-10-13 17:50:56 +02:00
}