Skip to content

Commit

Permalink
have log be optional and add context by default for rin in cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
runz0rd committed Oct 18, 2021
1 parent b7887ee commit e9a92b7
Show file tree
Hide file tree
Showing 11 changed files with 127 additions and 126 deletions.
24 changes: 14 additions & 10 deletions delve.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ import (

const delveBin = "dlv"

func (g Grapple) Delve(pod, container, sourcePath string, binArgs []string, host string, port int, delveContinue, vscode bool) error {
func (g Grapple) Delve(pod, container, sourcePath string, binArgs []string, host string,
port int, delveContinue, vscode bool) error {
validateCtx := context.Background()
// validate k8s resources for delve session
if err := g.kubeCmd.ValidatePod(g.deployment, &pod); err != nil {
if err := g.kubeCmd.ValidatePod(validateCtx, g.deployment, &pod); err != nil {
return err
}
if err := g.kubeCmd.ValidateContainer(g.deployment, &container); err != nil {
Expand All @@ -29,7 +31,8 @@ func (g Grapple) Delve(pod, container, sourcePath string, binArgs []string, host
// populate bin args if empty
if len(binArgs) == 0 {
var err error
d, err := g.kubeCmd.GetDeploymentFromConfigMap(g.DeploymentConfigMapName(), defaultConfigMapDeploymentKey)
d, err := g.kubeCmd.GetDeploymentFromConfigMap(validateCtx, g.DeploymentConfigMapName(),
defaultConfigMapDeploymentKey)
if err != nil {
return err
}
Expand Down Expand Up @@ -98,19 +101,19 @@ func (g Grapple) binDestination() string {

func (g Grapple) cleanupPIDs(ctx context.Context, pod, container string) error {
// get pids of delve and app were debugging
binPids, errBinPids := g.kubeCmd.GetPIDsOf(pod, container, g.binName())
binPids, errBinPids := g.kubeCmd.GetPIDsOf(ctx, pod, container, g.binName())
if errBinPids != nil {
return errBinPids
}
delvePids, errDelvePids := g.kubeCmd.GetPIDsOf(pod, container, delveBin)
delvePids, errDelvePids := g.kubeCmd.GetPIDsOf(ctx, pod, container, delveBin)
if errDelvePids != nil {
return errDelvePids
}
// kill pids directly on pod container
maxTries := 10
pids := append(binPids, delvePids...)
return tryCallWithContext(ctx, maxTries, time.Millisecond*200, func(i int) error {
killErrs := g.kubeCmd.KillPidsOnPod(pod, container, pids, true)
killErrs := g.kubeCmd.KillPidsOnPod(ctx, pod, container, pids, true)
if len(killErrs) == 0 {
return nil
}
Expand All @@ -132,28 +135,29 @@ func (g Grapple) deployBin(ctx context.Context, pod, container, goModPath, sourc
} else {
for _, file := range files {
if path.Ext(file.Name()) == ".go" {
relInputs = append(relInputs, strings.TrimPrefix(path.Join(sourcePath, file.Name()), goModPath+string(filepath.Separator)))
relInputs = append(relInputs, strings.TrimPrefix(path.Join(sourcePath,
file.Name()), goModPath+string(filepath.Separator)))
}
}
}
} else {
relInputs = append(relInputs, strings.TrimPrefix(sourcePath, goModPath+string(filepath.Separator)))
}

_, errBuild := g.goCmd.Build(goModPath, binSource, relInputs, `-gcflags="all=-N -l"`).Env("GOOS=linux").RunCtx(ctx)
_, errBuild := g.goCmd.Build(goModPath, binSource, relInputs, `-gcflags="all=-N -l"`).Env("GOOS=linux").Run(ctx)
if errBuild != nil {
return errBuild
}
// copy bin to pod
_, errCopyToPod := g.kubeCmd.CopyToPod(pod, container, binSource, g.binDestination()).RunCtx(ctx)
_, errCopyToPod := g.kubeCmd.CopyToPod(pod, container, binSource, g.binDestination()).Run(ctx)
return errCopyToPod
}

func (g Grapple) portForwardDelve(l *logrus.Entry, ctx context.Context, pod, host string, port int) {
l.Info("port-forwarding pod for delve server")
cmd := g.kubeCmd.PortForwardPod(pod, host, port)
go func() {
_, err := cmd.RunCtx(ctx)
_, err := cmd.Run(ctx)
if err != nil && err.Error() != "signal: killed" {
l.WithError(err).Errorf("port-forwarding %v pod failed", pod)
}
Expand Down
8 changes: 4 additions & 4 deletions delve/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ func (kds KubeDelveServer) Port() int {
}

func NewKubeDelveServer(l *logrus.Entry, namespace, host string, port int) *KubeDelveServer {
kubectl := exec.NewKubectlCommand(l)
kubectl.Args("-n", namespace)
kubectl := exec.NewKubectlCommand()
kubectl.Logger(l).Args("-n", namespace)
return &KubeDelveServer{host, port, kubectl, nil}
}

Expand All @@ -38,7 +38,7 @@ func (kds *KubeDelveServer) StartNoWait(ctx context.Context, pod, container stri
func(p *os.Process) error {
kds.process = p
return nil
}).NoWait().RunCtx(ctx)
}).NoWait().Run(ctx)
<-cmd.Started()
}

Expand All @@ -50,7 +50,7 @@ func (kds *KubeDelveServer) Start(ctx context.Context, pod, container string, bi
func(p *os.Process) error {
kds.process = p
return nil
}).RunCtx(ctx)
}).Run(ctx)
return errors.WithMessage(err, out)
}

Expand Down
54 changes: 22 additions & 32 deletions exec/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"io"
"os"
goexec "os/exec"
"time"

"github.com/sirupsen/logrus"
)
Expand All @@ -21,17 +20,16 @@ type Cmd struct {
stdoutWriters []io.Writer
stderrWriters []io.Writer
wait bool
t time.Duration
// t time.Duration
preStartFunc func() error
postStartFunc func(p *os.Process) error
postEndFunc func() error
chanStarted chan struct{}
chanDone chan struct{}
}

func NewCommand(l *logrus.Entry, name string) *Cmd {
func NewCommand(name string) *Cmd {
return &Cmd{
l: l,
command: []string{name},
wait: true,
env: os.Environ(),
Expand Down Expand Up @@ -85,11 +83,6 @@ func (c *Cmd) Stderr(w io.Writer) *Cmd {
return c
}

func (c *Cmd) Timeout(t time.Duration) *Cmd {
c.t = t
return c
}

func (c *Cmd) NoWait() *Cmd {
c.wait = false
return c
Expand All @@ -110,20 +103,25 @@ func (c *Cmd) PostEnd(f func() error) *Cmd {
return c
}

func (c *Cmd) Started() <-chan struct{} {
return c.chanStarted
func (c *Cmd) Logger(l *logrus.Entry) *Cmd {
c.l = l
return c
}

func (c *Cmd) Done() <-chan struct{} {
return c.chanDone
// func (c *Cmd) Run() (string, error) {
// return c.run(goexec.Command(c.command[0], c.command[1:]...))
// }

func (c *Cmd) Run(ctx context.Context) (string, error) {
return c.run(goexec.CommandContext(ctx, c.command[0], c.command[1:]...))
}

func (c *Cmd) Run() (string, error) {
return c.run(goexec.Command(c.command[0], c.command[1:]...))
func (c *Cmd) Started() <-chan struct{} {
return c.chanStarted
}

func (c *Cmd) RunCtx(ctx context.Context) (string, error) {
return c.run(goexec.CommandContext(ctx, c.command[0], c.command[1:]...))
func (c *Cmd) Done() <-chan struct{} {
return c.chanDone
}

func (c *Cmd) run(cmd *goexec.Cmd) (string, error) {
Expand All @@ -134,11 +132,12 @@ func (c *Cmd) run(cmd *goexec.Cmd) (string, error) {
c.l.Tracef("executing %q", cmd.String())

combinedBuf := new(bytes.Buffer)
traceWriter := c.l.WriterLevel(logrus.TraceLevel)
warnWriter := c.l.WriterLevel(logrus.WarnLevel)

c.stdoutWriters = append(c.stdoutWriters, combinedBuf, traceWriter)
c.stderrWriters = append(c.stderrWriters, combinedBuf, warnWriter)
if c.l != nil {
traceWriter := c.l.WriterLevel(logrus.TraceLevel)
warnWriter := c.l.WriterLevel(logrus.WarnLevel)
c.stdoutWriters = append(c.stdoutWriters, combinedBuf, traceWriter)
c.stderrWriters = append(c.stderrWriters, combinedBuf, warnWriter)
}
cmd.Stdout = io.MultiWriter(c.stdoutWriters...)
cmd.Stderr = io.MultiWriter(c.stderrWriters...)

Expand All @@ -163,17 +162,8 @@ func (c *Cmd) run(cmd *goexec.Cmd) (string, error) {
}()

if c.wait {
if c.t != 0 {
timer := time.AfterFunc(c.t, func() {
cmd.Process.Kill()
})
defer timer.Stop()
}

if err := cmd.Wait(); err != nil {
if c.t == 0 {
return "", err
}
return "", err
}
if c.postEndFunc != nil {
if err := c.postEndFunc(); err != nil {
Expand Down
10 changes: 4 additions & 6 deletions exec/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,20 @@ package exec

import (
"fmt"

"github.com/sirupsen/logrus"
)

type DockerCmd struct {
Cmd
}

func NewDockerCommand(l *logrus.Entry) *DockerCmd {
return &DockerCmd{*NewCommand(l, "docker")}
func NewDockerCommand() *DockerCmd {
return &DockerCmd{*NewCommand("docker")}
}

func (c DockerCmd) Build(workDir string, options ...string) *Cmd {
return c.Args("build", workDir).Args(options...)
}

func (c DockerCmd) Push(image, tag string, options ...string) (string, error) {
return c.Args("push", fmt.Sprintf("%v:%v", image, tag)).Args(options...).Run()
func (c DockerCmd) Push(image, tag string, options ...string) *Cmd {
return c.Args("push", fmt.Sprintf("%v:%v", image, tag)).Args(options...)
}
8 changes: 2 additions & 6 deletions exec/go.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package exec

import (
"github.com/sirupsen/logrus"
)

type GoCmd struct {
Cmd
}

func NewGoCommand(l *logrus.Entry) *GoCmd {
return &GoCmd{*NewCommand(l, "go")}
func NewGoCommand() *GoCmd {
return &GoCmd{*NewCommand("go")}
}

func (c GoCmd) Build(workDir, output string, inputs []string, flags ...string) *Cmd {
Expand Down
Loading

0 comments on commit e9a92b7

Please sign in to comment.