forked from jokeez/hackme
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuzz_pool_sync_worker.go
More file actions
282 lines (264 loc) · 8.05 KB
/
Copy pathfuzz_pool_sync_worker.go
File metadata and controls
282 lines (264 loc) · 8.05 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package main
import (
"context"
"log"
"strings"
"time"
"hackme/internal/fuzzengine"
"hackme/internal/logsafe"
"hackme/internal/poolfuzz"
"hackme/internal/poolsync"
)
type poolSyncJob struct {
campaign fuzzAutoCampaign
title string
desc string
ctype string
}
func (a *app) poolSyncStatusPayload() map[string]any {
snap := poolsync.Snapshot()
failed := a.poolSyncFailedIDs()
pending := int64(0)
if a.poolSyncCh != nil {
pending = int64(len(a.poolSyncCh))
}
snap.PendingCount = pending
return map[string]any{
"metrics": snap,
"failed_campaigns": failed,
"coordinator_url_resolved": poolsync.ResolveCoordinatorURL(),
"async_enabled": poolsync.AsyncEnabled(),
}
}
func (a *app) startPoolSyncWorker() {
a.poolSyncOnce.Do(func() {
a.poolSyncCh = make(chan poolSyncJob, 256)
go a.poolSyncWorkerLoop()
a.startFuzzSettlePullTicker()
go a.retryFailedPoolSyncCampaigns()
go a.reconcilePoolSyncCampaignsLoop()
})
}
// reconcilePoolSyncCampaignsLoop re-queues pool campaigns missing on the coordinator.
func (a *app) reconcilePoolSyncCampaignsLoop() {
time.Sleep(5 * time.Second)
a.reconcilePoolSyncCampaigns()
ticker := time.NewTicker(3 * time.Minute)
defer ticker.Stop()
for range ticker.C {
a.reconcilePoolSyncCampaigns()
}
}
func (a *app) reconcilePoolSyncCampaigns() {
if a == nil || a.db == nil {
return
}
if strings.TrimSpace(poolsync.ResolveCoordinatorURL()) == "" {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
rows, err := a.db.QueryContext(ctx,
`SELECT id, COALESCE(owner_ref,''), budget_runs, budget_seconds, config_json FROM fuzz_campaigns
WHERE status IN ('planned','running')
AND json_extract(config_json, '$.pool_distributed') IN (1, 'true', '1')
ORDER BY created_at DESC LIMIT 64`)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var id, ownerRef, cfgJSON string
var budgetRuns, budgetSec int
if err := rows.Scan(&id, &ownerRef, &budgetRuns, &budgetSec, &cfgJSON); err != nil {
continue
}
id = strings.TrimSpace(id)
if id == "" {
continue
}
if failed := a.poolSyncFailedIDs(); len(failed) > 0 {
if _, ok := failed[id]; ok {
continue
}
}
progCtx, progCancel := context.WithTimeout(ctx, 6*time.Second)
_, ok := a.fetchCoordinatorPoolCampaignProgress(progCtx, id)
progCancel()
if ok {
syncCtx, syncCancel := context.WithTimeout(ctx, 20*time.Second)
if err := a.syncPoolCampaignProgressFromCoordinator(syncCtx, id); err != nil {
log.Printf("pool sync reconcile: %s progress: %v", logsafe.ID(id), err)
}
syncCancel()
continue
}
a.poolSyncMu.Lock()
delete(a.poolSyncQueued, id)
a.poolSyncMu.Unlock()
mode, warn := a.schedulePoolFuzzSync(ctx, fuzzAutoCampaign{
ID: id, OwnerRef: ownerRef, BudgetRuns: budgetRuns, BudgetSeconds: budgetSec, ConfigJSON: cfgJSON,
})
if warn != "" {
log.Printf("pool sync reconcile: %s warn=%s", logsafe.ID(id), logsafe.ID(warn))
} else {
log.Printf("pool sync reconcile: %s mode=%s", logsafe.ID(id), logsafe.ID(mode))
}
}
}
// retryFailedPoolSyncCampaigns re-queues pool campaigns that failed coordinator register.
func (a *app) retryFailedPoolSyncCampaigns() {
time.Sleep(3 * time.Second)
failed := a.poolSyncFailedIDs()
if len(failed) == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
rows, err := a.db.QueryContext(ctx,
`SELECT id, COALESCE(owner_ref,''), budget_runs, budget_seconds, config_json FROM fuzz_campaigns
WHERE status IN ('planned','running')
AND json_extract(config_json, '$.pool_distributed') IN (1, 'true', '1')`)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var id, ownerRef, cfgJSON string
var budgetRuns, budgetSec int
if err := rows.Scan(&id, &ownerRef, &budgetRuns, &budgetSec, &cfgJSON); err != nil {
continue
}
if _, ok := failed[id]; !ok {
continue
}
a.poolSyncMu.Lock()
delete(a.poolSyncQueued, id)
a.poolSyncMu.Unlock()
_, _ = a.schedulePoolFuzzSync(ctx, fuzzAutoCampaign{
ID: id, OwnerRef: ownerRef, BudgetRuns: budgetRuns, BudgetSeconds: budgetSec, ConfigJSON: cfgJSON,
})
log.Printf("pool sync: retry queued for %s", logsafe.ID(id))
}
}
func (a *app) poolSyncWorkerLoop() {
for job := range a.poolSyncCh {
a.runPoolSyncJob(job)
}
}
func (a *app) runPoolSyncJob(job poolSyncJob) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
cfg := parseMapJSON(job.campaign.ConfigJSON)
ctype := strings.TrimSpace(job.ctype)
if ctype == "" {
ctype = "property"
}
// Hunt: upload harness BEFORE registering the campaign so workers never claim
// shards against a missing ASAN binary (yyjson-class lease spin).
if poolfuzz.IsHuntCampaign(cfg) {
if herr := a.syncHuntHarnessToCoordinator(ctx, cfg); herr != nil {
log.Printf("pool sync: campaign %s harness upload failed: %s", logsafe.ID(job.campaign.ID), logsafe.Err(herr))
a.poolSyncMarkFailed(job.campaign.ID, herr)
return
}
}
req := poolsync.RegisterRequest{
ID: job.campaign.ID,
CampaignType: ctype,
Title: job.title,
Description: job.desc,
OwnerRef: job.campaign.OwnerRef,
Status: "running",
BudgetRuns: job.campaign.BudgetRuns,
BudgetSeconds: job.campaign.BudgetSeconds,
Config: cfg,
}
err := poolsync.RegisterWithRetry(ctx, req)
if err != nil {
log.Printf("pool sync: campaign %s failed after retries: %v", logsafe.ID(job.campaign.ID), err)
a.poolSyncMarkFailed(job.campaign.ID, err)
return
}
if fuzzengine.CorpusPersistEnabled(cfg) {
a.syncCorpusNamespaceToCoordinator(ctx, cfg)
}
log.Printf("pool sync: campaign %s registered on coordinator", logsafe.ID(job.campaign.ID))
a.poolSyncMarkOK(job.campaign.ID)
}
func (a *app) poolSyncMarkOK(id string) {
a.poolSyncMu.Lock()
delete(a.poolSyncFailed, id)
a.poolSyncMu.Unlock()
}
func (a *app) poolSyncMarkFailed(id string, err error) {
a.poolSyncMu.Lock()
if a.poolSyncFailed == nil {
a.poolSyncFailed = make(map[string]string)
}
a.poolSyncFailed[id] = err.Error()
a.poolSyncMu.Unlock()
}
func (a *app) poolSyncFailedIDs() map[string]string {
a.poolSyncMu.Lock()
defer a.poolSyncMu.Unlock()
out := make(map[string]string, len(a.poolSyncFailed))
for k, v := range a.poolSyncFailed {
out[k] = v
}
return out
}
func (a *app) schedulePoolFuzzSync(ctx context.Context, c fuzzAutoCampaign) (syncMode string, syncWarning string) {
a.startPoolSyncWorker()
var title, desc, ctype, ownerRef string
_ = a.db.QueryRowContext(ctx,
`SELECT title, description, campaign_type, COALESCE(owner_ref,'') FROM fuzz_campaigns WHERE id=?`, c.ID).
Scan(&title, &desc, &ctype, &ownerRef)
if strings.TrimSpace(c.OwnerRef) == "" {
c.OwnerRef = ownerRef
}
job := poolSyncJob{campaign: c, title: title, desc: desc, ctype: ctype}
// Dedupe: skip if already queued recently (fuzz_runner may call sync repeatedly).
a.poolSyncMu.Lock()
if a.poolSyncQueued == nil {
a.poolSyncQueued = make(map[string]struct{})
}
if _, dup := a.poolSyncQueued[c.ID]; dup {
a.poolSyncMu.Unlock()
return "queued", ""
}
a.poolSyncQueued[c.ID] = struct{}{}
a.poolSyncMu.Unlock()
if poolsync.AsyncEnabled() {
poolsync.RecordQueued(c.ID)
select {
case a.poolSyncCh <- job:
return "queued", ""
default:
// channel full — run in dedicated goroutine so API still returns fast
go func() { a.runPoolSyncJob(job) }()
return "queued", "pool sync queue busy; running in background"
}
}
if err := a.syncPoolFuzzCampaignSync(ctx, c, title, desc, ctype); err != nil {
return "fail", err.Error()
}
return "ok", ""
}
func (a *app) syncPoolFuzzCampaignSync(ctx context.Context, c fuzzAutoCampaign, title, desc, ctype string) error {
cfg := parseMapJSON(c.ConfigJSON)
if ctype == "" {
ctype = "property"
}
return poolsync.RegisterWithRetry(ctx, poolsync.RegisterRequest{
ID: c.ID,
CampaignType: ctype,
Title: title,
Description: desc,
OwnerRef: c.OwnerRef,
Status: "running",
BudgetRuns: c.BudgetRuns,
BudgetSeconds: c.BudgetSeconds,
Config: cfg,
})
}