Skip to content

Commit

Permalink
update executor dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
et-nik committed Feb 16, 2024
1 parent 0a06382 commit 65d75a4
Show file tree
Hide file tree
Showing 14 changed files with 165 additions and 73 deletions.
49 changes: 49 additions & 0 deletions internal/app/components/custom_handlers/get_tool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package custom_handlers

import (
"context"
"io"
"os"
"path/filepath"

"github.com/gameap/daemon/internal/app/config"
"github.com/gameap/daemon/internal/app/contracts"
"github.com/gameap/daemon/internal/app/domain"
"github.com/hashicorp/go-getter"
"github.com/pkg/errors"
)

type GetTool struct {
cfg *config.Config
}

func NewGetTool(cfg *config.Config) *GetTool {
return &GetTool{cfg: cfg}
}

func (g *GetTool) Handle(ctx context.Context, args []string, out io.Writer, _ contracts.ExecutorOptions) (int, error) {
source := args[0]
fileName := filepath.Base(source)
destination := filepath.Join(g.cfg.ToolsPath, fileName)

c := getter.Client{
Ctx: ctx,
Src: args[0],
Dst: destination,
Mode: getter.ClientModeFile,
}

_, _ = out.Write([]byte("Getting tool from " + source + " to " + destination + " ..."))
err := c.Get()
if err != nil {
return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to get tool")
}

err = os.Chmod(destination, 0700)
if err != nil {
_, _ = out.Write([]byte("Failed to chmod tool"))
return int(domain.ErrorResult), errors.WithMessage(err, "[components.GetTool] failed to chmod tool")
}

return int(domain.ErrorResult), nil
}
48 changes: 48 additions & 0 deletions internal/app/components/custom_handlers/server_console.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package custom_handlers

import (
"context"
"io"

"github.com/gameap/daemon/internal/app/config"
"github.com/gameap/daemon/internal/app/contracts"
"github.com/gameap/daemon/internal/app/domain"
)

type outputReader interface {
GetOutput(ctx context.Context, server *domain.Server, out io.Writer) (domain.Result, error)
}

type OutputReader struct {
cfg *config.Config
getter outputReader
}

func NewOutputReader(cfg *config.Config, getter outputReader) *OutputReader {
return &OutputReader{cfg: cfg, getter: getter}
}

func (g *OutputReader) Handle(
_ context.Context, _ []string, _ io.Writer, _ contracts.ExecutorOptions,
) (int, error) {
return 0, nil
}

type commandSender interface {
SendCommand(ctx context.Context, server *domain.Server, out io.Writer) (domain.Result, error)
}

type CommandSender struct {
cfg *config.Config
sender commandSender
}

func NewCommandSender(cfg *config.Config, sender commandSender) *CommandSender {
return &CommandSender{cfg: cfg, sender: sender}
}

func (g *CommandSender) Handle(
_ context.Context, _ []string, _ io.Writer, _ contracts.ExecutorOptions,
) (int, error) {
return 0, nil
}
8 changes: 7 additions & 1 deletion internal/app/components/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,14 @@ type Executor struct {
appendCommandAndExitCode bool
}

// NewExecutor returns a new executor.
// This configuration of executor will append command and exit code to the output.
func NewExecutor() *Executor {
return &Executor{appendCommandAndExitCode: true}
}

// NewCleanExecutor returns a new executor.
// This configuration of executor will not append command and exit code to the output.
func NewCleanExecutor() *Executor {
return &Executor{appendCommandAndExitCode: false}
}
Expand Down Expand Up @@ -73,7 +77,9 @@ func Exec(ctx context.Context, command string, options contracts.ExecutorOptions
}

