octopush/internal/actions/builders/docker.go

96 lines
1.9 KiB
Go
Raw Normal View History

2022-09-18 00:21:23 +02:00
package builders
import (
"context"
2022-09-18 00:53:41 +02:00
"crypto/rand"
"encoding/hex"
2022-09-18 00:21:23 +02:00
"errors"
"fmt"
"os"
"os/exec"
"go.uber.org/zap"
2022-09-18 00:53:41 +02:00
"go.uber.org/zap/zapio"
2022-09-18 00:21:23 +02:00
)
type DockerBuild struct {
logger *zap.Logger
}
2022-09-18 00:53:41 +02:00
func NewDockerBuild(logger *zap.Logger) *DockerBuild {
return &DockerBuild{logger: logger}
2022-09-18 00:21:23 +02:00
}
type DockerRunCommand func(ctx context.Context, victimPath string) error
func (g *DockerBuild) Build(ctx context.Context, modulePath, entryPath string) (DockerRunCommand, error) {
g.logger.Debug("Building docker image", zap.String("actiondir", modulePath), zap.String("entry", entryPath))
if _, err := os.Stat(fmt.Sprintf("%s/%s", modulePath, entryPath)); os.IsNotExist(err) {
return nil, errors.New("could not find entry")
}
2022-09-18 00:53:41 +02:00
b := make([]byte, 20)
_, err := rand.Reader.Read(b)
if err != nil {
return nil, err
}
tag := hex.EncodeToString(b)
buildDockerCmd := fmt.Sprintf("(cd %s; docker build -f %s --tag kraken/%s .)", modulePath, entryPath, tag)
g.logger.Debug("Running command", zap.String("command", buildDockerCmd))
cmd := exec.CommandContext(
ctx,
"/bin/bash",
"-c",
buildDockerCmd,
)
debugwriter := &zapio.Writer{
Log: g.logger,
Level: zap.DebugLevel,
}
defer debugwriter.Close()
cmd.Stdout = debugwriter
cmd.Stderr = debugwriter
err = cmd.Start()
if err != nil {
return nil, err
}
err = cmd.Wait()
if err != nil {
return nil, err
}
g.logger.Debug("Docker image built!")
2022-09-18 00:21:23 +02:00
return func(ctx context.Context, victimPath string) error {
g.logger.Debug("Executing script", zap.String("victim", victimPath))
cmd := exec.CommandContext(
ctx,
"/bin/bash",
"-c",
2022-09-18 00:53:41 +02:00
fmt.Sprintf("docker run --rm -v %s/:/src/work/ kraken/%s", victimPath, tag),
2022-09-18 00:21:23 +02:00
)
2022-09-18 00:53:41 +02:00
runDockerWriter := &zapio.Writer{
Log: g.logger,
Level: zap.DebugLevel,
}
defer runDockerWriter.Close()
cmd.Stdout = runDockerWriter
cmd.Stderr = runDockerWriter
err = cmd.Start()
if err != nil {
return err
}
return cmd.Wait()
2022-09-18 00:21:23 +02:00
}, nil
}