mirror of
https://kolaente.dev/konrad/docker-db-backup.git
synced 2026-01-10 02:50:08 +01:00
feat: move running the actual dump command to the db container
This commit is contained in:
55
save.go
55
save.go
@@ -2,44 +2,71 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/client"
|
||||
"github.com/docker/docker/pkg/stdcopy"
|
||||
)
|
||||
|
||||
func runAndSaveCommand(filename, command string, args ...string) error {
|
||||
c := exec.Command(command, args...)
|
||||
|
||||
//fmt.Printf("Running %s\n\n", c.String())
|
||||
|
||||
func runAndSaveCommandInContainer(filename string, c *client.Client, container *types.ContainerJSON, command string, args ...string) error {
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
stdout, err := c.StdoutPipe()
|
||||
ctx := context.Background()
|
||||
|
||||
config := types.ExecConfig{
|
||||
AttachStderr: true,
|
||||
AttachStdout: true,
|
||||
Cmd: append([]string{command}, args...),
|
||||
}
|
||||
|
||||
r, err := c.ContainerExecCreate(ctx, container.ID, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var stderr bytes.Buffer
|
||||
c.Stderr = &stderr
|
||||
|
||||
err = c.Start()
|
||||
resp, err := c.ContainerExecAttach(ctx, r.ID, types.ExecStartCheck{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Close()
|
||||
|
||||
_, err = io.Copy(f, stdout)
|
||||
// read the output
|
||||
var outBuf, errBuf bytes.Buffer
|
||||
outputDone := make(chan error)
|
||||
|
||||
go func() {
|
||||
// StdCopy demultiplexes the stream into two buffers
|
||||
_, err = stdcopy.StdCopy(&outBuf, &errBuf, resp.Reader)
|
||||
outputDone <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-outputDone:
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
_, err = c.ContainerExecInspect(ctx, r.ID)
|
||||
if err != nil {
|
||||
fmt.Printf(errBuf.String())
|
||||
return err
|
||||
}
|
||||
|
||||
err = c.Wait()
|
||||
_, err = io.Copy(f, &outBuf)
|
||||
if err != nil {
|
||||
fmt.Printf(stderr.String())
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user