-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
314 lines (271 loc) · 8.23 KB
/
main.go
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/net"
"github.com/shirou/gopsutil/v3/process"
httpSwagger "github.com/swaggo/http-swagger"
_ "github.com/thatbeautifuldream/system-stats-backend/docs" // This line is needed for swagger
)
// @title System Stats API
// @version 1.0
// @description API for monitoring system resources and processes
// @host localhost:3000
// @BasePath /api
// Constants
const (
defaultPort = "3000"
apiPrefix = "/api"
// CORS headers
allowOrigin = "*"
allowMethods = "GET, POST, PUT, DELETE, OPTIONS"
allowHeaders = "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization"
allowCredentials = "true"
)
// SystemStats represents system resource usage statistics
// @Description System resource usage statistics including CPU, memory, disk, network, and processes
type SystemStats struct {
CPUUsage float64 `json:"cpuUsage" example:"45.2"`
MemUsage float64 `json:"memUsage" example:"60.5"`
DiskUsage float64 `json:"diskUsage" example:"75.0"`
NetTraffic int64 `json:"netTraffic" example:"1048576"`
Processes []ProcessInfo `json:"processes"`
}
// ProcessInfo represents information about a single process
// @Description Information about a single system process
type ProcessInfo struct {
PID int32 `json:"pid" example:"1234"`
Name string `json:"name" example:"chrome"`
CPUPercent float64 `json:"cpuPercent" example:"5.5"`
MemoryUsage float32 `json:"memoryUsage" example:"256.5"` // in MB
}
// Server represents our HTTP server
type Server struct {
router *http.ServeMux
port string
}
// NewServer creates a new server instance
func NewServer(port string) *Server {
if port == "" {
port = defaultPort
}
return &Server{
router: http.NewServeMux(),
port: port,
}
}
// corsMiddleware wraps an http.HandlerFunc and adds CORS headers
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", allowOrigin)
w.Header().Set("Access-Control-Allow-Methods", allowMethods)
w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
w.Header().Set("Access-Control-Allow-Credentials", allowCredentials)
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next(w, r)
}
}
// setupRoutes configures all the routes for the server
func (s *Server) setupRoutes() {
// Swagger documentation endpoint
s.router.Handle("/swagger/", httpSwagger.Handler(
httpSwagger.URL("/swagger/doc.json"),
httpSwagger.DeepLinking(true),
httpSwagger.DocExpansion("none"),
httpSwagger.DomID("swagger-ui"),
))
// Wrap root handler with CORS
s.router.HandleFunc("/", corsMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
info := map[string]interface{}{
"name": "System Stats API",
"version": "1.0",
"description": "API for monitoring system resources and processes",
"endpoints": map[string]string{
"/api/stats": "Get current system statistics",
"/api/events": "SSE endpoint for real-time system statistics",
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(info)
}))
// Wrap API endpoints with CORS
s.router.HandleFunc(apiPrefix+"/stats", corsMiddleware(s.statsHandler))
s.router.HandleFunc(apiPrefix+"/events", corsMiddleware(s.sseHandler))
}
// Start starts the server and handles graceful shutdown
func (s *Server) Start() error {
server := &http.Server{
Addr: ":" + s.port,
Handler: s.router,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Channel for shutdown signals
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
// Channel for server errors
errChan := make(chan error, 1)
go func() {
log.Printf("Server running at http://localhost:%s\n", s.port)
errChan <- server.ListenAndServe()
}()
// Wait for shutdown signal or error
select {
case <-stop:
log.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return server.Shutdown(ctx)
case err := <-errChan:
return fmt.Errorf("server error: %w", err)
}
}
// Fetch system and process stats
func getStats() (*SystemStats, error) {
// Get CPU stats
cpuPercentages, err := cpu.Percent(0, false)
if err != nil {
return nil, fmt.Errorf("error getting CPU stats: %w", err)
}
if len(cpuPercentages) == 0 {
return nil, fmt.Errorf("no CPU statistics available")
}
// Get memory stats
memStats, err := mem.VirtualMemory()
if err != nil {
return nil, fmt.Errorf("error getting memory stats: %w", err)
}
// Get disk stats
diskStats, err := disk.Usage("/")
if err != nil {
return nil, fmt.Errorf("error getting disk stats: %w", err)
}
// Get network stats
netStats, err := net.IOCounters(false)
if err != nil {
return nil, fmt.Errorf("error getting network stats: %w", err)
}
if len(netStats) == 0 {
return nil, fmt.Errorf("no network statistics available")
}
// Get process stats
procs, err := process.Processes()
if err != nil {
return nil, fmt.Errorf("error getting process list: %w", err)
}
processInfo := []ProcessInfo{}
for _, proc := range procs {
name, err := proc.Name()
if err != nil {
continue // Skip this process if we can't get its name
}
cpuPercent, err := proc.CPUPercent()
if err != nil {
continue // Skip this process if we can't get CPU usage
}
memInfo, err := proc.MemoryInfo()
if err != nil {
continue // Skip this process if we can't get memory info
}
processInfo = append(processInfo, ProcessInfo{
PID: proc.Pid,
Name: name,
CPUPercent: cpuPercent,
MemoryUsage: float32(memInfo.RSS) / (1024 * 1024),
})
}
stats := &SystemStats{
CPUUsage: cpuPercentages[0],
MemUsage: memStats.UsedPercent,
DiskUsage: diskStats.UsedPercent,
NetTraffic: int64(netStats[0].BytesRecv + netStats[0].BytesSent),
Processes: processInfo,
}
return stats, nil
}
// statsHandler godoc
// @Summary Get current system statistics
// @Description Returns current CPU, memory, disk usage, network traffic, and process information
// @Tags stats
// @Produce json
// @Success 200 {object} SystemStats
// @Failure 500 {string} string "Internal Server Error"
// @Router /stats [get]
func (s *Server) statsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
stats, err := getStats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(stats); err != nil {
log.Printf("Error encoding response: %v", err)
}
}
// sseHandler godoc
// @Summary Get real-time system statistics
// @Description Provides Server-Sent Events (SSE) stream of system statistics
// @Tags stats
// @Produce text/event-stream
// @Success 200 {string} string "SSE stream of SystemStats"
// @Failure 500 {string} string "Internal Server Error"
// @Router /events [get]
func (s *Server) sseHandler(w http.ResponseWriter, r *http.Request) {
// Set headers for SSE
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// Create encoder for JSON
encoder := json.NewEncoder(w)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ticker.C:
stats, err := getStats()
if err != nil {
fmt.Fprintf(w, "event: error\ndata: %v\n\n", err)
w.(http.Flusher).Flush()
continue
}
fmt.Fprintf(w, "event: stats\ndata: ")
encoder.Encode(stats)
fmt.Fprintf(w, "\n\n")
w.(http.Flusher).Flush()
}
}
}
func main() {
// Create and start server
server := NewServer(os.Getenv("PORT"))
server.setupRoutes()
if err := server.Start(); err != nil {
log.Fatal(err)
}
}