-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
548 lines (463 loc) · 12.8 KB
/
main.go
File metadata and controls
548 lines (463 loc) · 12.8 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package main
import (
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"gopkg.in/yaml.v2"
"github.com/fsnotify/fsnotify"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
)
// Build information (set via ldflags)
var (
Version = "dev"
BuildTime = "unknown"
GitCommit = "unknown"
GoVersion = "unknown"
)
// Config file path (set via flag)
var configPath string
// Templates and Config variables
var (
templates *template.Template
config Config
configMutex sync.RWMutex
sseClients map[chan string]bool
sseClientsMu sync.Mutex
)
// Service status store (updated by background goroutine)
var (
serviceStatus = make(map[string]string)
serviceStatusMux sync.RWMutex
)
// Global HTTP client for service status checks
var httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 5 * time.Second,
}
// getServiceID generates a short hash ID from a service URL
func getServiceID(url string) string {
hash := sha256.Sum256([]byte(url))
return hex.EncodeToString(hash[:])[:8]
}
func init() {
sseClients = make(map[chan string]bool)
}
type Config struct {
Services []ServiceGroup `yaml:"services"`
Bookmarks []BookmarkGroup `yaml:"bookmarks"`
Settings Settings `yaml:"settings"`
}
type ServiceGroup struct {
Group string `yaml:"group"`
Items []Service `yaml:"items"`
}
type Service struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
Description string `yaml:"description"`
Icon string `yaml:"icon"`
Status string `yaml:"-"`
}
type BookmarkGroup struct {
Group string `yaml:"group"`
Items []Bookmark `yaml:"items"`
}
type Bookmark struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
Abbr string `yaml:"abbr"`
}
type Settings struct {
Title string `yaml:"title"`
Port int `yaml:"port"` // Server port (default: 8080)
ShowTitle bool `yaml:"show_title"` // Show title in header (default: true)
}
// SystemMetrics holds all system metrics collected for display
// in the user interface.
type SystemMetrics struct {
CPULoad float64
MemoryUsed float64
MemoryTotal float64
DiskUsed float64
DiskTotal float64
}
// TemplateData holds all data passed to index.html template
type TemplateData struct {
Config
Version string
}
func loadTemplates() error {
var err error
// Template functions map
templateFuncs := template.FuncMap{
"getIconHTML": getIconHTML,
"getDomain": getDomain,
"getServiceID": getServiceID,
}
if useEmbedFS() {
// Try to load from embedded FS
templates, err = template.New("").Funcs(templateFuncs).ParseFS(templatesFS, "templates/*.html")
if err != nil {
return fmt.Errorf("error parsing embedded templates: %v", err)
}
} else {
// Load from file system (dev mode)
templates, err = template.New("").Funcs(templateFuncs).ParseGlob("templates/*.html")
if err != nil {
return fmt.Errorf("error parsing templates: %v", err)
}
}
return nil
}
func loadConfig() error {
configMutex.Lock()
defer configMutex.Unlock()
data, err := os.ReadFile(configPath)
if err != nil {
return fmt.Errorf("error reading config file: %v", err)
}
err = yaml.Unmarshal(data, &config)
if err != nil {
return fmt.Errorf("error parsing config file: %v", err)
}
// Notify all clients that config has changed
broadcastSSE(SSETypeReload, nil)
return nil
}
type SSEMessageType string
const (
SSETypeReload SSEMessageType = "reload"
SSETypeService SSEMessageType = "service"
SSETypeMetrics SSEMessageType = "metrics"
)
type SSEMessage struct {
Type SSEMessageType `json:"type"`
Data any `json:"data,omitempty"`
}
func broadcastSSE(msgType SSEMessageType, data any) {
msg := SSEMessage{Type: msgType}
if msgType != SSETypeReload {
msg.Data = data
}
jsonMsg, err := json.Marshal(msg)
if err != nil {
return
}
message := string(jsonMsg)
sseClientsMu.Lock()
defer sseClientsMu.Unlock()
for client := range sseClients {
select {
case client <- message:
default:
// Client not ready, skip
}
}
}
func watchConfig() error {
absPath, err := filepath.Abs(configPath)
if err != nil {
return fmt.Errorf("error getting absolute path: %v", err)
}
fmt.Printf("Starting config file watcher for: %s\n", absPath)
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("error creating watcher: %v", err)
}
// Watch the directory to handle atomic writes (temp file + rename)
dir := filepath.Dir(absPath)
err = watcher.Add(dir)
if err != nil {
watcher.Close()
return fmt.Errorf("error watching directory: %v", err)
}
// Start watching in background
go func() {
defer watcher.Close()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
// Check if the event is for our config file
if filepath.Base(event.Name) == filepath.Base(absPath) &&
event.Op&fsnotify.Write == fsnotify.Write {
fmt.Printf("Config file modified: %s\n", event.Name)
if err := loadConfig(); err != nil {
fmt.Printf("Error reloading config: %v\n", err)
} else {
fmt.Println("Config reloaded successfully")
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Printf("Watcher error: %v\n", err)
}
}
}()
return nil
}
func handleSSE(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")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Create a buffered channel for this client
messageChan := make(chan string, 100)
// Register this client
sseClientsMu.Lock()
sseClients[messageChan] = true
sseClientsMu.Unlock()
// Send current metrics to the new client immediately
if metrics, err := collectSystemMetrics(); err == nil {
msg := SSEMessage{Type: SSETypeMetrics, Data: metrics}
jsonMsg, _ := json.Marshal(msg)
select {
case messageChan <- string(jsonMsg):
default:
// Client not ready, skip
}
}
// Clean up when the client disconnects
defer func() {
sseClientsMu.Lock()
delete(sseClients, messageChan)
sseClientsMu.Unlock()
close(messageChan)
}()
// Keep the connection alive
for {
select {
case msg := <-messageChan:
fmt.Fprintf(w, "data: %s\n\n", msg)
w.(http.Flusher).Flush()
case <-r.Context().Done():
return
}
}
}
// checkServiceStatus performs a HEAD request to check if a service is responding.
func checkServiceStatus(url string) string {
resp, err := httpClient.Head(url)
// don't forget to close
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return "down"
}
return "up"
}
// getServiceStatus returns the current status from the background-updated store
func getServiceStatus(url string) string {
serviceStatusMux.RLock()
defer serviceStatusMux.RUnlock()
if status, exists := serviceStatus[url]; exists {
return status
}
return "checking"
}
// updateServiceStatusLoop runs in background and updates all service statuses periodically
func updateServiceStatusLoop() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
// Initial check
updateAllServiceStatus()
for range ticker.C {
updateAllServiceStatus()
}
}
// updateAllServiceStatus checks all services in parallel and updates the status map
func updateAllServiceStatus() {
configMutex.RLock()
services := config.Services
configMutex.RUnlock()
var wg sync.WaitGroup
tempStatus := make(map[string]string)
var mu sync.Mutex
// Check all services in parallel
for _, group := range services {
for _, service := range group.Items {
wg.Add(1)
go func(url string) {
defer wg.Done()
status := checkServiceStatus(url)
mu.Lock()
tempStatus[url] = status
mu.Unlock()
}(service.URL)
}
}
wg.Wait()
// First, read existing status with read lock
serviceStatusMux.RLock()
for url, newStatus := range tempStatus {
if oldStatus, exists := serviceStatus[url]; !exists || oldStatus != newStatus {
serviceID := getServiceID(url)
serviceData := map[string]string{"id": serviceID, "status": newStatus}
broadcastSSE(SSETypeService, serviceData)
}
}
serviceStatusMux.RUnlock()
// Then, update with write lock
serviceStatusMux.Lock()
serviceStatus = tempStatus
serviceStatusMux.Unlock()
}
// updateMetricsLoop runs in background and broadcasts metrics updates periodically
func updateMetricsLoop() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for range ticker.C {
metrics, err := collectSystemMetrics()
if err != nil {
continue
}
// Broadcast metrics update via SSE
broadcastSSE(SSETypeMetrics, metrics)
}
}
func getIconHTML(icon, name string) template.HTML {
if icon == "" {
return template.HTML(fmt.Sprintf(`<span class="iconify" data-icon="mdi:application" data-width="36" data-height="36"></span>`))
}
if strings.HasPrefix(icon, "mdi-") {
return template.HTML(fmt.Sprintf(`<span class="iconify" data-icon="mdi:%s" data-width="36" data-height="36"></span>`, strings.TrimPrefix(icon, "mdi-")))
}
url := fmt.Sprintf("https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/%s", icon)
return template.HTML(fmt.Sprintf(`<img src='%s' alt='%s'>`, url, name))
}
func getDomain(url string) string {
// Remove protocol
url = strings.TrimPrefix(url, "https://")
url = strings.TrimPrefix(url, "http://")
// Get domain part (before first /)
parts := strings.Split(url, "/")
if len(parts) > 0 {
domain := parts[0]
// Remove www. prefix if present
domain = strings.TrimPrefix(domain, "www.")
return domain
}
return url
}
// collectSystemMetrics gathers real-time system metrics using gopsutil.
// Returns an error if collection fails.
func collectSystemMetrics() (SystemMetrics, error) {
metrics := SystemMetrics{}
// CPU usage - use 0 duration to get instant value (non-blocking)
// Note: First call will return 0, subsequent calls show CPU usage since last call
cpuPercent, err := cpu.Percent(0, false)
if err != nil {
return metrics, fmt.Errorf("failed to collect CPU metrics: %w", err)
}
if len(cpuPercent) > 0 {
metrics.CPULoad = cpuPercent[0]
}
// Memory usage
memory, err := mem.VirtualMemory()
if err != nil {
return metrics, fmt.Errorf("failed to collect memory metrics: %w", err)
}
metrics.MemoryUsed = float64(memory.Used) / 1024 / 1024 / 1024 // Convert to GB
metrics.MemoryTotal = float64(memory.Total) / 1024 / 1024 / 1024 // Convert to GB
// Disk usage (root partition)
diskStat, err := disk.Usage("/")
if err != nil {
return metrics, fmt.Errorf("failed to collect disk metrics: %w", err)
}
metrics.DiskUsed = float64(diskStat.Used) / 1024 / 1024 / 1024 // Convert to GB
metrics.DiskTotal = float64(diskStat.Total) / 1024 / 1024 / 1024 // Convert to GB
return metrics, nil
}
// handleIndex serves the main index page with services, bookmarks, and metrics
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
configMutex.RLock()
// Get status for all services from background store
for i := range config.Services {
for j := range config.Services[i].Items {
service := &config.Services[i].Items[j]
service.Status = getServiceStatus(service.URL)
}
}
data := struct {
Config Config
Version string
}{
Config: config,
Version: Version,
}
configMutex.RUnlock()
err := templates.ExecuteTemplate(w, "index.html", data)
if err != nil {
// Use fmt.Printf instead of http.Error to avoid WriteHeader conflicts
fmt.Printf("Template execution error: %v\n", err)
return
}
}
func main() {
// Parse command line flags
flag.StringVar(&configPath, "config", "config.yaml", "Path to configuration file")
flag.Parse()
// Print version information
fmt.Printf("Homepage Lite %s\n", Version)
fmt.Printf(" Build Time: %s\n", BuildTime)
fmt.Printf(" Git Commit: %s\n", GitCommit)
fmt.Printf(" Go Version: %s\n", GoVersion)
fmt.Printf(" Config: %s\n", configPath)
fmt.Println()
if err := loadConfig(); err != nil {
fmt.Printf("Error loading config: %v\n", err)
return
}
if err := loadTemplates(); err != nil {
fmt.Printf("Error loading templates: %v\n", err)
return
}
if err := watchConfig(); err != nil {
fmt.Printf("Error setting up config watcher: %v\n", err)
return
}
// Start background goroutines
go updateServiceStatusLoop()
go updateMetricsLoop()
// API routes
http.HandleFunc("/events", handleSSE)
// Static files - setup based on build mode
setupStaticFiles()
// Root route
http.HandleFunc("/", handleIndex)
// Get port from config or use default
port := config.Settings.Port
if port == 0 {
port = 8080
}
addr := fmt.Sprintf(":%d", port)
fmt.Printf("Starting server on %s\n", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
fmt.Printf("Server error: %v\n", err)
}
}