mirror of
https://github.com/kolaente/docker-db-backup.git
synced 2026-11-21 10:48:38 +01:00
Non-TTY exec output carries 8-byte frame headers, which were written into dump files and corrupted them. stderr was mixed in as well.
72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/docker/docker/api/types/container"
|
|
"github.com/docker/docker/client"
|
|
"github.com/docker/docker/pkg/stdcopy"
|
|
)
|
|
|
|
func runAndSaveCommandInContainer(c *client.Client, ctr *container.InspectResponse, command string, args ...string) error {
|
|
ctx := context.Background()
|
|
|
|
filename := getDumpFilename(ctr.Name)
|
|
if config.CompressBackups {
|
|
filename += ".gz"
|
|
}
|
|
|
|
execConfig := container.ExecOptions{
|
|
AttachStderr: true,
|
|
AttachStdout: true,
|
|
Cmd: append([]string{command}, args...),
|
|
}
|
|
|
|
r, err := c.ContainerExecCreate(ctx, ctr.ID, execConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := c.ContainerExecAttach(ctx, r.ID, container.ExecStartOptions{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Close()
|
|
|
|
f, err := os.Create(filename)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
var target io.Writer = f
|
|
|
|
if config.CompressBackups {
|
|
gw, err := gzip.NewWriterLevel(f, gzip.BestCompression)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer gw.Close()
|
|
target = gw
|
|
}
|
|
|
|
// Non-TTY exec output is multiplexed with frame headers.
|
|
_, err = stdcopy.StdCopy(target, os.Stderr, resp.Reader)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
execInspect, err := c.ContainerExecInspect(ctx, r.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if execInspect.ExitCode != 0 {
|
|
return fmt.Errorf("backup from container %s failed with exit code %d", ctr.Name, execInspect.ExitCode)
|
|
}
|
|
return err
|
|
}
|