Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion core/http/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ func API(application *application.Application) (*echo.Echo, error) {
}
})

//Job tracking middleware (Fix for #7906)
e.Use(httpMiddleware.JobTracker())

// Recover middleware
if !application.ApplicationConfig().Debug {
e.Use(middleware.Recover())
Expand Down Expand Up @@ -222,7 +225,7 @@ func API(application *application.Application) (*echo.Echo, error) {
routes.RegisterUIRoutes(e, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig(), application.GalleryService())
}
routes.RegisterJINARoutes(e, requestExtractor, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig())

routes.RegisterJobRoutes(e)
// Note: 404 handling is done via HTTPErrorHandler above, no need for catch-all route

// Log startup message
Expand Down
85 changes: 85 additions & 0 deletions core/http/jobs/store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package jobs

import (
"sync"
"time"

"github.com/google/uuid"
)

//A task running in LocalAI
type Job struct{
ID string `json:"job_id"`
Type string `json:"type"`
Model string `json:"model"`
StartTime time.Time `json:"start_time"`
Status string `json:"status"`
ClientIP string `json:"client_ip"`
}

//All jobs
type JobStore struct{
jobs map[string]*Job
mu sync.RWMutex
}

var currentStore *JobStore
var once sync.Once

//Return singleton instance of the JobStore
func GetStore() *JobStore{
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks basically superseded by https://github.com/mudler/LocalAI/blob/master/core/http/middleware/trace.go which is used to trace instead any requests (useful for dataset extraction).

@pmarini-nc, wouldn't the current tracing feature already satisfy your issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mudler I have analyzed core/http/middleware/trace.go.
While trace.go is excellent for historical analysis and debugging, it captures the APIExchange after the request handler returns (Lines 100-125).

Why this PR is distinct and necessary:
The goal of issue #7906 is to have a "top-like" monitoring view. The key requirement is to see jobs while they are executing (e.g., long-running inference or downloads).

Trace: Shows what happened (Past tense).
Job Monitor: Shows what is happening (Present tense).

If we use trace.go, the API user won't see the job until it is already finished, which defeats the purpose of monitoring live resource usage.
This PR inserts the job into the store before next(c) is called, allowing real-time visibility into running processes. I believe keeping this lightweight "Active Job Store" separate from the heavy "Historical Trace Buffer" is the cleanest approach.

once.Do(func(){
currentStore=&JobStore{
jobs: make(map[string]*Job),
}
})
return currentStore
}

//Add new job to the store
func (s *JobStore) AddJob(j *Job){
s.mu.Lock()
defer s.mu.Unlock()
s.jobs[j.ID]=j
}

//Return specific job
func (s *JobStore) GetJob(id string) *Job{
s.mu.RLock()
defer s.mu.RUnlock()
return s.jobs[id]
}

//Return a list of all jobs
func (s *JobStore) GetAllJobs() []*Job{
s.mu.RLock()
defer s.mu.RUnlock()

var list []*Job
for _,job:=range s.jobs{
list=append(list,job)
}
return list
}

//Update status of a job
func (s *JobStore) UpdateStatus(id string,status string){
s.mu.Lock()
defer s.mu.Unlock()

if job,exists:=s.jobs[id]; exists{
job.Status=status
}
}

//Helper function to generate a new job
func CreateJob(jobType,model,clientIP string) *Job{
return &Job{
ID: uuid.New().String(),
Type: jobType,
Model: model,
StartTime: time.Now(),
Status: "executing",
ClientIP: clientIP,
}
}
58 changes: 58 additions & 0 deletions core/http/middleware/job_middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package middleware

import (
"bytes"
"encoding/json"
"io"
"strings"

"github.com/labstack/echo/v4"
"github.com/mudler/LocalAI/core/http/jobs"
)

//Find model name from JSON body
type simpleModelRequest struct{
Model string `json:"model"`
}

//Track jobs by intercepting requests
func JobTracker() echo.MiddlewareFunc{
return func(next echo.HandlerFunc) echo.HandlerFunc{
return func(c echo.Context) error{
req:=c.Request()
urlPath:=req.URL.Path

//Filter
if !strings.HasPrefix(urlPath,"/v1/") && !strings.HasPrefix(urlPath,"/api/"){
return next(c)
}
if strings.Contains(urlPath,"/jobs"){
return next(c)
}

modelName:="unknown"

if req.Method=="POST"{
bodyBytes,_:=io.ReadAll(req.Body)
req.Body=io.NopCloser(bytes.NewBuffer(bodyBytes))

var tmp simpleModelRequest
if err:=json.Unmarshal(bodyBytes,&tmp);err==nil && tmp.Model!=""{
modelName=tmp.Model
}
}
job:=jobs.CreateJob(urlPath,modelName,c.RealIP())
store:=jobs.GetStore()
store.AddJob(job)

err:=next(c)

if err!=nil{
store.UpdateStatus(job.ID,"error")
}else{
store.UpdateStatus(job.ID,"finished")
}
return err
}
}
}
18 changes: 18 additions & 0 deletions core/http/routes/jobs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package routes

import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/mudler/LocalAI/core/http/jobs"
)

func RegisterJobRoutes(e *echo.Echo){
e.GET("/backends/jobs",listJobs)
}

func listJobs(c echo.Context) error{
store:=jobs.GetStore()
runningJobs:=store.GetAllJobs()
return c.JSON(http.StatusOK,runningJobs)
}
Loading