Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
407 lines (348 loc) · 11.3 KB
/
Copy pathmain.go
File metadata and controls
407 lines (348 loc) · 11.3 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"fmt"
"log/slog"
"math/rand"
"net/http"
_ "net/http/pprof" // Import pprof HTTP handlers
"os"
"runtime"
"strconv"
"sync"
"time"
hosthttp "github.com/Bofry/host-http"
"github.com/Bofry/host-http/response"
)
// Configuration for stress testing scenarios
type Config struct {
EnablePprof bool
PprofPort string
SimulateLoad bool
MemoryIntensive bool
CPUIntensive bool
}
// MemoryLeakRequest demonstrates memory-intensive operations for profiling
type MemoryLeakRequest struct {
data [][]byte
mu sync.Mutex
}
func (r *MemoryLeakRequest) Get(w http.ResponseWriter, req *http.Request) {
sizeParam := req.URL.Query().Get("size")
size := 1024 // Default 1KB
if s, err := strconv.Atoi(sizeParam); err == nil && s > 0 {
size = s
}
// Allocate memory that may not be properly released
r.mu.Lock()
r.data = append(r.data, make([]byte, size*1024)) // size in KB
currentSize := len(r.data)
r.mu.Unlock()
// Force garbage collection to see the effect
var m runtime.MemStats
runtime.ReadMemStats(&m)
response.JSON.Success(w, map[string]any{
"message": "Memory allocated",
"allocated_kb": size,
"total_chunks": currentSize,
"heap_alloc_mb": bToMb(m.HeapAlloc),
"heap_sys_mb": bToMb(m.HeapSys),
"gc_runs": m.NumGC,
"advice": "Use 'go tool pprof http://localhost:6060/debug/pprof/heap' to analyze memory usage",
})
}
func (r *MemoryLeakRequest) Delete(w http.ResponseWriter, req *http.Request) {
r.mu.Lock()
r.data = nil // Clear allocated memory
r.mu.Unlock()
runtime.GC() // Force garbage collection
var m runtime.MemStats
runtime.ReadMemStats(&m)
response.JSON.Success(w, map[string]any{
"message": "Memory cleared",
"heap_alloc_mb": bToMb(m.HeapAlloc),
"heap_sys_mb": bToMb(m.HeapSys),
"gc_runs": m.NumGC,
})
}
// CPUIntensiveRequest demonstrates CPU-intensive operations
type CPUIntensiveRequest struct{}
func (r *CPUIntensiveRequest) Get(w http.ResponseWriter, req *http.Request) {
durationParam := req.URL.Query().Get("duration")
duration := 100 * time.Millisecond // Default duration
if d, err := time.ParseDuration(durationParam); err == nil {
duration = d
}
start := time.Now()
// CPU-intensive calculation
result := r.calculatePrimes(duration)
elapsed := time.Since(start)
response.JSON.Success(w, map[string]any{
"message": "CPU intensive task completed",
"primes_calculated": result,
"duration_ms": elapsed.Milliseconds(),
"requested_ms": duration.Milliseconds(),
"advice": "Use 'go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30' to analyze CPU usage",
})
}
func (r *CPUIntensiveRequest) calculatePrimes(duration time.Duration) int {
start := time.Now()
count := 0
num := 2
for time.Since(start) < duration {
if r.isPrime(num) {
count++
}
num++
}
return count
}
func (r *CPUIntensiveRequest) isPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// GoroutineLeakRequest demonstrates goroutine management issues
type GoroutineLeakRequest struct {
workers []chan struct{}
mu sync.Mutex
}
func (r *GoroutineLeakRequest) Get(w http.ResponseWriter, req *http.Request) {
countParam := req.URL.Query().Get("count")
count := 10 // Default goroutine count
if c, err := strconv.Atoi(countParam); err == nil && c > 0 {
count = c
}
r.mu.Lock()
// Start goroutines that might leak
for i := 0; i < count; i++ {
stop := make(chan struct{})
r.workers = append(r.workers, stop)
go func(id int, stop chan struct{}) {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
// Simulate work
_ = rand.Intn(1000)
}
}
}(i, stop)
}
totalWorkers := len(r.workers)
r.mu.Unlock()
response.JSON.Success(w, map[string]any{
"message": "Goroutines started",
"started_count": count,
"total_workers": totalWorkers,
"goroutines": runtime.NumGoroutine(),
"advice": "Use 'go tool pprof http://localhost:6060/debug/pprof/goroutine' to analyze goroutine usage",
})
}
func (r *GoroutineLeakRequest) Delete(w http.ResponseWriter, req *http.Request) {
r.mu.Lock()
// Stop all goroutines
for _, stop := range r.workers {
close(stop)
}
r.workers = nil
r.mu.Unlock()
// Give time for goroutines to cleanup
time.Sleep(200 * time.Millisecond)
response.JSON.Success(w, map[string]any{
"message": "Goroutines stopped",
"goroutines": runtime.NumGoroutine(),
})
}
// BlockingRequest demonstrates blocking operations
type BlockingRequest struct{}
func (r *BlockingRequest) Get(w http.ResponseWriter, req *http.Request) {
durationParam := req.URL.Query().Get("duration")
duration := 1 * time.Second // Default duration
if d, err := time.ParseDuration(durationParam); err == nil {
duration = d
}
start := time.Now()
// Simulate blocking I/O
time.Sleep(duration)
elapsed := time.Since(start)
response.JSON.Success(w, map[string]any{
"message": "Blocking operation completed",
"duration_ms": elapsed.Milliseconds(),
"advice": "Use 'go tool pprof http://localhost:6060/debug/pprof/block' to analyze blocking operations",
})
}
// ProfileStatsRequest provides runtime statistics
type ProfileStatsRequest struct{}
func (r *ProfileStatsRequest) Get(w http.ResponseWriter, req *http.Request) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
response.JSON.Success(w, map[string]any{
"timestamp": time.Now(),
"memory_stats": map[string]any{
"heap_alloc_mb": bToMb(m.HeapAlloc),
"heap_sys_mb": bToMb(m.HeapSys),
"heap_objects": m.HeapObjects,
"gc_runs": m.NumGC,
"gc_pause_total_ns": m.PauseTotalNs,
},
"runtime_stats": map[string]any{
"goroutines": runtime.NumGoroutine(),
"cpu_count": runtime.NumCPU(),
"gomaxprocs": runtime.GOMAXPROCS(0),
},
"pprof_endpoints": map[string]string{
"heap": "http://localhost:6060/debug/pprof/heap",
"profile": "http://localhost:6060/debug/pprof/profile?seconds=30",
"goroutine": "http://localhost:6060/debug/pprof/goroutine",
"block": "http://localhost:6060/debug/pprof/block",
"mutex": "http://localhost:6060/debug/pprof/mutex",
"allocs": "http://localhost:6060/debug/pprof/allocs",
},
"analysis_commands": map[string]string{
"heap_analysis": "go tool pprof http://localhost:6060/debug/pprof/heap",
"cpu_profile": "go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30",
"goroutine_analysis": "go tool pprof http://localhost:6060/debug/pprof/goroutine",
"blocking_analysis": "go tool pprof http://localhost:6060/debug/pprof/block",
},
})
}
// RequestManager defines all routes
type RequestManager struct {
*MemoryLeakRequest `url:"/memory"`
*CPUIntensiveRequest `url:"/cpu"`
*GoroutineLeakRequest `url:"/goroutines"`
*BlockingRequest `url:"/blocking"`
*ProfileStatsRequest `url:"/stats"`
}
// App with service provider
type App struct{}
func main() {
// Configuration
config := &Config{
EnablePprof: getEnvBool("ENABLE_PPROF", true),
PprofPort: getEnv("PPROF_PORT", "6060"),
SimulateLoad: getEnvBool("SIMULATE_LOAD", false),
MemoryIntensive: getEnvBool("MEMORY_INTENSIVE", false),
CPUIntensive: getEnvBool("CPU_INTENSIVE", false),
}
slog.Info("=== host-http Performance Profiling Demo ===")
slog.Info("This example demonstrates net/http/pprof integration for performance analysis")
slog.Info("")
slog.Info("Configuration",
"pprof_enabled", config.EnablePprof,
"pprof_port", config.PprofPort,
"simulate_load", config.SimulateLoad)
// Start pprof server if enabled
if config.EnablePprof {
go func() {
slog.Info("Starting pprof server", "port", config.PprofPort)
pprofServer := &http.Server{
Addr: ":" + config.PprofPort,
Handler: http.DefaultServeMux, // pprof handlers are registered here
}
if err := pprofServer.ListenAndServe(); err != nil {
slog.Error("pprof server failed", "error", err)
}
}()
slog.Info("pprof endpoints available:")
slog.Info(" http://localhost:" + config.PprofPort + "/debug/pprof/")
slog.Info(" http://localhost:" + config.PprofPort + "/debug/pprof/heap")
slog.Info(" http://localhost:" + config.PprofPort + "/debug/pprof/profile?seconds=30")
slog.Info(" http://localhost:" + config.PprofPort + "/debug/pprof/goroutine")
slog.Info(" http://localhost:" + config.PprofPort + "/debug/pprof/block")
slog.Info("")
}
slog.Info("Performance testing endpoints:")
slog.Info(" GET /memory?size=1024 - Allocate memory (size in KB)")
slog.Info(" DELETE /memory - Free allocated memory")
slog.Info(" GET /cpu?duration=100ms - CPU intensive task")
slog.Info(" GET /goroutines?count=10 - Start goroutines")
slog.Info(" DELETE /goroutines - Stop goroutines")
slog.Info(" GET /blocking?duration=1s - Blocking operation")
slog.Info(" GET /stats - Runtime statistics and pprof commands")
slog.Info("")
if config.EnablePprof {
slog.Info("Analysis commands:")
slog.Info(" # Memory analysis")
slog.Info(" go tool pprof http://localhost:" + config.PprofPort + "/debug/pprof/heap")
slog.Info("")
slog.Info(" # CPU profiling (30 seconds)")
slog.Info(" go tool pprof http://localhost:" + config.PprofPort + "/debug/pprof/profile?seconds=30")
slog.Info("")
slog.Info(" # Goroutine analysis")
slog.Info(" go tool pprof http://localhost:" + config.PprofPort + "/debug/pprof/goroutine")
slog.Info("")
slog.Info(" # Blocking analysis")
slog.Info(" go tool pprof http://localhost:" + config.PprofPort + "/debug/pprof/block")
slog.Info("")
}
// Enable blocking profile
runtime.SetBlockProfileRate(1)
// Start background load simulation if requested
if config.SimulateLoad {
go simulateBackgroundLoad(config)
}
slog.Info("Starting main server on port 8080...")
slog.Info("===============================================")
app := &App{}
// Setup middleware chain
hosthttp.Startup(app).
Middlewares(
hosthttp.UseRequestManager(&RequestManager{}),
hosthttp.UseLogging(),
hosthttp.UseErrorHandler(func(w http.ResponseWriter, r *http.Request, err any) {
slog.Error("Error in request", "method", r.Method, "path", r.URL.Path, "error", err)
response.JSON.Failure(w, map[string]any{
"error": "Internal Server Error",
"message": fmt.Sprintf("%v", err),
"timestamp": time.Now(),
}, http.StatusInternalServerError)
}),
).
Run()
}
// Helper functions
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func getEnvBool(key string, defaultValue bool) bool {
if value := os.Getenv(key); value != "" {
if b, err := strconv.ParseBool(value); err == nil {
return b
}
}
return defaultValue
}
func simulateBackgroundLoad(config *Config) {
slog.Info("Starting background load simulation")
for {
if config.MemoryIntensive {
// Allocate and release memory
data := make([]byte, 1024*1024) // 1MB
_ = data
time.Sleep(500 * time.Millisecond)
}
if config.CPUIntensive {
// CPU intensive calculation
for i := 0; i < 100000; i++ {
_ = i * i
}
}
time.Sleep(1 * time.Second)
}
}