Skip to content

Commit

Permalink
Merge pull request #9 from bilalcaliskan/devel
Browse files Browse the repository at this point in the history
Devel
  • Loading branch information
bilalcaliskan authored Feb 7, 2024
2 parents bbdff75 + 3c369df commit dab9238
Show file tree
Hide file tree
Showing 16 changed files with 164 additions and 105 deletions.
9 changes: 5 additions & 4 deletions cmd/cli/add/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package add
import (
"fmt"

"github.com/rs/zerolog"

"github.com/bilalcaliskan/split-the-tunnel/internal/constants"

"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/utils"
"github.com/bilalcaliskan/split-the-tunnel/internal/logging"
"github.com/spf13/cobra"
)

Expand All @@ -28,15 +29,15 @@ to quickly create a Cobra application.`,
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
logger := logging.GetLogger()
logger := cmd.Context().Value(constants.LoggerKey{}).(zerolog.Logger)

logger.Info().Any("args", args).Msg("add called")
logger.Debug().Any("args", args).Msg("add command called")

for _, arg := range args {
req := fmt.Sprintf("%s %s", cmd.Name(), arg)
res, err := utils.SendCommandToDaemon(utils.SocketPath, req)
if err != nil {
logger.Error().Str("command", req).Err(err).Msg(constants.FailedToSendCommand)
logger.Error().Str("command", req).Err(err).Msg(constants.FailedToProcessCommand)
continue
}

Expand Down
28 changes: 25 additions & 3 deletions cmd/cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package main

import (
"context"
"errors"
"os"

"github.com/bilalcaliskan/split-the-tunnel/internal/constants"
"github.com/bilalcaliskan/split-the-tunnel/internal/logging"

"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/add"
"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/list"
"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/remove"
Expand All @@ -13,20 +18,35 @@ import (
)

var (
ver = version.Get()
cliCmd = &cobra.Command{
verbose bool
ver = version.Get()
cliCmd = &cobra.Command{
Use: "stt-cli",
Short: "",
Long: ``,
Version: ver.GitVersion,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
logger := logging.GetLogger()
logger.Info().Str("appVersion", ver.GitVersion).Str("goVersion", ver.GoVersion).Str("goOS", ver.GoOs).
Str("goArch", ver.GoArch).Str("gitCommit", ver.GitCommit).Str("buildDate", ver.BuildDate).
Msg("split-the-tunnel cli is started!")

if verbose {
logger = logging.WithVerbose()
logger.Debug().Str("foo", "bar").Msg("this is a dummy log")
}

cmd.SetContext(context.WithValue(cmd.Context(), constants.LoggerKey{}, logger))
},
}
)

func main() {
if err := cliCmd.Execute(); err != nil {
// extract the response code from the error
var resCode int
if cmdErr, ok := err.(*utils.CommandError); ok {
var cmdErr *utils.CommandError
if errors.As(err, &cmdErr) {
resCode = cmdErr.Code
}

Expand All @@ -39,6 +59,8 @@ func main() {
}

func init() {
cliCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "enable verbose mode")

cliCmd.AddCommand(add.AddCmd)
cliCmd.AddCommand(list.ListCmd)
cliCmd.AddCommand(remove.RemoveCmd)
Expand Down
9 changes: 5 additions & 4 deletions cmd/cli/list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package list
import (
"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/utils"
"github.com/bilalcaliskan/split-the-tunnel/internal/constants"
"github.com/bilalcaliskan/split-the-tunnel/internal/logging"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
)

Expand All @@ -25,12 +25,13 @@ to quickly create a Cobra application.`,
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
logger := logging.GetLogger()
logger := cmd.Context().Value(constants.LoggerKey{}).(zerolog.Logger)

logger.Debug().Msg("list command called")

logger.Info().Msg("list called")
res, err := utils.SendCommandToDaemon(utils.SocketPath, cmd.Name())
if err != nil {
logger.Error().Str("command", cmd.Name()).Err(err).Msg(constants.FailedToSendCommand)
logger.Error().Str("command", cmd.Name()).Err(err).Msg(constants.FailedToProcessCommand)

return &utils.CommandError{Err: err, Code: 10}
}
Expand Down
10 changes: 5 additions & 5 deletions cmd/cli/remove/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package remove
import (
"fmt"

"github.com/rs/zerolog"

"github.com/bilalcaliskan/split-the-tunnel/internal/constants"

"github.com/bilalcaliskan/split-the-tunnel/cmd/cli/utils"
"github.com/bilalcaliskan/split-the-tunnel/internal/logging"

"github.com/spf13/cobra"
)

