9 "github.com/jhalter/mobius/hotline"
11 "go.uber.org/zap/zapcore"
12 "gopkg.in/natefinch/lumberjack.v2"
23 //go:embed mobius/config
24 var cfgTemplate embed.FS
31 rand.Seed(time.Now().UnixNano())
33 ctx, cancel := context.WithCancel(context.Background())
35 // TODO: implement graceful shutdown by closing context
36 // c := make(chan os.Signal, 1)
37 // signal.Notify(c, os.Interrupt)
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")
57 init := flag.Bool("init", false, "Populate the config dir with default configuration")
62 fmt.Printf("v%s\n", hotline.VERSION)
66 zapLvl, ok := zapLogLevel[*logLevel]
68 fmt.Printf("Invalid log level %s. Must be debug, info, warn, or error.\n", *logLevel)
72 cores := []zapcore.Core{
73 newStdoutCore(zapLvl),
77 cores = append(cores, newLogFileCore(*logFile, zapLvl))
80 l := zap.New(zapcore.NewTee(cores...))
81 defer func() { _ = l.Sync() }()
85 if _, err := os.Stat(filepath.Join(*configDir, "/config.yaml")); os.IsNotExist(err) {
86 if err := os.MkdirAll(*configDir, 0750); err != nil {
90 if err := copyDir("mobius/config", *configDir); err != nil {
93 logger.Infow("Config dir initialized at " + *configDir)
96 logger.Infow("Existing config dir found. Skipping initialization.")
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)
104 srv, err := hotline.NewServer(*configDir, *basePort, logger, &hotline.OSFileStore{})
109 sh := statHandler{hlServer: srv}
110 if *statsPort != "" {
111 http.HandleFunc("/", sh.RenderStats)
113 go func(srv *hotline.Server) {
114 // Use the default DefaultServeMux.
115 err = http.ListenAndServe(":"+*statsPort, nil)
122 // Serve Hotline requests until program exit
123 logger.Fatal(srv.ListenAndServe(ctx, cancel))
126 type statHandler struct {
127 hlServer *hotline.Server
130 func (sh *statHandler) RenderStats(w http.ResponseWriter, _ *http.Request) {
131 u, err := json.Marshal(sh.hlServer.CurrentStats())
136 _, _ = io.WriteString(w, string(u))
139 func newStdoutCore(level zapcore.Level) zapcore.Core {
140 encoderCfg := zap.NewProductionEncoderConfig()
141 encoderCfg.TimeKey = "timestamp"
142 encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
144 return zapcore.NewCore(
145 zapcore.NewConsoleEncoder(encoderCfg),
146 zapcore.Lock(os.Stdout),
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{
162 return zapcore.NewCore(
163 zapcore.NewConsoleEncoder(encoderCfg),
169 var zapLogLevel = map[string]zapcore.Level{
170 "debug": zap.DebugLevel,
171 "info": zap.InfoLevel,
172 "warn": zap.WarnLevel,
173 "error": zap.ErrorLevel,
176 func defaultConfigPath() (cfgPath string) {
177 switch runtime.GOOS {
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/"
187 cfgPath = "/usr/local/var/mobius/config/"
189 fmt.Printf("unsupported OS")
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)
201 for _, dirEntry := range entries {
202 if dirEntry.IsDir() {
203 if err := os.MkdirAll(filepath.Join(dst, dirEntry.Name()), 0777); err != nil {
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()))
213 srcFile, err := cfgTemplate.Open(filepath.Join(src, dirEntry.Name(), subDirEntry.Name()))
217 _, err = io.Copy(f, srcFile)
224 f, err := os.Create(filepath.Join(dst, dirEntry.Name()))
229 srcFile, err := cfgTemplate.Open(filepath.Join(src, dirEntry.Name()))
233 _, err = io.Copy(f, srcFile)