]>
Commit | Line | Data |
---|---|---|
1 | package main | |
2 | ||
3 | import ( | |
4 | "context" | |
5 | "embed" | |
6 | "encoding/json" | |
7 | "flag" | |
8 | "fmt" | |
9 | "github.com/jhalter/mobius/hotline" | |
10 | "go.uber.org/zap" | |
11 | "go.uber.org/zap/zapcore" | |
12 | "gopkg.in/natefinch/lumberjack.v2" | |
13 | "io" | |
14 | "log" | |
15 | "math/rand" | |
16 | "net/http" | |
17 | "os" | |
18 | "path/filepath" | |
19 | "runtime" | |
20 | "time" | |
21 | ) | |
22 | ||
23 | //go:embed mobius/config | |
24 | var cfgTemplate embed.FS | |
25 | ||
26 | const ( | |
27 | defaultPort = 5500 | |
28 | ) | |
29 | ||
30 | func main() { | |
31 | rand.Seed(time.Now().UnixNano()) | |
32 | ||
33 | ctx, cancel := context.WithCancel(context.Background()) | |
34 | ||
35 | // TODO: implement graceful shutdown by closing context | |
36 | // c := make(chan os.Signal, 1) | |
37 | // signal.Notify(c, os.Interrupt) | |
38 | // defer func() { | |
39 | // signal.Stop(c) | |
40 | // cancel() | |
41 | // }() | |
42 | // go func() { | |
43 | // select { | |
44 | // case <-c: | |
45 | // cancel() | |
46 | // case <-ctx.Done(): | |
47 | // } | |
48 | // }() | |
49 | ||
50 | basePort := flag.Int("bind", defaultPort, "Bind address and port") | |
51 | statsPort := flag.String("stats-port", "", "Enable stats HTTP endpoint on address and port") | |
52 | configDir := flag.String("config", defaultConfigPath(), "Path to config root") | |
53 | version := flag.Bool("version", false, "print version and exit") | |
54 | logLevel := flag.String("log-level", "info", "Log level") | |
55 | logFile := flag.String("log-file", "", "Path to log file") | |
56 | ||
57 | init := flag.Bool("init", false, "Populate the config dir with default configuration") | |
58 | ||
59 | flag.Parse() | |
60 | ||
61 | if *version { | |
62 | fmt.Printf("v%s\n", hotline.VERSION) | |
63 | os.Exit(0) | |
64 | } | |
65 | ||
66 | zapLvl, ok := zapLogLevel[*logLevel] | |
67 | if !ok { | |
68 | fmt.Printf("Invalid log level %s. Must be debug, info, warn, or error.\n", *logLevel) | |
69 | os.Exit(0) | |
70 | } | |
71 | ||
72 | cores := []zapcore.Core{ | |
73 | newStdoutCore(zapLvl), | |
74 | } | |
75 | ||
76 | if *logFile != "" { | |
77 | cores = append(cores, newLogFileCore(*logFile, zapLvl)) | |
78 | } | |
79 | ||
80 | l := zap.New(zapcore.NewTee(cores...)) | |
81 | defer func() { _ = l.Sync() }() | |
82 | logger := l.Sugar() | |
83 | ||
84 | if *init { | |
85 | if _, err := os.Stat(filepath.Join(*configDir, "/config.yaml")); os.IsNotExist(err) { | |
86 | if err := os.MkdirAll(*configDir, 0750); err != nil { | |
87 | logger.Fatal(err) | |
88 | } | |
89 | ||
90 | if err := copyDir("mobius/config", *configDir); err != nil { | |
91 | logger.Fatal(err) | |
92 | } | |
93 | logger.Infow("Config dir initialized at " + *configDir) | |
94 | ||
95 | } else { | |
96 | logger.Infow("Existing config dir found. Skipping initialization.") | |
97 | } | |
98 | } | |
99 | ||
100 | if _, err := os.Stat(*configDir); os.IsNotExist(err) { | |
101 | logger.Fatalw("Configuration directory not found. Correct the path or re-run with -init to generate initial config.", "path", configDir) | |
102 | } | |
103 | ||
104 | srv, err := hotline.NewServer(*configDir, *basePort, logger, &hotline.OSFileStore{}) | |
105 | if err != nil { | |
106 | logger.Fatal(err) | |
107 | } | |
108 | ||
109 | sh := statHandler{hlServer: srv} | |
110 | if *statsPort != "" { | |
111 | http.HandleFunc("/", sh.RenderStats) | |
112 | ||
113 | go func(srv *hotline.Server) { | |
114 | // Use the default DefaultServeMux. | |
115 | err = http.ListenAndServe(":"+*statsPort, nil) | |
116 | if err != nil { | |
117 | log.Fatal(err) | |
118 | } | |
119 | }(srv) | |
120 | } | |
121 | ||
122 | // Serve Hotline requests until program exit | |
123 | logger.Fatal(srv.ListenAndServe(ctx, cancel)) | |
124 | } | |
125 | ||
126 | type statHandler struct { | |
127 | hlServer *hotline.Server | |
128 | } | |
129 | ||
130 | func (sh *statHandler) RenderStats(w http.ResponseWriter, _ *http.Request) { | |
131 | u, err := json.Marshal(sh.hlServer.CurrentStats()) | |
132 | if err != nil { | |
133 | panic(err) | |
134 | } | |
135 | ||
136 | _, _ = io.WriteString(w, string(u)) | |
137 | } | |
138 | ||
139 | func newStdoutCore(level zapcore.Level) zapcore.Core { | |
140 | encoderCfg := zap.NewProductionEncoderConfig() | |
141 | encoderCfg.TimeKey = "timestamp" | |
142 | encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder | |
143 | ||
144 | return zapcore.NewCore( | |
145 | zapcore.NewConsoleEncoder(encoderCfg), | |
146 | zapcore.Lock(os.Stdout), | |
147 | level, | |
148 | ) | |
149 | } | |
150 | ||
151 | func newLogFileCore(path string, level zapcore.Level) zapcore.Core { | |
152 | encoderCfg := zap.NewProductionEncoderConfig() | |
153 | encoderCfg.TimeKey = "timestamp" | |
154 | encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder | |
155 | writer := zapcore.AddSync(&lumberjack.Logger{ | |
156 | Filename: path, | |
157 | MaxSize: 100, // MB | |
158 | MaxBackups: 3, | |
159 | MaxAge: 365, // days | |
160 | }) | |
161 | ||
162 | return zapcore.NewCore( | |
163 | zapcore.NewConsoleEncoder(encoderCfg), | |
164 | writer, | |
165 | level, | |
166 | ) | |
167 | } | |
168 | ||
169 | var zapLogLevel = map[string]zapcore.Level{ | |
170 | "debug": zap.DebugLevel, | |
171 | "info": zap.InfoLevel, | |
172 | "warn": zap.WarnLevel, | |
173 | "error": zap.ErrorLevel, | |
174 | } | |
175 | ||
176 | func defaultConfigPath() (cfgPath string) { | |
177 | switch runtime.GOOS { | |
178 | case "windows": | |
179 | cfgPath = "config/" | |
180 | case "darwin": | |
181 | if _, err := os.Stat("/usr/local/var/mobius/config/"); err == nil { | |
182 | cfgPath = "/usr/local/var/mobius/config/" | |
183 | } else if _, err := os.Stat("/opt/homebrew/var/mobius/config"); err == nil { | |
184 | cfgPath = "/opt/homebrew/var/mobius/config/" | |
185 | } | |
186 | case "linux": | |
187 | cfgPath = "/usr/local/var/mobius/config/" | |
188 | default: | |
189 | fmt.Printf("unsupported OS") | |
190 | } | |
191 | ||
192 | return cfgPath | |
193 | } | |
194 | ||
195 | // TODO: Simplify this mess. Why is it so difficult to recursively copy a directory? | |
196 | func copyDir(src, dst string) error { | |
197 | entries, err := cfgTemplate.ReadDir(src) | |
198 | if err != nil { | |
199 | return err | |
200 | } | |
201 | for _, dirEntry := range entries { | |
202 | if dirEntry.IsDir() { | |
203 | if err := os.MkdirAll(filepath.Join(dst, dirEntry.Name()), 0777); err != nil { | |
204 | panic(err) | |
205 | } | |
206 | subdirEntries, _ := cfgTemplate.ReadDir(filepath.Join(src, dirEntry.Name())) | |
207 | for _, subDirEntry := range subdirEntries { | |
208 | f, err := os.Create(filepath.Join(dst, dirEntry.Name(), subDirEntry.Name())) | |
209 | if err != nil { | |
210 | return err | |
211 | } | |
212 | ||
213 | srcFile, err := cfgTemplate.Open(filepath.Join(src, dirEntry.Name(), subDirEntry.Name())) | |
214 | if err != nil { | |
215 | return err | |
216 | } | |
217 | _, err = io.Copy(f, srcFile) | |
218 | if err != nil { | |
219 | return err | |
220 | } | |
221 | f.Close() | |
222 | } | |
223 | } else { | |
224 | f, err := os.Create(filepath.Join(dst, dirEntry.Name())) | |
225 | if err != nil { | |
226 | return err | |
227 | } | |
228 | ||
229 | srcFile, err := cfgTemplate.Open(filepath.Join(src, dirEntry.Name())) | |
230 | if err != nil { | |
231 | return err | |
232 | } | |
233 | _, err = io.Copy(f, srcFile) | |
234 | if err != nil { | |
235 | return err | |
236 | } | |
237 | f.Close() | |
238 | } | |
239 | ||
240 | } | |
241 | ||
242 | return nil | |
243 | } |