docker-db-backup/save.go

64 lines
1.2 KiB
Go
Raw Normal View History

2021-08-18 19:29:17 +00:00
package main
import (
2021-12-05 10:48:28 +00:00
"bytes"
"context"
2021-08-18 19:29:17 +00:00
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
2021-12-05 12:24:06 +00:00
"io"
"os"
)
2021-08-18 19:29:17 +00:00
func runAndSaveCommandInContainer(filename string, c *client.Client, container *types.ContainerJSON, command string, args ...string) error {
ctx := context.Background()
config := types.ExecConfig{
AttachStderr: true,
AttachStdout: true,
Cmd: append([]string{command}, args...),
}
r, err := c.ContainerExecCreate(ctx, container.ID, config)
2021-08-18 19:29:17 +00:00
if err != nil {
return err
}
resp, err := c.ContainerExecAttach(ctx, r.ID, types.ExecStartCheck{})
2021-08-18 19:29:17 +00:00
if err != nil {
return err
}
defer resp.Close()
// 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
}()
2021-12-05 12:24:06 +00:00
err = <-outputDone
if err != nil {
fmt.Printf(errBuf.String())
return err
}
2021-08-18 19:29:17 +00:00
_, err = c.ContainerExecInspect(ctx, r.ID)
2021-08-18 19:29:17 +00:00
if err != nil {
return err
}
2021-12-05 12:24:06 +00:00
f, err := os.Create(filename)
2021-12-05 10:48:28 +00:00
if err != nil {
return err
}
2021-12-05 12:24:06 +00:00
defer f.Close()
2021-12-05 10:48:28 +00:00
2021-12-05 12:24:06 +00:00
_, err = io.Copy(f, &outBuf)
return err
2021-08-18 19:29:17 +00:00
}