docker-db-backup/save.go

50 lines
1014 B
Go
Raw Normal View History

2021-08-18 19:29:17 +00:00
package main
import (
"context"
2021-08-18 19:29:17 +00:00
"fmt"
2021-12-05 12:24:06 +00:00
"io"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
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()
f, err := os.Create(filename)
2021-12-05 12:24:06 +00:00
if err != nil {
return err
}
defer f.Close()
2021-08-18 19:29:17 +00:00
_, err = io.Copy(f, resp.Reader)
2021-08-18 19:29:17 +00:00
if err != nil {
return err
}
execInspect, err := c.ContainerExecInspect(ctx, r.ID)
if execInspect.ExitCode != 0 {
return fmt.Errorf("backup from container %s failed with exit code %d", container.Name, execInspect.ExitCode)
2021-12-05 10:48:28 +00:00
}
2021-12-05 12:24:06 +00:00
return err
2021-08-18 19:29:17 +00:00
}