docker.go 4.56 KB
Newer Older
Addshore's avatar
Addshore committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*Package mwdd is used to interact a mwdd v2 setup

Copyright © 2020 Addshore

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package mwdd

import (
	"context"
	"fmt"
	"io"
	"os"
25
	gosignal "os/signal"
26
	"runtime"
Addshore's avatar
Addshore committed
27
28
29
30
31
	"time"

	"gerrit.wikimedia.org/r/mediawiki/tools/cli/internal/exec"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
32
	"github.com/docker/docker/pkg/signal"
Addshore's avatar
Addshore committed
33
34
35
36
37
	"golang.org/x/crypto/ssh/terminal"
)

// DockerExecCommand to be run with Docker, which directly uses the docker SDK
type DockerExecCommand struct {
Addshore's avatar
Addshore committed
38
39
40
41
42
	DockerComposeService string
	Command              []string
	WorkingDir           string
	User                 string
	HandlerOptions       exec.HandlerOptions
Addshore's avatar
Addshore committed
43
44
}

45
46
/*UserAndGroupForDockerExecution gets a user and group id combination for the current user that can be used for execution*/
func UserAndGroupForDockerExecution() string {
Addshore's avatar
Addshore committed
47
	if runtime.GOOS == "windows" {
48
49
50
51
52
53
54
		// TODO confirm that just using 2000 will always work on Windows?
		// This user won't exist, but that fact doesn't really matter on pure Windows
		return "2000:2000"
	}
	return fmt.Sprint(os.Getuid(), ":", os.Getgid())
}

Addshore's avatar
Addshore committed
55
/*DockerExec runs a docker exec command using the docker SDK*/
Addshore's avatar
Addshore committed
56
func (m MWDD) DockerExec(command DockerExecCommand) {
Addshore's avatar
Addshore committed
57
58
59
60
61
62
63
64
	containerID := m.DockerComposeProjectName() + "_" + command.DockerComposeService + "_1"

	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		fmt.Println("Unable to create docker client")
		panic(err)
	}

65
	execConfig := types.ExecConfig{
Addshore's avatar
Addshore committed
66
67
		AttachStderr: true,
		AttachStdout: true,
Addshore's avatar
Addshore committed
68
69
70
71
72
		AttachStdin:  true,
		Tty:          true,
		WorkingDir:   command.WorkingDir,
		User:         command.User,
		Cmd:          command.Command,
Addshore's avatar
Addshore committed
73
74
75
	}

	ctx := context.Background()
76
	response, err := cli.ContainerExecCreate(ctx, containerID, execConfig)
Addshore's avatar
Addshore committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
	if err != nil {
		return
	}

	execID := response.ID
	if execID == "" {
		fmt.Println("exec ID empty")
		return
	}

	execStartCheck := types.ExecStartCheck{
		Tty: true,
	}

	waiter, err := cli.ContainerExecAttach(ctx, execID, execStartCheck)
	if err != nil {
		fmt.Println(err)
		return
	}

97
98
99
100
101
102
103
	if execConfig.Tty {
		if err := monitorTtySize(ctx, cli, execID, true); err != nil {
			fmt.Println("Error monitoring TTY size:")
			fmt.Println(err)
		}
	}

104
105
	// When TTY is ON, just copy stdout https://phabricator.wikimedia.org/T282340
	// See: https://github.com/docker/cli/blob/70a00157f161b109be77cd4f30ce0662bfe8cc32/cli/command/container/hijack.go#L121-L130
Addshore's avatar
Addshore committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
	go io.Copy(os.Stdout, waiter.Reader)
	go io.Copy(waiter.Conn, os.Stdin)

	fd := int(os.Stdin.Fd())
	var oldState *terminal.State
	if terminal.IsTerminal(fd) {
		oldState, err = terminal.MakeRaw(fd)
		if err != nil {
			// print error
		}
		defer terminal.Restore(fd, oldState)
	}

	for {
		resp, err := cli.ContainerExecInspect(ctx, execID)
		time.Sleep(50 * time.Millisecond)
		if err != nil {
			break
		}

		if !resp.Running {
			break
		}
	}
}
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

// MonitorTtySize updates the container tty size when the terminal tty changes size
func monitorTtySize(ctx context.Context, client client.APIClient, id string, isExec bool) error {
	// Source: https://github.com/skiffos/skiff-core/blob/82c430e4961453c250883c2e5ebd4bd360fa13a5/shell/tty.go
	resizeTty := func() {
		width, height, _ := terminal.GetSize(0)
		resizeTtyTo(ctx, client, id, uint(height), uint(width), isExec)
	}

	resizeTty()

	sigchan := make(chan os.Signal, 1)
	gosignal.Notify(sigchan, signal.SIGWINCH)
	go func() {
		for range sigchan {
			resizeTty()
		}
	}()

	return nil
}

func resizeTtyTo(ctx context.Context, client client.ContainerAPIClient, id string, height, width uint, isExec bool) {
	// Source: https://github.com/skiffos/skiff-core/blob/82c430e4961453c250883c2e5ebd4bd360fa13a5/shell/tty.go
	if height == 0 && width == 0 {
		return
	}

	options := types.ResizeOptions{
		Height: height,
		Width:  width,
	}

	var err error
	if isExec {
		err = client.ContainerExecResize(ctx, id, options)
	} else {
		err = client.ContainerResize(ctx, id, options)
	}

	_ = err // Ignore this error for now.
	/*
		if err != nil {
		}
	*/
}