Expand All @@ -29,15 +29,15 @@ to quickly create a Cobra application.`,
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
logger := logging.GetLogger()
logger := cmd.Context().Value(constants.LoggerKey{}).(zerolog.Logger)

logger.Info().Any("args", args).Msg("add called")
logger.Info().Any("args", args).Msg("remove command called")

for _, arg := range args {
req := fmt.Sprintf("%s %s", cmd.Name(), arg)
res, err := utils.SendCommandToDaemon(utils.SocketPath, req)
if err != nil {
logger.Error().Str("command", req).Err(err).Msg(constants.FailedToSendCommand)
logger.Error().Str("command", req).Err(err).Msg(constants.FailedToProcessCommand)
continue
}

Expand Down
6 changes: 4 additions & 2 deletions cmd/cli/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"encoding/json"
"net"

"github.com/bilalcaliskan/split-the-tunnel/internal/constants"

"github.com/pkg/errors"
)

Expand All @@ -23,13 +25,13 @@ type DaemonResponse struct {
func SendCommandToDaemon(socketPath, command string) (string, error) {
conn, err := net.Dial("unix", socketPath)
if err != nil {
return "", errors.Wrap(err, "failed to connect to unix domain socket")
return "", errors.Wrap(err, constants.FailedToConnectToUnixDomainSocket)
}
defer conn.Close()

_, err = conn.Write([]byte(command + "\n"))
if err != nil {
return "", errors.Wrap(err, "failed to write to unix domain socket")
return "", errors.Wrap(err, constants.FailedToWriteToUnixDomainSocket)
}

buf := make([]byte, 1024)
Expand Down
2 changes: 1 addition & 1 deletion cmd/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ var daemonCmd = &cobra.Command{
}
}()

logger.Info().Msg(constants.DaemonRunning)
logger.Info().Str("socket", socketPath).Msg(constants.DaemonRunning)

// Wait for termination signal
<-sigs
Expand Down
4 changes: 2 additions & 2 deletions cmd/daemon/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func GetRootOptions() *RootOptions {
}

func (opts *RootOptions) InitFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&opts.Verbose, "verbose", "", false, "verbose log")
cmd.Flags().BoolVarP(&opts.Verbose, "verbose", "", false, "verbose logging output")
cmd.Flags().StringVarP(&opts.DnsServers, "dns-servers", "", "", "comma separated dns servers to be used for DNS resolving")
cmd.Flags().IntVarP(&opts.CheckIntervalMin, "check-interval-min", "", 5, "")
cmd.Flags().IntVarP(&opts.CheckIntervalMin, "check-interval-min", "", 5, "routing table check interval with collected state, in minutes")
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.21

require (
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.31.0
github.com/rs/zerolog v1.32.0
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.8.4
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
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/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
Expand Down
5 changes: 3 additions & 2 deletions internal/constants/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ const (
FailedToResolveDomain = "failed to resolve domain"
FailedToMarshalResponse = "failed to marshal response"
FailedToWriteRouteEntry = "failed to write RouteEntry to state"
EntryNotFound = "entry not found"
EntryNotFound = "route entry not found in state"
NonVPNGatewayNotFound = "non-VPN gateway not found"
FailedToDecodeHex = "failed to decode hex string"
InvalidIpLength = "invalid IP length: %d"
FailedToSendCommand = "failed to send command to daemon"
FailedToProcessCommand = "failed to process command"
FailedToCleanupIPC = "failed to cleanup IPC"
FailedToInitializeIPC = "failed to initialize IPC"
FailedToRemoveRouteEntry = "failed to remove RouteEntry from state"
)
2 changes: 1 addition & 1 deletion internal/constants/infos.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package constants
const (
SuccessfullyProcessed = "successfully processed command"
IPCInitialized = "IPC is initialized"
DaemonRunning = "daemon is running..."
DaemonRunning = "daemon is running, waiting for requests over unix domain socket..."
TermSignalReceived = "termination signal received"
ShuttingDownDaemon = "shutting down daemon..."
AppStarted = "split-the-tunnel is started!"
Expand Down
7 changes: 7 additions & 0 deletions internal/constants/keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package constants

//const (
// LoggerKey = "logger"
//)

type LoggerKey struct{}
Loading

0 comments on commit dab9238

Please sign in to comment.