-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
97 lines (81 loc) · 1.88 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
package main
import (
"context"
"embed"
"os"
"os/exec"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/yarlson/duh/docker"
"github.com/yarlson/duh/logger"
"github.com/yarlson/duh/server"
"github.com/yarlson/duh/service"
"github.com/yarlson/duh/store"
)
//go:embed www/dist
var StaticFiles embed.FS
const (
serverPort = ":4242"
serverURL = "http://localhost" + serverPort
)
func openBrowser(url string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("cmd", "/c", "start", url)
case "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
return cmd.Start()
}
func main() {
l := logger.New()
l.Info("Starting duh...")
dockerClient := docker.NewClient()
memoryStore := store.NewStore(30 * time.Second)
containerService := service.New(dockerClient, memoryStore)
containers, err := containerService.SyncContainers(context.Background())
if err != nil {
l.Fatal("Initial sync failed: %v", err)
}
go func() {
containerService.SyncStats(context.Background(), containers)
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := containerService.Sync(ctx); err != nil {
l.Warn("Sync error: %v", err)
}
case <-ctx.Done():
return
}
}
}()
srv := server.New(containerService, StaticFiles)
go func() {
if err := srv.ListenAndServe(serverPort); err != nil {
l.Fatal("Server failed: %v", err)
}
}()
time.Sleep(100 * time.Millisecond)
if err := openBrowser(serverURL); err != nil {
l.Warn("Failed to open browser: %v", err)
}
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
l.Info("Shutting down...")
cancel()
memoryStore.Close()
l.Info("Server stopped gracefully")
}