github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/test/docker/vault/vault_container.deprecated.go (about) 1 package vault 2 3 /* 4 import ( 5 "context" 6 "fmt" 7 "time" 8 9 dockertypes "github.com/docker/docker/api/types" 10 "github.com/docker/docker/api/types/container" 11 "github.com/docker/docker/api/types/network" 12 docker "github.com/docker/docker/client" 13 "github.com/docker/go-connections/nat" 14 "github.com/google/uuid" 15 v1 "github.com/opencontainers/image-spec/specs-go/v1" 16 ) 17 18 type Container struct { 19 Image string 20 Cmd []string 21 containerID string 22 } 23 24 func (t *Container) Run(ctx context.Context) error { 25 cli, err := docker.NewEnvClient() 26 if err != nil { 27 return err 28 } 29 30 containerConfig := &container.Config{ 31 Image: t.Image, 32 Cmd: t.Cmd, 33 } 34 35 hostConfig := &container.HostConfig{ 36 PublishAllPorts: true, 37 } 38 39 networkConfig := &network.NetworkingConfig{} 40 41 status, err := cli.ImagePull(ctx, containerConfig.Image, dockertypes.ImagePullOptions{}) 42 if err != nil { 43 return fmt.Errorf("unable to pull image: %v", err) 44 } 45 status.Close() 46 47 guid, _ := uuid.NewRandom() 48 containerName := fmt.Sprintf("vault-%s", guid.String()) 49 50 c, err := cli.ContainerCreate(ctx, containerConfig, hostConfig, networkConfig, &v1.Platform{ 51 OS: "linux", 52 Architecture: "amd64", 53 }, containerName) 54 if err != nil { 55 return fmt.Errorf("unable to create container: %v", err) 56 } 57 58 t.containerID = c.ID 59 err = cli.ContainerStart(ctx, c.ID, dockertypes.ContainerStartOptions{}) 60 if err != nil { 61 return err 62 } 63 64 return nil 65 } 66 67 func (t *Container) GetPort(ctx context.Context, port string) (string, error) { 68 cli, err := docker.NewEnvClient() 69 if err != nil { 70 return "", err 71 } 72 73 data, err := cli.ContainerInspect(ctx, t.containerID) 74 if err != nil { 75 return "", err 76 } 77 78 ports := data.NetworkSettings.Ports 79 hostPort := ports[nat.Port(port)][0].HostPort 80 81 return hostPort, nil 82 } 83 84 func (t *Container) Stop(ctx context.Context) error { 85 cli, err := docker.NewEnvClient() 86 if err != nil { 87 return err 88 } 89 90 err = cli.ContainerKill(ctx, t.containerID, "SIGKILL") 91 if err != nil { 92 return fmt.Errorf("error killing container %s: %v", t.containerID, err) 93 } 94 95 toCtx, _ := context.WithTimeout(ctx, 1*time.Second) 96 _, _ = cli.ContainerWait(toCtx, t.containerID, container.WaitConditionRemoved) 97 // if err != nil { 98 // return err 99 // } 100 101 err = cli.ContainerRemove(ctx, t.containerID, dockertypes.ContainerRemoveOptions{}) 102 if err != nil { 103 return fmt.Errorf("error removing container %s: %v", t.containerID, err) 104 } 105 return nil 106 } 107 */