docker-db-backup/save.go

75 lines
1.3 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"
"io"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
)
2021-08-18 19:29:17 +00:00
func runAndSaveCommandInContainer(filename string, c *client.Client, container *types.ContainerJSON, command string, args ...string) error {
2021-08-18 19:29:17 +00:00
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
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
}()
select {
case err := <-outputDone:
if err != nil {
return err
}
break
case <-ctx.Done():
return ctx.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 {
fmt.Printf(errBuf.String())
2021-08-18 19:29:17 +00:00
return err
}
_, err = io.Copy(f, &outBuf)
2021-12-05 10:48:28 +00:00
if err != nil {
return err
}
return nil
2021-08-18 19:29:17 +00:00
}