dogtamer/cmd/dogtamer.go

176 lines
4.2 KiB
Go
Raw Normal View History

2021-08-21 14:15:29 +00:00
package main
import (
"context"
"fmt"
2021-08-23 00:45:44 +00:00
"net/http"
2021-08-21 14:15:29 +00:00
"os"
"os/signal"
2021-10-19 00:58:41 +00:00
"runtime/pprof"
2021-09-02 01:05:04 +00:00
"strings"
2021-08-21 14:15:29 +00:00
"github.com/urfave/cli/v2"
"github.uio.no/torjus/dogtamer"
"github.uio.no/torjus/dogtamer/config"
2021-08-21 14:15:29 +00:00
"github.uio.no/torjus/dogtamer/server"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
ExitSuccess = 0
ExitGenericError = 1
)
func main() {
cli.VersionPrinter = func(c *cli.Context) {
fmt.Println(dogtamer.GetVersion())
}
app := &cli.App{
Name: "dogtamer",
Version: dogtamer.Version,
Authors: []*cli.Author{
{
Name: "Torjus Håkestad",
Email: "torjus@usit.uio.no",
},
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Path to config-file",
Aliases: []string{"c"},
},
2021-10-19 00:58:41 +00:00
&cli.StringFlag{
Name: "cpu-profile",
Usage: "Profile cpu usage and write to file",
},
2021-08-21 14:15:29 +00:00
},
Commands: []*cli.Command{
{
Name: "serve",
Usage: "Start dogtamer server",
Action: ActionServe,
},
},
}
err := app.Run(os.Args)
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(ExitGenericError)
}
}
func ActionServe(c *cli.Context) error {
2021-09-02 01:05:04 +00:00
// Setup temporary logger, incase config could not be read
logger := setupServerLogger("INFO")
cfg, err := config.FromDefaultLocations()
if err != nil {
logger.Warn("No config file found.")
}
2021-09-02 01:05:04 +00:00
// Setup proper logger
logger = setupServerLogger(cfg.LogLevel)
2021-09-19 03:49:23 +00:00
cfg.DebugLog(logger)
2021-08-21 14:15:29 +00:00
ctx, cancel := context.WithCancel(context.Background())
2021-10-19 00:58:41 +00:00
defer cancel()
// Setup RTMP-server
2021-09-19 03:49:23 +00:00
rtmpServer := server.NewRTMPServer(ctx, cfg.RTMPListenAddr)
rtmpServer.Logger = logger
rtmpServer.Hostname = cfg.Hostname
2021-08-21 14:15:29 +00:00
2021-11-01 20:31:24 +00:00
if cfg.MetricsEnable {
rtmpServer.EnableMetrics()
}
2021-10-19 00:58:41 +00:00
if c.IsSet("cpu-profile") {
filename := c.String("cpu-profile")
logger.Infow("CPU-profiling enabled.", "filename", filename)
f, err := os.Create(filename)
if err != nil {
return cli.Exit(fmt.Sprintf("Unable to create cpu-profile file '%s': %s", filename, err), 1)
}
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Setup web-server
webDone := make(chan struct{})
if cfg.HTTPServerEnable {
2021-09-19 03:49:23 +00:00
ws := server.NewWebServer(ctx, rtmpServer)
ws.ListenAddr = cfg.HTTPListenAddr
ws.Logger = logger
2021-11-01 20:31:24 +00:00
if cfg.MetricsEnable {
ws.EnableMetrics = true
}
go func() {
2021-09-19 03:49:23 +00:00
rtmpServer.Logger.Infow("Starting HTTP server.", "listen_addr", ws.ListenAddr)
err := ws.Serve()
if err != nil && err != http.ErrServerClosed {
2021-09-19 03:49:23 +00:00
rtmpServer.Logger.Infow("HTTP server shut down with error.", "err", err)
}
close(webDone)
}()
} else {
close(webDone)
}
2021-08-21 14:15:29 +00:00
// Listen for SIGINT
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt)
go func() {
<-sigChan
2021-09-19 03:49:23 +00:00
rtmpServer.Logger.Debug("Got shutdown signal.")
2021-08-21 14:15:29 +00:00
cancel()
}()
// Start RTMP-server
2021-09-19 03:50:26 +00:00
rtmpServer.Logger.Infow("Starting RTMP server.", "listen_addr", rtmpServer.ListenAddr)
2021-09-19 03:49:23 +00:00
if err := rtmpServer.Listen(); err != nil {
2021-08-21 14:15:29 +00:00
return cli.Exit(err, ExitGenericError)
}
// Wait for webserver to exit, if started
<-webDone
2021-09-19 03:49:23 +00:00
rtmpServer.Logger.Info("Server shut down.")
2021-08-21 14:15:29 +00:00
return nil
}
2021-09-02 01:05:04 +00:00
func setupServerLogger(loglevel string) *zap.SugaredLogger {
2021-08-21 14:15:29 +00:00
logEncoderConfig := zap.NewProductionEncoderConfig()
logEncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
logEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
logEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logEncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
rootLoggerConfig := &zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
2021-08-21 14:15:29 +00:00
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stdout"},
Encoding: "console",
EncoderConfig: logEncoderConfig,
2021-09-02 01:05:04 +00:00
DisableCaller: true,
}
switch strings.ToUpper(loglevel) {
case "DEBUG":
rootLoggerConfig.DisableCaller = false
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
case "INFO":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
case "WARN", "WARNING":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
case "ERR", "ERROR":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
2021-08-21 14:15:29 +00:00
}
rootLogger, err := rootLoggerConfig.Build()
if err != nil {
panic(err)
}
return rootLogger.Named("RTMP").WithOptions().Sugar()
}