/
docker.go
106 lines (92 loc) · 2.35 KB
/
docker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package commands
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/errdefs"
"github.com/docker/go-connections/nat"
"github.com/spf13/cobra"
)
var (
imageName = "trizlybear/discless:latest"
ip string
port string
)
var StartCmd = &cobra.Command{
Use: "start",
Short: "Start the Discless background daemon",
RunE: StartDaemon,
}
var StopCmd = &cobra.Command{
Use: "stop",
Short: "Stop the Discless background daemon",
RunE: StopDaemon,
}
func IStart() {
StartCmd.Flags().StringVarP(&ip,"ip","i","localhost","set the ip for the docker daemon to run on")
StartCmd.Flags().StringVarP(&port,"port","p","8443","set the port for the docker daemon to run on")
}
func StartDaemon(c *cobra.Command, args []string) error {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
_, err = cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
if err != nil {
return err
}
// io.Copy(os.Stdout, out)
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: imageName,
ExposedPorts: nat.PortSet{
"8443/tcp": struct{}{},
},
}, &container.HostConfig{
PortBindings: nat.PortMap{
"8443/tcp": []nat.PortBinding{
{
HostIP: ip,
HostPort: port,
},
},
},
}, nil, nil, "")
if err != nil {
return err
}
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
if errdefs.Conflict(err) != nil {
fmt.Println("❌ Docker daemon is already running.")
return nil
} else {
return err
}
}
fmt.Println("✅ Succesfully started Docker daemon.")
return nil
}
func StopDaemon(c *cobra.Command, args []string) error {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
if err != nil {
panic(err)
}
for _, container := range containers {
if container.Image == imageName {
if err := cli.ContainerStop(ctx, container.ID, nil); err != nil {
return err
}
fmt.Println("✅ Succesfully stopped docker daemon.")
return nil
}
}
fmt.Println("❌ Couldn't find a running daemon.")
return nil
}