-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
349 lines (321 loc) · 9.52 KB
/
main.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
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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
Copyright (C) 2025 Michael Ablassmeier <[email protected]>
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 main
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/gliderlabs/ssh"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
InfoPrint("%s: %s %s %s ", os.Args[0], version, commit, date)
bindAddress := flag.String("bind", "127.0.0.1:2222", "bind address, 127.0.0.1:2222, use :2222 for all")
dockerEndpoint := flag.String("endpoint", "", "Docker endpoint. Default: use environment settings. Example: tcp://192.168.1.100:2375")
vol := flag.String("vol", "", "Share volume into container, example: /home/:/home_shared")
image := flag.String("image", "", "Force image to be executed")
cmd := flag.String("cmd", "", "Execute cmd after login, example: ls")
exportFolder := flag.String("export", "", "Before removing, export container contents to specified directory, example: /tmp/")
flag.Parse()
if *exportFolder != "" {
*exportFolder = filepath.Clean(*exportFolder)
}
ssh.Handle(func(sess ssh.Session) {
InfoPrint("Connection from: [%s]", sess.RemoteAddr())
var defaultImage = sess.User()
if *image != "" {
InfoPrint("Overriding image with: [%s]", *image)
sess.Write([]byte("Overriding image with: [" + *image + "]\n"))
defaultImage = *image
}
_, _, isTty := sess.Pty()
cfg := &container.Config{
Image: defaultImage,
Env: sess.Environ(),
Tty: isTty,
OpenStdin: true,
AttachStderr: true,
AttachStdin: true,
AttachStdout: true,
StdinOnce: true,
}
shares := []string{}
if *vol != "" {
shares = append(shares, *vol)
}
hostcfg := &container.HostConfig{
Binds: shares,
Tmpfs: map[string]string{
"/tmp": "rw,noexec,nosuid",
"/run": "rw,noexec,nosuid",
"/run/lock": "rw,noexec,nosuid",
},
Mounts: []mount.Mount{
{
Type: mount.TypeBind,
Source: "/sys/fs/cgroup",
Target: "/sys/fs/cgroup",
},
},
CapAdd: []string{"SYS_ADMIN"},
CgroupnsMode: "host",
SecurityOpt: []string{"apparmor=unconfined"},
}
status, cleanup, err := dockerRun(
*dockerEndpoint,
cfg,
hostcfg,
sess,
*cmd,
*exportFolder,
)
defer cleanup()
if err != nil {
sess.Write([]byte("Error executing container: [" + err.Error() + "]\n"))
ErrorPrint("Failed to execute: %s", err.Error())
}
sess.Exit(int(status))
})
InfoPrint("starting ssh server on %s...", *bindAddress)
log.Fatal(ssh.ListenAndServe(*bindAddress, nil))
}
func imageExistsLocally(
ctx context.Context,
imageName string,
cli *client.Client,
) bool {
images, err := cli.ImageList(ctx, image.ListOptions{})
if err != nil {
ErrorPrint("Error listing images: %v", err)
return false
}
// Check if the image exists locally
for _, image := range images {
for _, tag := range image.RepoTags {
if tag == imageName {
return true
}
}
}
return false
}
func waitForContainerReady(
ctx context.Context,
sess ssh.Session,
cli *client.Client,
containerID string,
timeout time.Duration,
) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
containerJSON, err := cli.ContainerInspect(ctx, containerID)
if err != nil {
return fmt.Errorf("error inspecting container: %w", err)
}
// Check if the container is running
if containerJSON.State.Running {
// If a health check is defined, ensure it's healthy
if containerJSON.State.Health != nil {
if containerJSON.State.Health.Status == "healthy" {
InfoPrint("Container %s is running and healthy.", containerID)
return nil
} else if containerJSON.State.Health.Status == "unhealthy" {
return fmt.Errorf("container is unhealthy")
}
} else {
InfoPrint("Container %s is running.", containerID)
return nil
}
}
sess.Write([]byte("Waiting for container to become ready...\n"))
InfoPrint("Waiting for container %s to be ready...", containerID)
time.Sleep(2 * time.Second)
}
return fmt.Errorf("timeout waiting for container to be ready")
}
func dockerRun(
endpoint string,
cfg *container.Config,
hostcfg *container.HostConfig,
sess ssh.Session,
cmd string,
exportFolder string,
) (status int, cleanup func(), err error) {
var docker *client.Client
status = 255
cleanup = func() {}
ctx := context.Background()
useTty := true
cImage := cfg.Image
if endpoint != "" {
docker, err = client.NewClientWithOpts(
client.WithHost(endpoint),
client.WithAPIVersionNegotiation(),
)
} else {
docker, err = client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
}
if err != nil {
panic(err)
}
InfoPrint("Image: %s", cImage)
defaultCmd := []string{"/bin/sh", "-c", "[ -e /bin/bash ] && /bin/bash || /bin/sh"}
if sess.RawCommand() != "" {
defaultCmd = sess.Command()
useTty = false
}
if cmd != "" {
defaultCmd = strings.Fields(cmd)
}
InfoPrint("Executing command: %s", defaultCmd)
networkingConfig := network.NetworkingConfig{}
platformConfig := v1.Platform{
OS: "linux",
Architecture: "amd64",
}
if imageExistsLocally(ctx, cImage, docker) != true {
sess.Write([]byte("Image [" + cImage + "] not found, attempting to fetch from repository ..\n"))
reader, pullerr := docker.ImagePull(ctx, cImage, image.PullOptions{})
if pullerr != nil {
sess.Write([]byte("Unable to pull requested image [" + cImage + "]: [" + string(pullerr.Error()) + "]\n"))
ErrorPrint("Unable to pull requested image [%s]: %v", cImage, pullerr)
cleanup = func() {}
return
}
defer reader.Close()
if _, err := io.Copy(os.Stdout, reader); err != nil {
ErrorPrint("Unable to read pull output: %v", pullerr)
}
}
resp, err := docker.ContainerCreate(ctx, cfg, hostcfg, &networkingConfig, &platformConfig, "")
if err != nil {
ErrorPrint("Unable to create container: %v", err)
return
}
InfoPrint("Created container: %s", resp.ID)
cleanup = func() {
docker.ContainerRemove(ctx, resp.ID, container.RemoveOptions{})
}
startErr := docker.ContainerStart(ctx, resp.ID, container.StartOptions{})
if startErr != nil {
ErrorPrint("Unable to start container: %s", startErr)
sess.Write([]byte("Unable to start requested image: [" + string(startErr.Error()) + "]\n"))
return
}
InfoPrint("Wait for container %s to be ready", resp.ID)
err = waitForContainerReady(ctx, sess, docker, resp.ID, 30*time.Second)
if err != nil {
sess.Write([]byte("Container failed to become ready: [" + err.Error() + "]\n"))
log.Print("Container failed to become ready: ", err)
return
}
execResp, err := docker.ContainerExecCreate(ctx, resp.ID, container.ExecOptions{
Cmd: defaultCmd,
Tty: true,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
})
if err != nil {
ErrorPrint("Error creating container exec: [%s]", err.Error())
return
}
InfoPrint("Attaching container: %s", resp.ID)
stream, err := docker.ContainerExecAttach(ctx, execResp.ID, container.ExecStartOptions{
Tty: useTty,
})
if err != nil {
ErrorPrint("Error during container attach: [%v]", err.Error())
return
}
outputErr := make(chan error)
go func() {
var err error
if cfg.Tty {
_, err = io.Copy(sess, stream.Reader)
} else {
_, err = stdcopy.StdCopy(sess, sess.Stderr(), stream.Reader)
}
outputErr <- err
}()
go func() {
defer stream.CloseWrite()
io.Copy(stream.Conn, sess)
}()
if cfg.Tty {
_, winCh, _ := sess.Pty()
go func() {
for win := range winCh {
err := docker.ContainerResize(ctx, resp.ID, container.ResizeOptions{
Height: uint(win.Height),
Width: uint(win.Width),
})
if err != nil {
ErrorPrint(err.Error())
break
}
}
}()
}
select {
case <-outputErr:
execInspect, ierr := docker.ContainerExecInspect(ctx, execResp.ID)
if ierr != nil {
WarnPrint("Unable to inspect command exit code: %s", err.Error())
}
status = execInspect.ExitCode
InfoPrint("Exit code from specified command: %d", status)
if exportFolder != "" {
InfoPrint("Exporting container to : [%s/%s.tar]", exportFolder, resp.ID)
stream, eErr := docker.ContainerExport(ctx, resp.ID)
if eErr != nil {
WarnPrint("Unable to create export context for container %s: %s", resp.ID, eErr.Error())
}
targetFile, fErr := os.Create(exportFolder + "/" + resp.ID + ".tar")
if fErr != nil {
WarnPrint("Unable to create export file for container %s: %s", resp.ID, fErr.Error())
}
io.Copy(targetFile, stream)
targetFile.Close()
stream.Close()
}
cleanup = func() {
InfoPrint("Killing container: %s", resp.ID)
docker.ContainerKill(ctx, resp.ID, "9")
InfoPrint("Removing container: %s", resp.ID)
docker.ContainerRemove(ctx, resp.ID, container.RemoveOptions{Force: true})
}
return
}
}