Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion cmd/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package cmd

import (
"context"
"log/slog"
"time"

appconfig "github.com/lachlanharrisdev/gonetsim/internal/config"
"github.com/lachlanharrisdev/gonetsim/internal/dnsserver"
"github.com/lachlanharrisdev/gonetsim/internal/observability"
"github.com/lachlanharrisdev/gonetsim/internal/service"
"github.com/lachlanharrisdev/gonetsim/internal/utils"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -48,7 +51,12 @@ var dnsCmd = &cobra.Command{
ctx, stop := utils.SignalContext(context.Background())
defer stop()

manager := service.NewManager(5 * time.Second)
logger, err := observability.NewLogger(appconfig.Default().Logging)
if err != nil {
return err
}
slog.SetDefault(logger)
manager := service.NewManager(5*time.Second, logger)
return manager.RunSingleService(ctx, dnsserver.NewService(conf))
},
}
Expand Down
10 changes: 9 additions & 1 deletion cmd/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package cmd

import (
"context"
"log/slog"
"time"

appconfig "github.com/lachlanharrisdev/gonetsim/internal/config"
"github.com/lachlanharrisdev/gonetsim/internal/httpserver"
"github.com/lachlanharrisdev/gonetsim/internal/observability"
"github.com/lachlanharrisdev/gonetsim/internal/service"
"github.com/lachlanharrisdev/gonetsim/internal/utils"
"github.com/spf13/cobra"
Expand All @@ -27,7 +30,12 @@ var httpCmd = &cobra.Command{
ctx, stop := utils.SignalContext(context.Background())
defer stop()

manager := service.NewManager(5 * time.Second)
logger, err := observability.NewLogger(appconfig.Default().Logging)
if err != nil {
return err
}
slog.SetDefault(logger)
manager := service.NewManager(5*time.Second, logger)

return manager.RunSingleService(ctx,
httpserver.NewHTTPService(
Expand Down
10 changes: 9 additions & 1 deletion cmd/https.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package cmd

import (
"context"
"log/slog"
"time"

appconfig "github.com/lachlanharrisdev/gonetsim/internal/config"
"github.com/lachlanharrisdev/gonetsim/internal/httpserver"
"github.com/lachlanharrisdev/gonetsim/internal/observability"
"github.com/lachlanharrisdev/gonetsim/internal/service"
"github.com/lachlanharrisdev/gonetsim/internal/utils"
"github.com/spf13/cobra"
Expand All @@ -29,7 +32,12 @@ var httpsCmd = &cobra.Command{
ctx, stop := utils.SignalContext(context.Background())
defer stop()

manager := service.NewManager(5 * time.Second)
logger, err := observability.NewLogger(appconfig.Default().Logging)
if err != nil {
return err
}
slog.SetDefault(logger)
manager := service.NewManager(5*time.Second, logger)
return manager.RunSingleService(ctx,
httpserver.NewHTTPSService(
httpserver.Config{Addr: listen, StatusCode: httpsStatus},
Expand Down
36 changes: 20 additions & 16 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package cmd
import (
"context"
"fmt"
"log"
"log/slog"
"os"

appconfig "github.com/lachlanharrisdev/gonetsim/internal/config"
"github.com/lachlanharrisdev/gonetsim/internal/dnsserver"
"github.com/lachlanharrisdev/gonetsim/internal/httpserver"
"github.com/lachlanharrisdev/gonetsim/internal/observability"
"github.com/lachlanharrisdev/gonetsim/internal/service"
"github.com/lachlanharrisdev/gonetsim/internal/utils"
"github.com/spf13/cobra"
Expand All @@ -17,28 +18,35 @@ import (
var rootConfigPath string

var rootCmd = &cobra.Command{
Use: "gonetsim",
Short: "Network service simulator (dns + http + https)",
Args: cobra.NoArgs,
SilenceUsage: true,
Use: "gonetsim",
Short: "Network service simulator (dns + http + https)",
Args: cobra.NoArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
cfgRes, err := appconfig.LoadOrCreate(rootConfigPath)
if err != nil {
return err
}
cfg := cfgRes.Config

logger, err := observability.NewLogger(cfg.Logging)
if err != nil {
return err
}
slog.SetDefault(logger)
if cfgRes.Created {
log.Printf("config: created default config at %s", cfgRes.Path)
logger.Info("config created", "path", cfgRes.Path)
}
log.Printf("config: using %s", cfgRes.Path)
cfg := cfgRes.Config
logger.Info("config loaded", "path", cfgRes.Path)

ctx, stop := utils.SignalContext(context.Background())
defer stop()

runCtx, cancel := context.WithCancel(ctx)
defer cancel()

manager := service.NewManager(cfg.General.ShutdownTimeout)
manager := service.NewManager(cfg.General.ShutdownTimeout, logger)

if cfg.DNS.Enabled {
listen, err := parseAddrPort(cfg.DNS.Listen)
Expand Down Expand Up @@ -85,20 +93,16 @@ var rootCmd = &cobra.Command{
manager.Add(httpserver.NewHTTPSService(conf, tlsOpts))
}

log.Printf("root: running (dns=%t http=%t https=%t)", cfg.DNS.Enabled, cfg.HTTP.Enabled, cfg.HTTPS.Enabled)
logger.Info("running", "dns", cfg.DNS.Enabled, "http", cfg.HTTP.Enabled, "https", cfg.HTTPS.Enabled)

return manager.RunAll(runCtx)
},
}

func exitError(msg interface{}) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
exitError(err)
slog.Error("fatal error", "err", err)
os.Exit(1)
}
}

Expand Down
6 changes: 5 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ require (
github.com/knadh/koanf/providers/file v1.2.1
github.com/knadh/koanf/providers/structs v1.0.0
github.com/knadh/koanf/v2 v2.3.4
github.com/lmittmann/tint v1.1.3
github.com/mattn/go-colorable v0.1.14
github.com/mattn/go-isatty v0.0.20
github.com/miekg/dns v1.1.72
github.com/spf13/cobra v1.10.2
)

require (
github.com/fatih/color v1.19.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
Expand All @@ -24,6 +28,6 @@ require (
golang.org/x/mod v0.31.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/tools v0.40.0 // indirect
)
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
Expand All @@ -21,6 +23,12 @@ github.com/knadh/koanf/providers/structs v1.0.0 h1:DznjB7NQykhqCar2LvNug3MuxEQsZ
github.com/knadh/koanf/providers/structs v1.0.0/go.mod h1:kjo5TFtgpaZORlpoJqcbeLowM2cINodv8kX+oFAeQ1w=
github.com/knadh/koanf/v2 v2.3.4 h1:fnynNSDlujWE+v83hAp8wKr/cdoxHLO0629SN+U8Urc=
github.com/knadh/koanf/v2 v2.3.4/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=
github.com/lmittmann/tint v1.1.3 h1:Hv4EaHWXQr+GTFnOU4VKf8UvAtZgn0VuKT+G0wFlO3I=
github.com/lmittmann/tint v1.1.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
Expand All @@ -45,8 +53,11 @@ golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
29 changes: 29 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"runtime"
"strings"
"time"

"github.com/knadh/koanf/parsers/toml/v2"
Expand All @@ -28,6 +29,7 @@ type Config struct {
DNS DNSConfig `koanf:"dns"`
HTTP HTTPConfig `koanf:"http"`
HTTPS HTTPSConfig `koanf:"https"`
Logging LoggingConfig `koanf:"logging"`
}

type GeneralConfig struct {
Expand Down Expand Up @@ -60,6 +62,11 @@ type HTTPSConfig struct {
Key string `koanf:"key"`
}

type LoggingConfig struct {
LogFormat string `koanf:"format"`
Level string `koanf:"level"`
}

func Default() Config {
return Config{
General: GeneralConfig{ShutdownTimeout: 2 * time.Second},
Expand All @@ -84,6 +91,10 @@ func Default() Config {
Listen: ":8443",
Status: 200,
},
Logging: LoggingConfig{
LogFormat: "text",
Level: "info",
},
}
}

Expand Down Expand Up @@ -122,6 +133,24 @@ func (c Config) Validate() error {
if !c.DNS.Enabled && !c.HTTP.Enabled && !c.HTTPS.Enabled {
return errors.New("at least one service must be enabled")
}

// logging
logFormat := strings.ToLower(strings.TrimSpace(c.Logging.LogFormat))
switch logFormat {
case "", "text", "json":
// ok
default:
return fmt.Errorf("logging.format must be one of: text, json")
}
// default is "info" (see Default()); allow empty for backwards compat
logLevel := strings.ToLower(strings.TrimSpace(c.Logging.Level))
switch logLevel {
case "", "debug", "info", "warn", "warning", "error":
// ok
default:
return fmt.Errorf("logging.level must be one of: debug, info, warn, error")
}

return nil
}

Expand Down
6 changes: 6 additions & 0 deletions internal/config/default_config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,9 @@ status = 200
# ephemeral self-signed certificate at startup.
cert = ""
key = ""

[logging]
# Log output format: "text" (fixed-width columns) or "json".
format = "text"
# Minimum log level: "debug", "info", "warn", "error".
level = "info"
6 changes: 6 additions & 0 deletions internal/dnsserver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dnsserver

import (
"errors"
"log/slog"
"net/netip"

"github.com/miekg/dns"
Expand All @@ -16,12 +17,17 @@ func (s *Server) Name() string {
type Server struct {
conf Config
srv *dns.Server
log *slog.Logger
}

func NewService(conf Config) service.Service {
return &Server{conf: conf}
}

func (s *Server) SetLogger(logger *slog.Logger) {
s.log = logger
}

type Config struct {
Addr string
Net string
Expand Down
Loading
Loading