-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
221 lines (196 loc) · 4.86 KB
/
Copy pathmain.go
File metadata and controls
221 lines (196 loc) · 4.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
log.Println("🚀 Starting Go Job Simulator with Web Dashboard")
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// Initialize worker pool
pool := NewPool(3)
pool.Start(ctx)
// Load unfinished jobs from WAL
jobs := LoadJobsFromWAL()
JobMutex.Lock()
for _, job := range jobs {
jobMap[job.ID] = job
}
JobMutex.Unlock()
for _, job := range jobs {
log.Printf("🔄 Re-queueing job from WAL: %v\n", job)
pool.Submit(job)
}
// Auto job generator
go func() {
jobID := len(jobs) + 1
for {
select {
case <-ctx.Done():
return
case <-time.After(time.Duration(500+randInt(500)) * time.Millisecond):
if autoGeneratorActive {
job := NewJob(jobID)
JobMutex.Lock()
jobMap[jobID] = job
JobMutex.Unlock()
pool.Submit(job)
AppendJobToWAL(job)
jobID++
}
}
}
}()
// Terminal monitor (refresh table every 1.5s)
go monitor(ctx)
// Checkpointer (Compaction)
go func() {
for {
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Second):
Checkpoint()
}
}
}()
// HTTP server
http.Handle("/", http.FileServer(http.Dir("./web")))
http.HandleFunc("/jobs", handleJobSubmit(pool))
http.HandleFunc("/jobs/status", handleJobStatus(pool))
http.HandleFunc("/api/reset", handleReset)
http.HandleFunc("/api/toggle-auto", handleToggleAuto)
http.HandleFunc("/api/jobs/stop", handleJobStop)
http.HandleFunc("/api/pool/resize", handlePoolResize(pool, ctx))
http.HandleFunc("/api/logs", func(w http.ResponseWriter, r *http.Request) {
b, _ := os.ReadFile("jobs.log")
w.Header().Set("Content-Type", "text/plain")
w.Write(b)
})
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
srv := &http.Server{Addr: ":" + port}
go func() {
log.Printf("🌐 Web dashboard listening on :%s\n", port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
<-ctx.Done()
log.Println("⚡ Shutting down gracefully...")
pool.Stop()
srv.Shutdown(context.Background())
log.Println("✅ All workers stopped. Exiting.")
}
func handleJobSubmit(pool *Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var job Job
if err := json.NewDecoder(r.Body).Decode(&job); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
job.Status = Pending
job.Attempts = 0
if job.MaxRetry == 0 {
job.MaxRetry = 3
}
JobMutex.Lock()
jobMap[job.ID] = &job
JobMutex.Unlock()
pool.Submit(&job)
AppendJobToWAL(&job)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(job)
log.Printf("📩 Received job via HTTP: %v\n", job)
}
}
func handleJobStatus(pool *Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
JobMutex.RLock()
statuses := make([]*Job, 0, len(jobMap))
for _, job := range jobMap {
statuses = append(statuses, job)
}
JobMutex.RUnlock()
w.Header().Set("Content-Type", "application/json")
response := map[string]interface{}{
"jobs": statuses,
"auto": autoGeneratorActive,
"poolSize": pool.Size(),
}
json.NewEncoder(w).Encode(response)
}
}
var autoGeneratorActive = true
func handleReset(w http.ResponseWriter, r *http.Request) {
JobMutex.Lock()
jobMap = make(map[int]*Job)
JobMutex.Unlock()
os.WriteFile("jobs.log", []byte(""), 0644)
w.WriteHeader(http.StatusOK)
}
func handleToggleAuto(w http.ResponseWriter, r *http.Request) {
autoGeneratorActive = !autoGeneratorActive
w.WriteHeader(http.StatusOK)
}
func handleJobStop(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req struct {
ID int `json:"id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
JobMutex.RLock()
job, ok := jobMap[req.ID]
JobMutex.RUnlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
JobMutex.Lock()
if job.Status == Running && job.Cancel != nil {
job.Cancel()
}
JobMutex.Unlock()
w.WriteHeader(http.StatusOK)
}
func handlePoolResize(pool *Pool, ctx context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req struct {
Size int `json:"size"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Size > 0 {
pool.Resize(ctx, req.Size)
}
w.WriteHeader(http.StatusOK)
}
}