diff --git a/build_linux.ps1 b/build_linux.ps1 new file mode 100644 index 0000000..5ab8c64 --- /dev/null +++ b/build_linux.ps1 @@ -0,0 +1,2 @@ +$Env:GOOS="linux" +go build \ No newline at end of file diff --git a/cmd/bounce.go b/cmd/bounce.go index c1675cc..8337074 100644 --- a/cmd/bounce.go +++ b/cmd/bounce.go @@ -2,7 +2,7 @@ package cmd import ( "github.com/hdu-dn11/wg-quick-op/quick" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" ) @@ -13,23 +13,23 @@ var bounceCmd = &cobra.Command{ Long: `down and then up the interface,if the interface is not up, it will up the interface.`, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { - logrus.Errorln("bounce command requires exactly one interface name") + log.Error().Msg("bounce command requires exactly one interface name") return } cfgs := quick.MatchConfig(args[0]) for iface, cfg := range cfgs { - err := quick.Down(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Down(cfg, iface, log.With().Str("iface", iface).Logger()) if err != nil { - logrus.WithError(err).WithField("iface", iface).Errorln("failed to down interface") + log.Err(err).Str("iface", iface).Msg("failed to down interface") } } for iface, cfg := range cfgs { - err := quick.Up(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Up(cfg, iface, log.With().Str("iface", iface).Logger()) if err != nil { - logrus.WithError(err).WithField("iface", iface).Errorln("failed to up interface") + log.Err(err).Str("iface", iface).Msg("failed to up interface") } } - logrus.Infoln("bounce done") + log.Info().Msg("bounce done") }, } diff --git a/cmd/down.go b/cmd/down.go index 0b1bd65..2265725 100644 --- a/cmd/down.go +++ b/cmd/down.go @@ -2,8 +2,7 @@ package cmd import ( "github.com/hdu-dn11/wg-quick-op/quick" - "github.com/sirupsen/logrus" - + "github.com/rs/zerolog/log" "github.com/spf13/cobra" ) @@ -13,14 +12,14 @@ var downCmd = &cobra.Command{ Short: "down [interface name]", Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { - logrus.Errorln("up command requires exactly one interface name") + log.Error().Msg("up command requires exactly one interface name") return } cfgs := quick.MatchConfig(args[0]) for iface, cfg := range cfgs { - err := quick.Down(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Down(cfg, iface, log.With().Str("iface", iface).Logger()) if err != nil { - logrus.WithError(err).Errorln("failed to up interface") + log.Err(err).Msg("failed to up interface") } } }, diff --git a/cmd/root.go b/cmd/root.go index bb8dcf9..2ae80b8 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,7 +3,7 @@ package cmd import ( "github.com/hdu-dn11/wg-quick-op/conf" "github.com/hdu-dn11/wg-quick-op/lib/dns" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog" "os" "github.com/spf13/cobra" @@ -31,7 +31,7 @@ func init() { rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) { verbose, _ := cmd.Flags().GetBool("verbose") if verbose { - logrus.SetLevel(logrus.DebugLevel) + zerolog.SetGlobalLevel(zerolog.TraceLevel) } conf.Init(config) dns.Init() diff --git a/cmd/sync.go b/cmd/sync.go index 939034e..6c09d63 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -2,8 +2,7 @@ package cmd import ( "github.com/hdu-dn11/wg-quick-op/quick" - "github.com/sirupsen/logrus" - + "github.com/rs/zerolog/log" "github.com/spf13/cobra" ) @@ -15,14 +14,14 @@ var syncCmd = &cobra.Command{ it may result in address added by PostUp being deleted.'`, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { - logrus.Errorln("up command requires exactly one interface name") + log.Error().Msg("up command requires exactly one interface name") return } cfgs := quick.MatchConfig(args[0]) for iface, cfg := range cfgs { - err := quick.Sync(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Sync(cfg, iface, log.With().Str("iface", iface).Logger()) if err != nil { - logrus.WithError(err).Errorln("failed to sync interface") + log.Err(err).Msg("failed to sync interface") } } }, diff --git a/cmd/uninstall.go b/cmd/uninstall.go index 5b4faf4..3257f61 100644 --- a/cmd/uninstall.go +++ b/cmd/uninstall.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" ) -// uninstallCmd represents the uninstall command +// uninstallCmd represents the uninstallation command var uninstallCmd = &cobra.Command{ Use: "uninstall", Short: "uninstall wg-quick-op from /usr/sbin/wg-quick-op", diff --git a/cmd/up.go b/cmd/up.go index a98d35c..491fbd4 100644 --- a/cmd/up.go +++ b/cmd/up.go @@ -2,7 +2,7 @@ package cmd import ( "github.com/hdu-dn11/wg-quick-op/quick" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" ) @@ -16,14 +16,14 @@ regexp in supported, match interface with ^$ by default `, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { - logrus.Errorln("up command requires exactly one interface name") + log.Error().Msg("up command requires exactly one interface name") return } cfgs := quick.MatchConfig(args[0]) for iface, cfg := range cfgs { - err := quick.Up(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Up(cfg, iface, log.With().Str("iface", iface).Logger()) if err != nil { - logrus.WithError(err).Errorln("failed to up interface") + log.Err(err).Msg("failed to up interface") } } }, diff --git a/conf/config.go b/conf/config.go index 74c9a85..1a89bca 100644 --- a/conf/config.go +++ b/conf/config.go @@ -3,7 +3,8 @@ package conf import ( _ "embed" "github.com/fsnotify/fsnotify" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/viper" "os" "time" @@ -33,21 +34,21 @@ var EnhancedDNS struct { } var Log struct { - Level logrus.Level + Level zerolog.Level } func Init(file string) { if _, err := os.Stat(file); err != nil { if !os.IsNotExist(err) { - logrus.WithError(err).Fatalf("get stat of %s failed", file) + log.Fatal().Err(err).Msgf("get stat of %s failed", file) } - logrus.Infof("config not existed, creating at %s", file) + log.Info().Msgf("config not existed, creating at %s", file) created, err := os.Create(file) if err != nil { - logrus.WithError(err).Fatalf("create config at %s failed", file) + log.Fatal().Err(err).Msgf("create config at %s failed", file) } if _, err := created.Write(configSample); err != nil { - logrus.WithError(err).Fatalf("write config at %s failed", file) + log.Fatal().Err(err).Msgf("write config at %s failed", file) } } @@ -59,7 +60,7 @@ func Init(file string) { update() if err != nil { - logrus.WithError(err).Fatalf("read config from %s failed", file) + log.Fatal().Err(err).Msgf("read config from %s failed", file) } viper.OnConfigChange(func(e fsnotify.Event) { @@ -81,8 +82,8 @@ func update() { EnhancedDNS.DirectResolver.Enabled = viper.GetBool("enhanced_dns.direct_resolver.enabled") EnhancedDNS.DirectResolver.ROAFinder = viper.GetString("enhanced_dns.direct_resolver.roa_finder") - if level, err := logrus.ParseLevel(viper.GetString("log.level")); err == nil { + if level, err := zerolog.ParseLevel(viper.GetString("log.level")); err == nil { Log.Level = level - logrus.SetLevel(level) + zerolog.SetGlobalLevel(level) } } diff --git a/daemon/binary.go b/daemon/binary.go index 1d2a162..c0220b0 100644 --- a/daemon/binary.go +++ b/daemon/binary.go @@ -2,7 +2,7 @@ package daemon import ( "errors" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" "io" "os" "os/exec" @@ -15,60 +15,60 @@ const installed = "/usr/sbin/wg-quick-op" func Install() { file, err := exec.LookPath(os.Args[0]) if err != nil && !errors.Is(err, exec.ErrDot) { - logrus.WithError(err).Errorln("fetch current binary path failed") + log.Err(err).Msg("fetch current binary path failed") return } absFile, err := filepath.Abs(file) if err != nil { - logrus.WithField("path", absFile).WithError(err).Errorln("The absPath failed") + log.Err(err).Str("path", absFile).Msg("The absPath failed") return } - logrus.Infof("current binary: %v", absFile) + log.Info().Msgf("current binary: %v", absFile) originFp, err := os.Open(absFile) if err != nil { - logrus.WithError(err).Errorf("open current binary failed") + log.Err(err).Msgf("open current binary failed") return } defer originFp.Close() if _, err := os.Stat(installed); err != nil { if !os.IsNotExist(err) { - logrus.WithError(err).Errorf("fetch binary stat failed") + log.Err(err).Msgf("fetch binary stat failed") return } } else { if err := os.RemoveAll(installed); err != nil { - logrus.WithError(err).Errorf("remove old binary failed") + log.Err(err).Msgf("remove old binary failed") return } } fp, err := os.OpenFile(installed, os.O_CREATE|os.O_RDWR, os.ModePerm) if err != nil { - logrus.WithError(err).Errorf("cannot write to %v", installed) + log.Err(err).Msgf("write to %v", installed) return } defer fp.Close() _, err = io.Copy(fp, originFp) if err != nil { _ = os.RemoveAll(installed) - logrus.Errorf("copy binary to %v failed: %s", installed, err) + log.Err(err).Msgf("copy binary to %s", installed) return } - logrus.Infof("installed wg-quick-op") + log.Info().Msg("installed wg-quick-op") } func Uninstall() { file, err := exec.LookPath("wg-quick-op") if err != nil { - logrus.WithError(err).Errorln("find wg-quick-op failed") + log.Err(err).Msg("find wg-quick-op failed") return } if err := os.RemoveAll(file); err != nil { - logrus.WithField("path", file).WithError(err).Errorln("remove binary failed") + log.Err(err).Str("path", file).Msg("remove binary failed") return } } diff --git a/daemon/daemon.go b/daemon/daemon.go index c3f5f3d..1f5fb7c 100644 --- a/daemon/daemon.go +++ b/daemon/daemon.go @@ -5,7 +5,8 @@ import ( "github.com/hdu-dn11/wg-quick-op/lib/dns" "github.com/hdu-dn11/wg-quick-op/quick" "github.com/hdu-dn11/wg-quick-op/utils" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "github.com/vishvananda/netlink" "slices" "sync" @@ -27,10 +28,10 @@ func newDaemon() *daemon { func (d *daemon) Run() { // prepare config for _, iface := range utils.FindIface(conf.DDNS.IfaceOnly, conf.DDNS.IfaceSkip) { - logrus.WithField("iface", iface).Infoln("find iface, init ddns config") + log.Info().Str("iface", iface).Msg("find iface, init ddns config") ddns, err := newDDNS(iface) if err != nil { - logrus.WithField("iface", iface).WithError(err).Error("failed to init ddns config") + log.Err(err).Str("iface", iface).Msg("failed to init ddns config") d.pendingIfaces = append(d.pendingIfaces, iface) continue } @@ -46,7 +47,7 @@ func (d *daemon) Run() { for _, iface := range d.runIfaces { peers, err := quick.PeerStatus(iface.name) if err != nil { - logrus.WithError(err).WithField("iface", iface.name).Error("failed to get device") + log.Err(err).Str("iface", iface.name).Msg("failed to get device") continue } @@ -54,21 +55,21 @@ func (d *daemon) Run() { for _, peer := range peers { if peer.Endpoint == nil || peer.Endpoint.IP == nil { - logrus.WithField("iface", iface.name).WithField("peer", peer.PublicKey).Debugln("peer endpoint is nil, skip it") + log.Debug().Str("iface", iface.name).Str("peer", peer.PublicKey.String()).Msg("peer endpoint is nil, skip it") continue } if time.Since(peer.LastHandshakeTime) < conf.DDNS.HandleShakeMax { - logrus.WithField("iface", iface.name).WithField("peer", peer.PublicKey).Debugln("peer ok") + log.Debug().Str("iface", iface.name).Str("peer", peer.PublicKey.String()).Msg("peer ok") continue } - logrus.WithField("iface", iface.name).WithField("peer", peer.PublicKey).Debugln("peer handshake timeout, re-resolve endpoint") + log.Debug().Str("iface", iface.name).Str("peer", peer.PublicKey.String()).Msg("peer handshake timeout, re-resolve endpoint") endpoint, ok := iface.unresolvedEndpoints[peer.PublicKey] if !ok { continue } addr, err := dns.ResolveUDPAddr("", endpoint) if err != nil { - logrus.WithField("iface", iface).WithField("peer", peer.PublicKey).WithError(err).Error("failed to resolve endpoint") + log.Err(err).Str("iface", iface.name).Str("peer", peer.PublicKey.String()).Msg("failed to resolve endpoint") continue } @@ -82,25 +83,25 @@ func (d *daemon) Run() { } if !wgSync { - logrus.WithField("iface", iface.name).Debugln("same addr, skip") + log.Debug().Str("iface", iface.name).Msg("same addr, skip") continue } link, err := netlink.LinkByName(iface.name) if err != nil { - logrus.WithField("iface", iface.name).WithError(err).Error("get link failed") + log.Err(err).Str("iface", iface.name).Msg("get link failed") continue } - if err := quick.SyncWireguardDevice(iface.cfg, link, logrus.WithField("iface", iface.name)); err != nil { - logrus.WithField("iface", iface.name).WithError(err).Error("sync device failed") + if err := quick.SyncWireguardDevice(iface.cfg, link, log.With().Str("iface", iface.name).Logger()); err != nil { + log.Err(err).Str("iface", iface.name).Msg("sync device failed") continue } - logrus.WithField("iface", iface.name).Infoln("re-resolve done") + log.Info().Str("iface", iface.name).Msg("re-resolve done") } d.lock.Unlock() - logrus.Infoln("endpoint re-resolve done") + log.Info().Msg("endpoint re-resolve done") } } @@ -113,7 +114,7 @@ func (d *daemon) registerWatch() { if conf.DDNS.IfaceSkip != nil && slices.Index(conf.DDNS.IfaceSkip, name) != -1 { return } - logrus.WithField("iface", name).Infoln("iface update, add to pending list") + log.Info().Str("iface", name).Msg("iface update, add to pending list") d.lock.Lock() defer d.lock.Unlock() if slices.Index(d.pendingIfaces, name) == -1 { @@ -127,7 +128,7 @@ func (d *daemon) registerWatch() { if conf.DDNS.IfaceSkip != nil && slices.Index(conf.DDNS.IfaceSkip, name) != -1 { return } - logrus.WithField("iface", name).Infoln("iface remove, remove from run list") + log.Info().Str("iface", name).Msg("iface remove, remove from run list") d.lock.Lock() defer d.lock.Unlock() delete(d.runIfaces, name) @@ -145,10 +146,10 @@ func (d *daemon) updateLoop() { for _, iface := range d.pendingIfaces { ddns, err := newDDNS(iface) if err != nil { - logrus.WithField("iface", iface).WithError(err).Error("failed to init ddns config") + log.Err(err).Str("iface", iface).Msg("failed to init ddns config") continue } - logrus.WithField("iface", iface).Infoln("init success, move to run list") + log.Info().Str("iface", iface).Msg("init success, move to run list") d.runIfaces[iface] = ddns deleteList = append(deleteList, iface) } diff --git a/daemon/ddns.go b/daemon/ddns.go index 9939024..56ff900 100644 --- a/daemon/ddns.go +++ b/daemon/ddns.go @@ -2,7 +2,7 @@ package daemon import ( "github.com/hdu-dn11/wg-quick-op/quick" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" "golang.zx2c4.com/wireguard/wgctrl/wgtypes" ) @@ -23,7 +23,7 @@ func newDDNS(iface string) (*ddns, error) { endpoints, err := quick.GetUnresolvedEndpoints(iface) if err != nil { - logrus.WithField("iface", iface).WithError(err).Error("failed to get unresolved unresolved Endpoint") + log.Err(err).Str("iface", iface).Msg("failed to get unresolved unresolved Endpoint") } ddnsConfig.unresolvedEndpoints = endpoints return &ddnsConfig, nil diff --git a/daemon/service.go b/daemon/service.go index 19c7720..ac9e501 100644 --- a/daemon/service.go +++ b/daemon/service.go @@ -6,7 +6,8 @@ import ( "github.com/hdu-dn11/wg-quick-op/conf" "github.com/hdu-dn11/wg-quick-op/quick" "github.com/hdu-dn11/wg-quick-op/utils" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "os" "os/exec" ) @@ -30,55 +31,55 @@ func startOnBoot() { iface := iface cfg, err := quick.GetConfig(iface) if err != nil { - logrus.WithField("iface", iface).WithError(err).Error("failed to get config") + log.Err(err).Str("iface", iface).Msg("failed to get config") continue } go func() { if err := <-utils.GoRetry(5, func() error { - err := quick.Up(cfg, iface, logrus.WithField("iface", iface)) + err := quick.Up(cfg, iface, log.With().Str("iface", iface).Logger()) if err == nil { return nil } if errors.Is(err, os.ErrExist) { - logrus.WithField("iface", iface).Infoln("interface already up") + log.Info().Str("iface", iface).Msg("interface already up") return nil } return err }); err != nil { - logrus.WithField("iface", iface).WithError(err).Error("failed to up interface") + log.Err(err).Str("iface", iface).Msg("failed to up interface") return } - logrus.Infof("interface %s up", iface) + log.Info().Msgf("interface %s up", iface) }() } - logrus.Infoln("all interface parsed") + log.Info().Msg("all interface parsed") } func AddService() { _, err := exec.LookPath("wg-quick-op") if err != nil { if !errors.Is(err, exec.ErrDot) { - logrus.WithError(err).Errorln("look up wg-quick-up failed") + log.Err(err).Msgf("look up wg-quick-up failed") } - logrus.Warningln("wg-quick-op hasn't been installed to path, let's turn to install it") + log.Warn().Msg("wg-quick-op hasn't been installed to path, let's turn to install it") Install() } if _, err := os.Stat(ServicePath); err == nil { err := os.Remove(ServicePath) if err != nil { - logrus.Warnf("remove %s failed", ServicePath) + log.Warn().Msgf("remove %s failed", ServicePath) } } file, err := os.OpenFile(ServicePath, os.O_CREATE|os.O_RDWR, 0755) if err != nil { - logrus.WithError(err).Fatalf("open %s failed", ServicePath) + log.Fatal().Err(err).Msgf("open %s failed", ServicePath) } defer file.Close() if _, err := file.Write(ServiceFile); err != nil { - logrus.WithError(err).Fatalf("write %s failed", ServicePath) + log.Fatal().Err(err).Msgf("write %s failed", ServicePath) } - logrus.Infoln("add wg-quick-op to init.d success") + log.Info().Msg("add wg-quick-op to init.d success") } func RmService() { @@ -87,6 +88,6 @@ func RmService() { if os.IsNotExist(err) { return } - logrus.WithError(err).Errorln("delete service failed") + log.Err(err).Msgf("delete service failed") } } diff --git a/daemon/watcher.go b/daemon/watcher.go index 81c0d04..28a5636 100644 --- a/daemon/watcher.go +++ b/daemon/watcher.go @@ -2,7 +2,8 @@ package daemon import ( "github.com/fsnotify/fsnotify" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "path/filepath" "strings" ) @@ -15,7 +16,7 @@ type WireguardWatcher struct { func (w *WireguardWatcher) Watch() { watcher, err := fsnotify.NewWatcher() if err != nil { - logrus.Errorf("failed to create watcher: %v", err) + log.Error().Msgf("failed to create watcher: %v", err) } watcher.Add("/etc/wireguard") for { @@ -30,13 +31,13 @@ func (w *WireguardWatcher) Watch() { } name := strings.TrimSuffix(filename, ".conf") if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create { - logrus.Info("update file:", event.Name) + log.Info().Msgf("update file: %s", event.Name) if w.UpdateCallback != nil { w.UpdateCallback(name) } } if event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename { - logrus.Info("remove file:", event.Name) + log.Info().Msgf("remove file: %s" + event.Name) if w.RemoveCallback != nil { w.RemoveCallback(name) } @@ -45,7 +46,7 @@ func (w *WireguardWatcher) Watch() { if !ok { return } - logrus.Error("error:", err) + log.Err(err).Msgf("watcher error") } } } diff --git a/daemon/wg-quick-op b/daemon/wg-quick-op index 7f8f7a6..a4b59e5 100644 --- a/daemon/wg-quick-op +++ b/daemon/wg-quick-op @@ -1,31 +1,12 @@ #!/bin/sh /etc/rc.common USE_PROCD=1 -START=100 -STOP=1 +START=99 +STOP=10 WG_QUICK_OP_CONF="/etc/wg-quick-op.toml" -MAX_WAIT=3600 -INTERVAL=1 - -boot() { - waited_time=0 - while [ $waited_time -lt $MAX_WAIT ]; do - if nslookup localhost >/dev/null 2>&1 || dig +short localhost >/dev/null 2>&1; then - start - return - else - sleep $INTERVAL - waited_time=$((waited_time + $INTERVAL)) - fi - done - - echo "localhost is not resolved. Not starting myservice..." -} - start_service() { - mkdir -p /var/run procd_open_instance procd_set_param command wg-quick-op service -c $WG_QUICK_OP_CONF procd_set_param stdout 1 @@ -33,7 +14,3 @@ start_service() { procd_set_param respawn procd_close_instance } - -reload_service() { - procd_send_signal wg-quick-op -} diff --git a/go.mod b/go.mod index c7fafc1..c7436ef 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,9 @@ module github.com/hdu-dn11/wg-quick-op go 1.19 require ( + github.com/fsnotify/fsnotify v1.7.0 github.com/miekg/dns v1.1.59 - github.com/sirupsen/logrus v1.9.3 + github.com/rs/zerolog v1.32.0 github.com/spf13/cobra v1.8.0 github.com/spf13/viper v1.18.1 github.com/stretchr/testify v1.8.4 @@ -15,12 +16,13 @@ require ( require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/google/go-cmp v0.5.9 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/native v1.1.0 // indirect github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/mdlayher/genetlink v1.3.2 // indirect github.com/mdlayher/netlink v1.7.2 // indirect github.com/mdlayher/socket v0.4.1 // indirect diff --git a/go.sum b/go.sum index ec9be0e..274df34 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,4 @@ +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -6,6 +7,7 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8Yc github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= @@ -18,6 +20,11 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mdlayher/genetlink v1.3.2 h1:KdrNKe+CTu+IbZnm/GVUMXSqBBLqcGpRDa0xkQy56gw= github.com/mdlayher/genetlink v1.3.2/go.mod h1:tcC3pkCrPUGIKKsCsp0B3AdaaKuHtaxoJRz3cc+528o= github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g= @@ -31,17 +38,19 @@ github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyua github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0= +github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= @@ -58,7 +67,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= @@ -84,7 +92,9 @@ golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= diff --git a/lib/dns/dns.go b/lib/dns/dns.go index 43f852b..b3c65b7 100644 --- a/lib/dns/dns.go +++ b/lib/dns/dns.go @@ -5,7 +5,8 @@ import ( "github.com/hdu-dn11/wg-quick-op/conf" "github.com/hdu-dn11/wg-quick-op/utils" "github.com/miekg/dns" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "net" "net/netip" "strconv" @@ -63,7 +64,7 @@ func resolveIPAddr(addr string) (net.IP, error) { return err }); err != nil { // fallback - logrus.Warnf("directDNS failed: %v", err) + log.Warn().Msgf("directDNS failed: %v", err) ip, err := net.ResolveIPAddr("ip", addr) if err != nil { return nil, fmt.Errorf("fallback failed: %w", err) diff --git a/lib/dns/dns_test.go b/lib/dns/dns_test.go index 8f3aba1..775d625 100644 --- a/lib/dns/dns_test.go +++ b/lib/dns/dns_test.go @@ -6,6 +6,7 @@ func TestDirectDNS(t *testing.T) { RoaFinder = "223.5.5.5:53" testcases := []string{ "www.baidu.com", + "dorm.ec3o.fun", } for _, testcase := range testcases { ip, err := directDNS(testcase) diff --git a/main.go b/main.go index c552e61..46683f1 100644 --- a/main.go +++ b/main.go @@ -2,11 +2,12 @@ package main import ( "github.com/hdu-dn11/wg-quick-op/cmd" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "os" ) func main() { - logrus.SetOutput(os.Stdout) + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) cmd.Execute() } diff --git a/quick/config.go b/quick/config.go index 4841d74..b5ea52c 100644 --- a/quick/config.go +++ b/quick/config.go @@ -6,7 +6,8 @@ import ( "encoding/base64" "fmt" "github.com/hdu-dn11/wg-quick-op/lib/dns" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "net" "os" "path/filepath" @@ -199,7 +200,7 @@ func MatchConfig(pattern string) map[string]*Config { files, err := os.ReadDir("/etc/wireguard") if err != nil { - logrus.WithError(err).Fatalln("cannot read /etc/wireguard") + log.Fatal().Err(err).Msg("cannot read /etc/wireguard") return nil } @@ -210,17 +211,17 @@ func MatchConfig(pattern string) map[string]*Config { } matched, err := regexp.Match(pattern, []byte(file.Name()[:len(file.Name())-5])) if err != nil { - logrus.WithError(err).Fatalln("cannot match pattern") + log.Fatal().Err(err).Msg("cannot match pattern") return nil } if matched { b, err := os.ReadFile(filepath.Join("/etc/wireguard/" + file.Name())) if err != nil { - logrus.WithError(err).Fatalln("cannot read file") + log.Fatal().Err(err).Msg("cannot read file") } c := &Config{} if err := c.UnmarshalText(b); err != nil { - logrus.WithError(err).Fatalln("cannot parse config file") + log.Fatal().Err(err).Msg("cannot parse config file") } cfgs[file.Name()[:len(file.Name())-5]] = c } diff --git a/quick/wg.go b/quick/wg.go index ac97b2a..e41fc89 100644 --- a/quick/wg.go +++ b/quick/wg.go @@ -2,92 +2,92 @@ package quick import ( "bytes" + "errors" "fmt" + "github.com/rs/zerolog" "net" "os" "os/exec" "strings" "syscall" - "github.com/sirupsen/logrus" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" ) // Up sets and configures the wg interface. Mostly equivalent to `wg-quick up iface` -func Up(cfg *Config, iface string, logger logrus.FieldLogger) error { - log := logger.WithField("iface", iface) +func Up(cfg *Config, iface string, logger zerolog.Logger) error { _, err := netlink.LinkByName(iface) if err == nil { return os.ErrExist } - if _, ok := err.(netlink.LinkNotFoundError); !ok { + var linkNotFoundError netlink.LinkNotFoundError + if !errors.As(err, &linkNotFoundError) { return err } for _, dns := range cfg.DNS { - if err := execSh("resolvconf -a tun.%i -m 0 -x", iface, log, fmt.Sprintf("nameserver %s\n", dns)); err != nil { + if err := execSh("resolvconf -a tun.%i -m 0 -x", iface, logger, fmt.Sprintf("nameserver %s\n", dns)); err != nil { return err } } for _, cmd := range cfg.PreUp { - if err := execSh(cmd, iface, log); err != nil { + if err := execSh(cmd, iface, logger); err != nil { return err } - log.Infoln("applied pre-up command") + logger.Info().Msg("applied pre-up command") } if err := Sync(cfg, iface, logger); err != nil { return err } for _, cmd := range cfg.PostUp { - if err := execSh(cmd, iface, log); err != nil { + if err := execSh(cmd, iface, logger); err != nil { return err } - log.Infoln("applied post-up command") + logger.Info().Msg("applied post-up command") } return nil } // Down destroys the wg interface. Mostly equivalent to `wg-quick down iface` -func Down(cfg *Config, iface string, logger logrus.FieldLogger) error { - log := logger.WithField("iface", iface) +func Down(cfg *Config, iface string, logger zerolog.Logger) error { link, err := netlink.LinkByName(iface) if err != nil { return err } if len(cfg.DNS) > 1 { - if err := execSh("resolvconf -d tun.%s", iface, log); err != nil { + if err := execSh("resolvconf -d tun.%s", iface, logger); err != nil { return err } } for _, cmd := range cfg.PreDown { - if err := execSh(cmd, iface, log); err != nil { + if err := execSh(cmd, iface, logger); err != nil { return err } - log.Infoln("applied pre-down command") + logger.Info().Msg("applied pre-down command") } if err := netlink.LinkDel(link); err != nil { return err } - log.Infoln("link deleted") + logger.Info().Msg("link deleted") for _, cmd := range cfg.PostDown { - if err := execSh(cmd, iface, log); err != nil { + if err := execSh(cmd, iface, logger); err != nil { return err } - log.Infoln("applied post-down command") + logger.Info().Msg("applied post-down command") } return nil } -func execSh(command string, iface string, log logrus.FieldLogger, stdin ...string) error { +func execSh(command string, iface string, logger zerolog.Logger, stdin ...string) error { cmd := exec.Command("sh", "-ce", strings.ReplaceAll(command, "%i", iface)) if len(stdin) > 0 { - log = log.WithField("stdin", strings.Join(stdin, "")) + logger = logger.With().Str("stdin", strings.Join(stdin, "")).Logger() b := &bytes.Buffer{} for _, ln := range stdin { if _, err := fmt.Fprint(b, ln); err != nil { @@ -98,10 +98,10 @@ func execSh(command string, iface string, log logrus.FieldLogger, stdin ...strin } out, err := cmd.CombinedOutput() if err != nil { - log.WithError(err).Errorf("failed to execute %s:\n%s", cmd.Args, out) + logger.Err(err).Msgf("failed to execute %s:\n%s", cmd.Args, out) return err } - log.Infof("executed %s:\n%s", cmd.Args, out) + logger.Info().Msgf("executed %s:\n%s", cmd.Args, out) return nil } @@ -111,27 +111,25 @@ func execSh(command string, iface string, log logrus.FieldLogger, stdin ...strin // * SyncWireguardDevice --> configures allowedIP & other wireguard specific settings // * SyncAddress --> synces linux addresses bounded to this interface // * SyncRoutes --> synces all allowedIP routes to route to this interface, if Table is not off -func Sync(cfg *Config, iface string, logger logrus.FieldLogger) error { - log := logger.WithField("iface", iface) - - link, err := SyncLink(cfg, iface, log) +func Sync(cfg *Config, iface string, logger zerolog.Logger) error { + link, err := SyncLink(cfg, iface, logger) if err != nil { - log.WithError(err).Errorln("cannot sync wireguard link") + logger.Err(err).Msg("cannot sync wireguard link") return err } - log.Info("synced link") + logger.Info().Msg("synced link") - if err := SyncWireguardDevice(cfg, link, log); err != nil { - log.WithError(err).Errorln("cannot sync wireguard link") + if err := SyncWireguardDevice(cfg, link, logger); err != nil { + logger.Err(err).Msg("cannot sync wireguard link") return err } - log.Info("synced link") + logger.Info().Msg("synced link") - if err := SyncAddress(cfg, link, log); err != nil { - log.WithError(err).Errorln("cannot sync addresses") + if err := SyncAddress(cfg, link, logger); err != nil { + logger.Err(err).Msg("cannot sync addresses") return err } - log.Info("synced addresss") + logger.Info().Msg("synced addresses") if cfg.Table != nil { var managedRoutes []net.IPNet @@ -140,38 +138,39 @@ func Sync(cfg *Config, iface string, logger logrus.FieldLogger) error { managedRoutes = append(managedRoutes, rt) } } - if err := SyncRoutes(cfg, link, managedRoutes, log); err != nil { - log.WithError(err).Errorln("cannot sync routes") + if err := SyncRoutes(cfg, link, managedRoutes, logger); err != nil { + logger.Err(err).Msg("cannot sync routes") return err } - log.Info("synced routed") + logger.Info().Msg("synced routed") } else { - log.Info("Table=off, skip route sync") + logger.Info().Msg("Table=off, skip route sync") } - log.Info("Successfully synced device") + logger.Info().Msg("Successfully synced device") return nil } -// SyncWireguardDevice synces wireguard vpn setting on the given link. It does not set routes/addresses beyond wg internal crypto-key routing, only handles wireguard specific settings -func SyncWireguardDevice(cfg *Config, link netlink.Link, log logrus.FieldLogger) error { +// SyncWireguardDevice syncs wireguard vpn setting on the given link. It does not set routes/addresses beyond wg internal crypto-key routing, only handles wireguard specific settings +func SyncWireguardDevice(cfg *Config, link netlink.Link, logger zerolog.Logger) error { if err := client.ConfigureDevice(link.Attrs().Name, cfg.Config); err != nil { - log.WithError(err).Error("cannot configure device") + logger.Err(err).Msg("cannot configure device") return err } return nil } -// SyncLink synces link state with the config. It does not sync Wireguard settings, just makes sure the device is up and type wireguard -func SyncLink(cfg *Config, iface string, log logrus.FieldLogger) (netlink.Link, error) { +// SyncLink syncs link state with the config. It does not sync Wireguard settings, just makes sure the device is up and type wireguard +func SyncLink(cfg *Config, iface string, logger zerolog.Logger) (netlink.Link, error) { link, err := netlink.LinkByName(iface) if err != nil { - if _, ok := err.(netlink.LinkNotFoundError); !ok { - log.WithError(err).Error("cannot read link") + var linkNotFoundError netlink.LinkNotFoundError + if !errors.As(err, &linkNotFoundError) { + logger.Err(err).Msg("cannot read link") return nil, err } - log.Info("link not found, creating") + logger.Info().Msg("link not found, creating") if cfg.WgBin == "" { wgLink := &netlink.GenericLink{ @@ -182,83 +181,77 @@ func SyncLink(cfg *Config, iface string, log logrus.FieldLogger) (netlink.Link, LinkType: "wireguard", } if err := netlink.LinkAdd(wgLink); err != nil { - log.WithError(err).Error("cannot create link") + logger.Err(err).Msg("cannot create link") return nil, err } } else { - log.Infof("using %s to create link", cfg.WgBin) + logger.Info().Msgf("using %s to create link", cfg.WgBin) output, err := exec.Command(cfg.WgBin, iface).CombinedOutput() if err != nil { - log.WithError(err).WithField("output", string(output)).Error("cannot create link") + logger.Err(err).Str("output", string(output)).Msg("cannot create link") return nil, err } } link, err = netlink.LinkByName(iface) if err != nil { - log.WithError(err).Error("cannot read link") + logger.Err(err).Msg("cannot read link") return nil, err } } if err := netlink.LinkSetUp(link); err != nil { - log.WithError(err).Error("cannot set link up") + logger.Err(err).Msg("cannot set link up") return nil, err } - log.Info("set device up") + logger.Info().Msg("set device up") return link, nil } // SyncAddress adds/deletes all lind assigned IPV4 addressed as specified in the config -func SyncAddress(cfg *Config, link netlink.Link, log logrus.FieldLogger) error { +func SyncAddress(cfg *Config, link netlink.Link, logger zerolog.Logger) error { addrs, err := netlink.AddrList(link, syscall.AF_INET) if err != nil { - log.Error(err, "cannot read link address") + logger.Err(err).Msg("cannot read link address") return err } // nil addr means I've used it presentAddresses := make(map[string]netlink.Addr, 0) for _, addr := range addrs { - log.WithFields(map[string]interface{}{ - "addr": fmt.Sprint(addr.IPNet), - "label": addr.Label, - }).Debugf("found existing address: %v", addr) + logger.Debug().Str("addr", addr.IPNet.String()).Str("label", addr.Label).Msg("found existing address") presentAddresses[addr.IPNet.String()] = addr } for _, addr := range cfg.Address { - log := log.WithField("addr", addr.String()) + logger := logger.With().Str("addr", addr.String()).Logger() _, present := presentAddresses[addr.String()] presentAddresses[addr.String()] = netlink.Addr{} // mark as present if present { - log.Info("address present") + logger.Info().Msg("address present") continue } if err := netlink.AddrAdd(link, &netlink.Addr{ IPNet: &addr, Label: cfg.AddressLabel, }); err != nil { - if err != syscall.EEXIST { - log.WithError(err).Error("cannot add addr") + if !errors.Is(err, syscall.EEXIST) { + logger.Err(err).Msg("cannot add addr") return err } } - log.Info("address added") + logger.Info().Msg("address added") } for _, addr := range presentAddresses { if addr.IPNet == nil { continue } - log := log.WithFields(map[string]interface{}{ - "addr": addr.IPNet.String(), - "label": addr.Label, - }) + logger := logger.With().Str("addr", addr.IPNet.String()).Str("label", addr.Label).Logger() if err := netlink.AddrDel(link, &addr); err != nil { - log.WithError(err).Error("cannot delete addr") + logger.Err(err).Msg("cannot delete addr") return err } - log.Info("addr deleted") + logger.Info().Msg("addr deleted") } return nil } @@ -279,20 +272,20 @@ func fillRouteDefaults(rt *netlink.Route) { } // SyncRoutes adds/deletes all route assigned IPV4 addressed as specified in the config -func SyncRoutes(cfg *Config, link netlink.Link, managedRoutes []net.IPNet, log logrus.FieldLogger) error { +func SyncRoutes(cfg *Config, link netlink.Link, managedRoutes []net.IPNet, logger zerolog.Logger) error { if cfg.Table == nil { return nil } var wantedRoutes = make(map[string][]netlink.Route, len(managedRoutes)) presentRoutes, err := netlink.RouteList(link, syscall.AF_INET) if err != nil { - log.Error(err, "cannot read existing routes") + logger.Err(err).Msg("cannot read existing routes") return err } for _, rt := range managedRoutes { rt := rt // make copy - log.WithField("dst", rt.String()).Debug("managing route") + logger.Debug().Str("dst", rt.String()).Msg("managing route") nrt := netlink.Route{ LinkIndex: link.Attrs().Index, @@ -307,18 +300,18 @@ func SyncRoutes(cfg *Config, link netlink.Link, managedRoutes []net.IPNet, log l for _, rtLst := range wantedRoutes { for _, rt := range rtLst { rt := rt // make copy - log := log.WithFields(map[string]interface{}{ - "route": rt.Dst.String(), - "protocol": rt.Protocol, - "table": rt.Table, - "type": rt.Type, - "metric": rt.Priority, - }) + log := logger.With(). + Str("route", rt.Dst.String()). + Int("protocol", rt.Protocol). + Int("table", rt.Table). + Int("type", rt.Type). + Int("metric", rt.Priority). + Logger() if err := netlink.RouteReplace(&rt); err != nil { - log.WithError(err).Errorln("cannot add/replace route") + log.Err(err).Msg("cannot add/replace route") return err } - log.Infoln("route added/replaced") + log.Info().Msg("route added/replaced") } } @@ -332,33 +325,33 @@ func SyncRoutes(cfg *Config, link netlink.Link, managedRoutes []net.IPNet, log l } for _, rt := range presentRoutes { - log := log.WithFields(map[string]interface{}{ - "route": rt.Dst.String(), - "protocol": rt.Protocol, - "table": rt.Table, - "type": rt.Type, - "metric": rt.Priority, - }) + log := logger.With(). + Str("route", rt.Dst.String()). + Int("protocol", rt.Protocol). + Int("table", rt.Table). + Int("type", rt.Type). + Int("metric", rt.Priority). + Logger() if !(rt.Table == *cfg.Table || (*cfg.Table == 0 && rt.Table == unix.RT_CLASS_MAIN)) { - log.Debug("wrong table for route, skipping") + log.Debug().Msg("wrong table for route, skipping") continue } if !(rt.Protocol == cfg.RouteProtocol) { - log.Infof("skipping route deletion, not owned by this daemon") + log.Info().Msgf("skipping route deletion, not owned by this daemon") continue } if checkWanted(rt) { - log.Debug("route wanted, skipping deleting") + log.Debug().Msg("route wanted, skipping deleting") continue } if err := netlink.RouteDel(&rt); err != nil { - log.WithError(err).Error("cannot delete route") + log.Err(err).Msg("cannot delete route") return err } - log.Info("route deleted") + log.Info().Msg("route deleted") } return nil } diff --git a/utils/utils.go b/utils/utils.go index 34a4156..d7c2c64 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -1,7 +1,7 @@ package utils import ( - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" "os" "slices" "strings" @@ -38,7 +38,7 @@ func FindIface(only []string, skip []string) []string { var ifaceList []string entry, err := os.ReadDir("/etc/wireguard") if err != nil { - logrus.WithError(err).Errorln("read dir /etc/wireguard failed when find iface") + log.Err(err).Msg("read dir /etc/wireguard failed when find iface") return nil } for _, v := range entry {