//nolint:lll,funlen
func ExecWithWriter(ctx context.Context, command string, out io.Writer, options contracts.ExecutorOptions) (int, error) {
func ExecWithWriter(
ctx context.Context, command string, out io.Writer, options contracts.ExecutorOptions,
) (int, error) {
if command == "" {
return invalidResult, ErrEmptyCommand
}
Expand Down
66 changes: 14 additions & 52 deletions internal/app/components/extendable_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@ package components
import (
"context"
"io"
"os"
"path/filepath"
"sync"

"github.com/gameap/daemon/internal/app/config"
"github.com/gameap/daemon/internal/app/contracts"
"github.com/gopherclass/go-shellquote"
"github.com/hashicorp/go-getter"
"github.com/pkg/errors"
)

type CommandHandler func(
Expand All @@ -23,30 +19,24 @@ type CommandHandler func(
type CommandsHandlers map[string]CommandHandler

type ExtendableExecutor struct {
handlers CommandsHandlers
innerExecutor contracts.Executor
}

func NewDefaultExtendableExecutor(cfg *config.Config) *ExtendableExecutor {
getTool := &GetTool{cfg: cfg}
mu sync.RWMutex
handlers CommandsHandlers
}

func NewDefaultExtendableExecutor(executor contracts.Executor) *ExtendableExecutor {
return &ExtendableExecutor{
handlers: CommandsHandlers{
"get-tool": getTool.Handle,
},
innerExecutor: NewExecutor(),
handlers: make(CommandsHandlers),
innerExecutor: executor,
}
}

func NewCleanDefaultExtendableExecutor(cfg *config.Config) *ExtendableExecutor {
getTool := &GetTool{cfg: cfg}
func (executor *ExtendableExecutor) RegisterHandler(command string, handler CommandHandler) {
executor.mu.Lock()
defer executor.mu.Unlock()

return &ExtendableExecutor{
handlers: CommandsHandlers{
"get-tool": getTool.Handle,
},
innerExecutor: NewCleanExecutor(),
}
executor.handlers[command] = handler
}

func (executor *ExtendableExecutor) Exec(
Expand Down Expand Up @@ -90,41 +80,13 @@ func (executor *ExtendableExecutor) ExecWithWriter(

handleCommand := args[0]

executor.mu.RLock()
handler, exists := executor.handlers[handleCommand]
executor.mu.RUnlock()

if !exists {
return executor.innerExecutor.ExecWithWriter(ctx, command, out, options)
}

return handler(ctx, args[1:], out, options)
}

type GetTool struct {
cfg *config.Config
}

func (g *GetTool) Handle(ctx context.Context, args []string, out io.Writer, _ contracts.ExecutorOptions) (int, error) {
source := args[0]
fileName := filepath.Base(source)
destination := filepath.Join(g.cfg.ToolsPath, fileName)

c := getter.Client{
Ctx: ctx,
Src: args[0],
Dst: destination,
Mode: getter.ClientModeFile,
}

_, _ = out.Write([]byte("Getting tool from " + source + " to " + destination + " ..."))
err := c.Get()
if err != nil {
return errorResult, errors.WithMessage(err, "[components.GetTool] failed to get tool")
}

err = os.Chmod(destination, 0700)
if err != nil {
_, _ = out.Write([]byte("Failed to chmod tool"))
return errorResult, errors.WithMessage(err, "[components.GetTool] failed to chmod tool")
}

return successResult, nil
}
8 changes: 2 additions & 6 deletions internal/app/components/extendable_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"testing"

"github.com/gameap/daemon/internal/app/components"
"github.com/gameap/daemon/internal/app/config"
"github.com/gameap/daemon/internal/app/contracts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -22,10 +21,7 @@ func TestExtendableExecutor_ExecGetTool_ExpectToolDownloaded(t *testing.T) {
t.Log(err)
}
}(tmpDir)
cfg := &config.Config{
ToolsPath: tmpDir,
}
executor := components.NewCleanDefaultExtendableExecutor(cfg)
executor := components.NewDefaultExtendableExecutor(components.NewCleanExecutor())

result, code, err := executor.Exec(
context.Background(),
Expand Down Expand Up @@ -55,7 +51,7 @@ func TestExtendableExecutor_ExecEchoCommand_ExpectCommandExecuted(t *testing.T)
t.Log(err)
}
}(tmpDir)
executor := components.NewCleanDefaultExtendableExecutor(&config.Config{})
executor := components.NewDefaultExtendableExecutor(components.NewCleanExecutor())

result, code, err := executor.Exec(
context.Background(),
Expand Down
12 changes: 8 additions & 4 deletions internal/app/di/internal/container.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
// Code generated by DIGEN; DO NOT EDIT.
// This file was generated by Dependency Injection Container Generator 0.0.3 (built at 2021-10-18T18:27:06Z).
// See docs at https://github.com/strider2038/digen

package internal

import (
"context"

"github.com/gameap/daemon/internal/app/config"
"github.com/gameap/daemon/internal/app/contracts"
gameservercommands "github.com/gameap/daemon/internal/app/game_server_commands"
Expand Down Expand Up @@ -123,6 +120,13 @@ func (c *ServicesContainer) Executor(ctx context.Context) contracts.Executor {
return c.executor
}

func (c *ServicesContainer) ExtendableExecutor(ctx context.Context) contracts.Executor {
if c.executor == nil && c.err == nil {
c.executor = definitions.CreateServiceExtendableExecutor(ctx, c)
}
return c.executor
}

func (c *ServicesContainer) ProcessManager(ctx context.Context) contracts.ProcessManager {
if c.processManager == nil && c.err == nil {
c.processManager = definitions.CreateServicesProcessManager(ctx, c)
Expand Down
1 change: 1 addition & 0 deletions internal/app/di/internal/definitions/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
func CreateProcessRunner(ctx context.Context, c Container) *services.Runner {
processRunner, err := services.NewProcessRunner(
c.Cfg(ctx),
c.Services().Executor(ctx),
c.ServerCommandFactory(ctx),
c.Services().ApiCaller(ctx),
c.Services().GdTaskManager(ctx),
Expand Down
1 change: 1 addition & 0 deletions internal/app/di/internal/definitions/contracts.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 12 additions & 3 deletions internal/app/di/internal/definitions/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/gameap/daemon/internal/app/components"
"github.com/gameap/daemon/internal/app/components/custom_handlers"
"github.com/gameap/daemon/internal/app/contracts"
gdaemonscheduler "github.com/gameap/daemon/internal/app/gdaemon_scheduler"
"github.com/gameap/daemon/internal/app/services"
Expand Down Expand Up @@ -47,8 +48,16 @@ func CreateServicesApiCaller(ctx context.Context, c Container) contracts.APIRequ
return client
}

func CreateServicesExecutor(ctx context.Context, c Container) contracts.Executor {
return components.NewDefaultExtendableExecutor(c.Cfg(ctx))
func CreateServicesExecutor(_ context.Context, _ Container) contracts.Executor {
return components.NewExecutor()
}

func CreateServiceExtendableExecutor(ctx context.Context, c Container) contracts.Executor {
executor := components.NewDefaultExtendableExecutor(c.Services().Executor(ctx))

executor.RegisterHandler("get-tool", custom_handlers.NewGetTool(c.Cfg(ctx)).Handle)

return executor
}

func CreateServicesProcessManager(ctx context.Context, c Container) contracts.ProcessManager {
Expand All @@ -63,7 +72,7 @@ func CreateServicesGdTaskManager(ctx context.Context, c Container) *gdaemonsched
c.Repositories().GdTaskRepository(ctx),
c.CacheManager(ctx),
c.ServerCommandFactory(ctx),
c.Services().Executor(ctx),
c.Services().ExtendableExecutor(ctx),
c.Cfg(ctx),
)
}
13 changes: 8 additions & 5 deletions internal/app/server/commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@ import (
"io"

"github.com/et-nik/binngo/decode"
"github.com/gameap/daemon/internal/app/components"
"github.com/gameap/daemon/internal/app/contracts"
"github.com/gameap/daemon/internal/app/server/response"
"github.com/gameap/daemon/pkg/logger"
"github.com/pkg/errors"
)

type Commands struct{}
type Commands struct {
executor contracts.Executor
}

func NewCommands() *Commands {
return &Commands{}
func NewCommands(executor contracts.Executor) *Commands {
return &Commands{
executor: executor,
}
}

func (c *Commands) Handle(ctx context.Context, readWriter io.ReadWriter) error {
Expand All @@ -38,7 +41,7 @@ func (c *Commands) Handle(ctx context.Context, readWriter io.ReadWriter) error {
func (c Commands) executeCommand(ctx context.Context, msg commandExec, writer io.Writer) error {
logger.WithField(ctx, "command", msg.Command).Debug("Executing command")

out, exitCode, err := components.Exec(ctx, msg.Command, contracts.ExecutorOptions{
out, exitCode, err := c.executor.Exec(ctx, msg.Command, contracts.ExecutorOptions{
WorkDir: msg.WorkDir,
})

Expand Down
Loading

0 comments on commit 65d75a4

Please sign in to comment.